diff --git a/types/node/fs.d.ts b/types/node/fs.d.ts index f0ae01b17c..140dd08149 100644 --- a/types/node/fs.d.ts +++ b/types/node/fs.d.ts @@ -1,33 +1,2156 @@ -// tslint:disable-next-line:no-bad-reference -/// +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + import { URL } from "url"; + import * as promises from 'fs/promises'; -declare module 'fs' { - interface BigIntStats extends StatsBase { + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + + export type BufferEncodingOption = 'buffer' | { encoding: 'buffer' }; + + export interface BaseEncodingOptions { + encoding?: BufferEncoding | null; } - class BigIntStats { + export type OpenMode = number | string; + + export type Mode = number | string; + + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + export interface Stats extends StatsBase { + } + + export class Stats { + } + + export class Dirent { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + name: string; + } + + /** + * A class representing a directory stream. + */ + export class Dir { + readonly path: string; + + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + */ + close(): Promise; + close(cb: NoParamCallback): void; + + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + */ + closeSync(): void; + + /** + * Asynchronously read the next directory entry via `readdir(3)` as an `Dirent`. + * After the read is completed, a value is returned that will be resolved with an `Dirent`, or `null` if there are no more directory entries to read. + * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + + /** + * Synchronously read the next directory entry via `readdir(3)` as a `Dirent`. + * If there are no more directory entries to read, null will be returned. + * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. + */ + readSync(): Dirent; + } + + export interface FSWatcher extends events.EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + export class ReadStream extends stream.Readable { + close(): void; + bytesRead: number; + path: string | Buffer; + pending: boolean; + + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "ready", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "ready", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export class WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + pending: boolean; + + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + 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: "open", listener: (fd: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "ready", listener: () => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + + /** + * Synchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + export function truncateSync(path: PathLike, len?: number | null): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + + /** + * Synchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + export function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + + /** + * Synchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + + /** + * Synchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function chmodSync(path: PathLike, mode: Mode): void; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + + /** + * Synchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function fchmodSync(fd: number, mode: Mode): void; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + + /** + * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function stat(path: PathLike, options: BigIntOptions, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; + export function stat(path: PathLike, options: StatOptions, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options: BigIntOptions): Promise; + function __promisify__(path: PathLike, options: StatOptions): Promise; + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function statSync(path: PathLike, options: BigIntOptions): BigIntStats; + export function statSync(path: PathLike, options: StatOptions): Stats | BigIntStats; + export function statSync(path: PathLike): Stats; + + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + export function fstatSync(fd: number): Stats; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lstatSync(path: PathLike): Stats; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + + type Type = "dir" | "file" | "junction"; + } + + /** + * Synchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: BaseEncodingOptions | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void + ): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; + } + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: BaseEncodingOptions | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void + ): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; + + function native( + path: PathLike, + options: BaseEncodingOptions | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void + ): void; + function native(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + } + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; + + export namespace realpathSync { + function native(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; + } + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function unlinkSync(path: PathLike): void; + + export interface RmDirOptions { + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, errors are not reported if `path` does not exist, and + * operations are retried on failure. + * @experimental + * @default false + */ + recursive?: boolean; + } + + export interface RmDirAsyncOptions extends RmDirOptions { + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number; + } + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirAsyncOptions, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirAsyncOptions): Promise; + } + + /** + * Synchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode; + } + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true }, callback: (err: NodeJS.ErrnoException | null, path: string) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, options: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null | undefined, callback: NoParamCallback): void; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path: string | undefined) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + } + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): string; + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null): void; + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: BaseEncodingOptions | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: BaseEncodingOptions | string | null): Promise; + } + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): string; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: BaseEncodingOptions | string | null): string | Buffer; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Promise; + } + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): string[] | Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Dirent[]; + + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + export function close(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + export function closeSync(fd: number): void; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + export function open(path: PathLike, flags: OpenMode, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, flags: OpenMode, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + + /** + * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + export function fsync(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + export function fsyncSync(fd: number): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write(fd: number, string: string, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write(fd: number, string: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): Promise<{ bytesWritten: number, buffer: string }>; + } + + /** + * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; + + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): number; + + /** + * Asynchronously reads data from the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null + ): Promise<{ bytesRead: number, buffer: TBuffer }>; + } + + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number; + /** + * @default `length of buffer` + */ + length?: number; + /** + * @default null + */ + position?: number | null; + } + + /** + * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: number | null): number; + + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string; } | string, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathLike | number, + options: BaseEncodingOptions & { flag?: string; } | string | undefined | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, + ): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string; } | string): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: BaseEncodingOptions & { flag?: string; } | string | null): Promise; + } + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string; } | BufferEncoding): string; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync(path: PathLike | number, options?: BaseEncodingOptions & { flag?: string; } | BufferEncoding | null): string | Buffer; + + export type WriteFileOptions = BaseEncodingOptions & { mode?: Mode; flag?: string; } | string | null; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + export function writeFile(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile(path: PathLike | number, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + export function writeFileSync(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + export function appendFile(file: PathLike | number, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathLike | number, data: string | Uint8Array, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathLike | number, data: string | Uint8Array, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + export function appendFileSync(file: PathLike | number, data: string | Uint8Array, options?: WriteFileOptions): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + */ + export function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Stop watching for changes on `filename`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, + listener?: (event: string, filename: string) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | string | null, + listener?: (event: string, filename: string | Buffer) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; + + /** + * Asynchronously tests whether or not the given path exists by checking with the file system. + * @deprecated since v1.0.0 Use `fs.stat()` or `fs.access()` instead + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronously tests whether or not the given path exists by checking with the file system. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function existsSync(path: PathLike): boolean; + + export namespace constants { + // File Access Constants + + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + + // File Copy Constants + + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + 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. */ + 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). + */ + 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. */ + const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + 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. + */ + const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + 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. */ + const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + 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. */ + 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. */ + const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + 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. */ + const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + 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. */ + const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + 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. */ + const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + + /** + * Synchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function accessSync(path: PathLike, mode?: number): void; + + /** + * Returns a new `ReadStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function createReadStream(path: PathLike, options?: string | { + flags?: string; + encoding?: BufferEncoding; + fd?: number; + mode?: number; + autoClose?: boolean; + /** + * @default false + */ + emitClose?: boolean; + start?: number; + end?: number; + highWaterMark?: number; + }): ReadStream; + + /** + * Returns a new `WriteStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function createWriteStream(path: PathLike, options?: string | { + flags?: string; + encoding?: BufferEncoding; + fd?: number; + mode?: number; + autoClose?: boolean; + emitClose?: boolean; + start?: number; + highWaterMark?: number; + }): WriteStream; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + export function fdatasyncSync(fd: number): void; + + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + export function copyFile(src: PathLike, dest: PathLike, flags: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace copyFile { + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, + * which causes the copy operation to fail if dest already exists. + */ + function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; + } + + /** + * Synchronously copies src to dest. By default, dest is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + export function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; + + /** + * Write an array of ArrayBufferViews to the file specified by fd using writev(). + * position is the offset from the beginning of the file where this data should be written. + * It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use fs.createWriteStream(). + * 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 writev( + fd: number, + buffers: NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export function writev( + fd: number, + buffers: NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + + export namespace writev { + function __promisify__(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): Promise; + } + + /** + * See `writev`. + */ + export function writevSync(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): number; + + export function readv( + fd: number, + buffers: NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export function readv( + fd: number, + buffers: NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + + export namespace readv { + function __promisify__(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): Promise; + } + + /** + * See `readv`. + */ + export function readvSync(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): number; + + export interface OpenDirOptions { + encoding?: BufferEncoding; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number; + } + + export function opendirSync(path: string, options?: OpenDirOptions): Dir; + + export function opendir(path: string, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir(path: string, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + + export namespace opendir { + function __promisify__(path: string, options?: OpenDirOptions): Promise; + } + + export interface BigIntStats extends StatsBase { + } + + export class BigIntStats { atimeNs: bigint; mtimeNs: bigint; ctimeNs: bigint; birthtimeNs: bigint; } - interface BigIntOptions { + export interface BigIntOptions { bigint: true; } - interface StatOptions { + export interface StatOptions { bigint: boolean; } - - function stat(path: PathLike, options: BigIntOptions, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; - function stat(path: PathLike, options: StatOptions, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; - - namespace stat { - function __promisify__(path: PathLike, options: BigIntOptions): Promise; - function __promisify__(path: PathLike, options: StatOptions): Promise; - } - - function statSync(path: PathLike, options: BigIntOptions): BigIntStats; - function statSync(path: PathLike, options: StatOptions): Stats | BigIntStats; } diff --git a/types/node/globals.d.ts b/types/node/globals.d.ts index a8c3e2a94f..76247f9a75 100644 --- a/types/node/globals.d.ts +++ b/types/node/globals.d.ts @@ -1,13 +1,606 @@ -// tslint:disable-next-line:no-bad-reference -/// +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; -interface Buffer extends Uint8Array { - readBigUInt64BE(offset?: number): bigint; - readBigUInt64LE(offset?: number): bigint; - readBigInt64BE(offset?: number): bigint; - readBigInt64LE(offset?: number): bigint; + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + + stackTraceLimit: number; +} + +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; + + /** Returns a copy with leading whitespace removed. */ + trimStart(): string; + /** Returns a copy with trailing whitespace removed. */ + trimEnd(): string; +} + +interface ImportMeta { + url: string; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + +// For backwards compability +interface NodeRequire extends NodeJS.Require {} +interface RequireResolve extends NodeJS.RequireResolve {} +interface NodeModule extends NodeJS.Module {} + +declare var process: NodeJS.Process; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T): Promise; +} +declare function clearTimeout(timeoutId: NodeJS.Timeout): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare function clearInterval(intervalId: NodeJS.Timeout): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; +declare namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T): Promise; +} +declare function clearImmediate(immediateId: NodeJS.Immediate): void; + +declare function queueMicrotask(callback: () => void): void; + +declare var require: NodeRequire; +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"; + +/** + * 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 class Buffer extends Uint8Array { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + constructor(str: string, encoding?: BufferEncoding); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + constructor(size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + constructor(array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + constructor(arrayBuffer: ArrayBuffer | SharedArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + constructor(array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + constructor(buffer: 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 any TypedArray or a new ArrayBuffer() + */ + static from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + static from(data: number[]): Buffer; + static from(data: Uint8Array): Buffer; + /** + * Creates a new buffer containing the coerced value of an object + * A `TypeError` will be thrown if {obj} has not mentioned methods or is not of other type appropriate for `Buffer.from()` variants. + * @param obj An object supporting `Symbol.toPrimitive` or `valueOf()`. + */ + static from(obj: { valueOf(): string | object } | { [Symbol.toPrimitive](hint: 'string'): string }, byteOffset?: number, length?: number): 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'. + */ + static from(str: string, encoding?: BufferEncoding): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + static of(...items: number[]): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static 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. + */ + static isEncoding(encoding: string): encoding is BufferEncoding; + /** + * 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 | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding + ): 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: Uint8Array[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Uint8Array, buf2: Uint8Array): 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 + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): 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 + */ + static 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 + */ + static allocUnsafeSlow(size: number): Buffer; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + static poolSize: number; + + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + toJSON(): { type: 'Buffer'; data: number[] }; + equals(otherBuffer: Uint8Array): boolean; + compare( + otherBuffer: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number + ): number; + copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. + * + * This method is incompatible with `Uint8Array#slice()`, which returns a copy of the original memory. + * + * @param begin Where the new `Buffer` will start. Default: `0`. + * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. + */ + slice(begin?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. + * + * This method is compatible with `Uint8Array#subarray()`. + * + * @param begin Where the new `Buffer` will start. Default: `0`. + * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. + */ + subarray(begin?: number, end?: number): Buffer; writeBigInt64BE(value: bigint, offset?: number): number; writeBigInt64LE(value: bigint, offset?: number): number; writeBigUInt64BE(value: bigint, offset?: number): number; writeBigUInt64LE(value: bigint, offset?: number): number; + writeUIntLE(value: number, offset: number, byteLength: number): number; + writeUIntBE(value: number, offset: number, byteLength: number): number; + writeIntLE(value: number, offset: number, byteLength: number): number; + writeIntBE(value: number, offset: number, byteLength: number): number; + readBigUInt64BE(offset?: number): bigint; + readBigUInt64LE(offset?: number): bigint; + readBigInt64BE(offset?: number): bigint; + readBigInt64LE(offset?: number): bigint; + readUIntLE(offset: number, byteLength: number): number; + readUIntBE(offset: number, byteLength: number): number; + readIntLE(offset: number, byteLength: number): number; + readIntBE(offset: number, byteLength: number): number; + readUInt8(offset?: number): number; + readUInt16LE(offset?: number): number; + readUInt16BE(offset?: number): number; + readUInt32LE(offset?: number): number; + readUInt32BE(offset?: number): number; + readInt8(offset?: number): number; + readInt16LE(offset?: number): number; + readInt16BE(offset?: number): number; + readInt32LE(offset?: number): number; + readInt32BE(offset?: number): number; + readFloatLE(offset?: number): number; + readFloatBE(offset?: number): number; + readDoubleLE(offset?: number): number; + readDoubleBE(offset?: number): number; + reverse(): this; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset?: number): number; + writeUInt16LE(value: number, offset?: number): number; + writeUInt16BE(value: number, offset?: number): number; + writeUInt32LE(value: number, offset?: number): number; + writeUInt32BE(value: number, offset?: number): number; + writeInt8(value: number, offset?: number): number; + writeInt16LE(value: number, offset?: number): number; + writeInt16BE(value: number, offset?: number): number; + writeInt32LE(value: number, offset?: number): number; + writeInt32BE(value: number, offset?: number): number; + writeFloatLE(value: number, offset?: number): number; + writeFloatBE(value: number, offset?: number): number; + writeDoubleLE(value: number, offset?: number): number; + writeDoubleBE(value: number, offset?: number): number; + + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean; + showHidden?: boolean; + /** + * @default 2 + */ + depth?: number | null; + colors?: boolean; + customInspect?: boolean; + showProxy?: boolean; + maxArrayLength?: number | null; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default Infinity + */ + maxStringLength?: number | null; + breakLength?: number; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default `true` + */ + compact?: boolean | number; + sorted?: boolean | ((a: string, b: string) => number); + } + + interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): void; + end(data: string | Uint8Array, cb?: () => void): void; + end(str: string, encoding?: BufferEncoding, cb?: () => void): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + 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; + 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: typeof Promise; + 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: typeof Uint8ClampedArray; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: Immediate) => void; + clearInterval: (intervalId: Timeout) => void; + clearTimeout: (timeoutId: Timeout) => void; + 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; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + queueMicrotask: typeof queueMicrotask; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + interface RefCounted { + ref(): this; + unref(): this; + } + + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + } + + interface Immediate extends RefCounted { + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + } + + interface Timeout extends Timer { + hasRef(): boolean; + refresh(): this; + } + + type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + /* tslint:disable-next-line:callable-types */ + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + '.js': (m: Module, filename: string) => any; + '.json': (m: Module, filename: string) => any; + '.node': (m: Module, filename: string) => any; + } + interface Module { + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since 14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since 11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } } diff --git a/types/node/package.json b/types/node/package.json index dd84e4f705..b17d6c5bc5 100644 --- a/types/node/package.json +++ b/types/node/package.json @@ -2,11 +2,6 @@ "private": true, "types": "index", "typesVersions": { - "<=3.1": { - "*": [ - "ts3.1/*" - ] - }, "<=3.4": { "*": [ "ts3.4/*" diff --git a/types/node/process.d.ts b/types/node/process.d.ts index 352a196401..07c918350c 100644 --- a/types/node/process.d.ts +++ b/types/node/process.d.ts @@ -1,12 +1,406 @@ -// tslint:disable-next-line:no-bad-reference -/// +declare module "process" { + import * as tty from "tty"; -declare module 'process' { global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; + } + + interface CpuUsage { + user: number; + system: number; + } + + interface ProcessRelease { + name: string; + sourceUrl?: string; + headersUrl?: string; + libUrl?: string; + lts?: string; + } + + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | 'cygwin' + | 'netbsd'; + + type Signals = + "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | + "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | + "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type MultipleResolveType = 'resolve' | 'reject'; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = (signal: Signals) => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; + + interface Socket extends ReadWriteStream { + isTTY?: true; + } + + // Alias for compatibility + interface ProcessEnv extends Dict {} + interface HRTime { + (time?: [number, number]): [number, number]; bigint(): bigint; } + + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @defaul false + */ + reportOnSignal: boolean; + + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + + interface Process extends EventEmitter { + /** + * Can also be a tty.WriteStream, not typed due to limitations. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * Can also be a tty.WriteStream, not typed due to limitations. + */ + stderr: WriteStream & { + fd: 2; + }; + stdin: ReadStream & { + fd: 0; + }; + openStdin(): Socket; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + debugPort: number; + emitWarning(warning: string | Error, name?: string, ctor?: Function): void; + env: ProcessEnv; + exit(code?: number): never; + exitCode?: number; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: Array): void; + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + hasUncaughtExceptionCaptureCallback(): boolean; + 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): true; + pid: number; + ppid: number; + title: string; + arch: string; + platform: Platform; + /** @deprecated since v14.0.0 - use `require.main` instead. */ + mainModule?: Module; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * @deprecated since v14.0.0 - Calling process.umask() with no argument causes + * the process-wide umask to be written twice. This introduces a race condition between threads, + * and is a potential security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: number): number; + uptime(): number; + hrtime: HRTime; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; + disconnect(): void; + connected: boolean; + + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] + * environment variable. + */ + allowedNodeEnvironmentFlags: ReadonlySet; + + /** + * Only available with `--experimental-report` + */ + report?: ProcessReport; + + resourceUsage(): ResourceUsage; + + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; + + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + } + + interface Global { + process: Process; + } } } + + export = process; } diff --git a/types/node/ts3.1/base.d.ts b/types/node/ts3.1/base.d.ts deleted file mode 100644 index f0c6ff0ad2..0000000000 --- a/types/node/ts3.1/base.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -// base definitions for all NodeJS modules that are not specific to any version of TypeScript - -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// diff --git a/types/node/ts3.1/fs.d.ts b/types/node/ts3.1/fs.d.ts deleted file mode 100644 index d4849bf43b..0000000000 --- a/types/node/ts3.1/fs.d.ts +++ /dev/null @@ -1,2132 +0,0 @@ -declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; - import { URL } from "url"; - import * as promises from 'fs/promises'; - - export { promises }; - /** - * Valid types for path values in "fs". - */ - export type PathLike = string | Buffer | URL; - - export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; - - export type BufferEncodingOption = 'buffer' | { encoding: 'buffer' }; - - export interface BaseEncodingOptions { - encoding?: BufferEncoding | null; - } - - export type OpenMode = number | string; - - export type Mode = number | string; - - export interface StatsBase { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - - dev: T; - ino: T; - mode: T; - nlink: T; - uid: T; - gid: T; - rdev: T; - size: T; - blksize: T; - blocks: T; - atimeMs: T; - mtimeMs: T; - ctimeMs: T; - birthtimeMs: T; - atime: Date; - mtime: Date; - ctime: Date; - birthtime: Date; - } - - export interface Stats extends StatsBase { - } - - export class Stats { - } - - export class Dirent { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - name: string; - } - - /** - * A class representing a directory stream. - */ - export class Dir { - readonly path: string; - - /** - * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. - */ - [Symbol.asyncIterator](): AsyncIterableIterator; - - /** - * Asynchronously close the directory's underlying resource handle. - * Subsequent reads will result in errors. - */ - close(): Promise; - close(cb: NoParamCallback): void; - - /** - * Synchronously close the directory's underlying resource handle. - * Subsequent reads will result in errors. - */ - closeSync(): void; - - /** - * Asynchronously read the next directory entry via `readdir(3)` as an `Dirent`. - * After the read is completed, a value is returned that will be resolved with an `Dirent`, or `null` if there are no more directory entries to read. - * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. - */ - read(): Promise; - read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; - - /** - * Synchronously read the next directory entry via `readdir(3)` as a `Dirent`. - * If there are no more directory entries to read, null will be returned. - * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. - */ - readSync(): Dirent; - } - - export interface FSWatcher extends events.EventEmitter { - close(): void; - - /** - * events.EventEmitter - * 1. change - * 2. error - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } - - export class ReadStream extends stream.Readable { - close(): void; - bytesRead: number; - path: string | Buffer; - pending: boolean; - - /** - * events.EventEmitter - * 1. open - * 2. close - * 3. ready - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "ready", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "ready", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "ready", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "ready", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "ready", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - export class WriteStream extends stream.Writable { - close(): void; - bytesWritten: number; - path: string | Buffer; - pending: boolean; - - /** - * events.EventEmitter - * 1. open - * 2. close - * 3. ready - */ - 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: "open", listener: (fd: number) => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "ready", listener: () => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "ready", listener: () => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "ready", listener: () => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "ready", listener: () => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "ready", listener: () => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace rename { - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; - } - - /** - * Synchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function renameSync(oldPath: PathLike, newPath: PathLike): void; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function truncate(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace truncate { - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function __promisify__(path: PathLike, len?: number | null): Promise; - } - - /** - * Synchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - export function truncateSync(path: PathLike, len?: number | null): void; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - */ - export function ftruncate(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace ftruncate { - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - function __promisify__(fd: number, len?: number | null): Promise; - } - - /** - * Synchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - export function ftruncateSync(fd: number, len?: number | null): void; - - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace chown { - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - - /** - * Synchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function chownSync(path: PathLike, uid: number, gid: number): void; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fchown { - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - function __promisify__(fd: number, uid: number, gid: number): Promise; - } - - /** - * Synchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - export function fchownSync(fd: number, uid: number, gid: number): void; - - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace lchown { - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - - /** - * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function lchownSync(path: PathLike, uid: number, gid: number): void; - - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace chmod { - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(path: PathLike, mode: Mode): Promise; - } - - /** - * Synchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function chmodSync(path: PathLike, mode: Mode): void; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fchmod { - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(fd: number, mode: Mode): Promise; - } - - /** - * Synchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function fchmodSync(fd: number, mode: Mode): void; - - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace lchmod { - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(path: PathLike, mode: Mode): Promise; - } - - /** - * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function lchmodSync(path: PathLike, mode: Mode): void; - - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace stat { - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function statSync(path: PathLike): Stats; - - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fstat { - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - export function fstatSync(fd: number): Stats; - - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace lstat { - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function lstatSync(path: PathLike): Stats; - - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace link { - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; - } - - /** - * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function linkSync(existingPath: PathLike, newPath: PathLike): void; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - */ - export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace symlink { - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; - - type Type = "dir" | "file" | "junction"; - } - - /** - * Synchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlink( - path: PathLike, - options: BaseEncodingOptions | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, linkString: string) => void - ): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlink(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlink(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace readlink { - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; - } - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlinkSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlinkSync(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpath( - path: PathLike, - options: BaseEncodingOptions | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void - ): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpath(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpath(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace realpath { - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; - - function native( - path: PathLike, - options: BaseEncodingOptions | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void - ): void; - function native(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - function native(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; - function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; - } - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpathSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpathSync(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; - - export namespace realpathSync { - function native(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; - function native(path: PathLike, options: BufferEncodingOption): Buffer; - function native(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; - } - - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function unlink(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace unlink { - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function unlinkSync(path: PathLike): void; - - export interface RmDirOptions { - /** - * If `true`, perform a recursive directory removal. In - * recursive mode, errors are not reported if `path` does not exist, and - * operations are retried on failure. - * @experimental - * @default false - */ - recursive?: boolean; - } - - export interface RmDirAsyncOptions extends RmDirOptions { - /** - * The amount of time in milliseconds to wait between retries. - * This option is ignored if the `recursive` option is not `true`. - * @default 100 - */ - retryDelay?: number; - /** - * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or - * `EPERM` error is encountered, Node.js will retry the operation with a linear - * backoff wait of `retryDelay` ms longer on each try. This option represents the - * number of retries. This option is ignored if the `recursive` option is not - * `true`. - * @default 0 - */ - maxRetries?: number; - } - - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function rmdir(path: PathLike, callback: NoParamCallback): void; - export function rmdir(path: PathLike, options: RmDirAsyncOptions, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace rmdir { - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, options?: RmDirAsyncOptions): Promise; - } - - /** - * Synchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function rmdirSync(path: PathLike, options?: RmDirOptions): void; - - export interface MakeDirectoryOptions { - /** - * Indicates whether parent folders should be created. - * If a folder was created, the path to the first created folder will be returned. - * @default false - */ - recursive?: boolean; - /** - * A file mode. If a string is passed, it is parsed as an octal integer. If not specified - * @default 0o777 - */ - mode?: Mode; - } - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true }, callback: (err: NodeJS.ErrnoException | null, path: string) => void): void; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdir(path: PathLike, options: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null | undefined, callback: NoParamCallback): void; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdir(path: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path: string | undefined) => void): void; - - /** - * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function mkdir(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace mkdir { - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; - } - - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdirSync(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): string; - - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdirSync(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null): void; - - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtemp(prefix: string, options: BaseEncodingOptions | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtemp(prefix: string, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - */ - export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace mkdtemp { - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options: BufferEncodingOption): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options?: BaseEncodingOptions | string | null): Promise; - } - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtempSync(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): string; - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtempSync(prefix: string, options?: BaseEncodingOptions | string | null): string | Buffer; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdir( - path: PathLike, - options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, - ): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdir( - path: PathLike, - options: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, - ): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - export function readdir(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace readdir { - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent - */ - function __promisify__(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Promise; - } - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdirSync(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): string[] | Buffer[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - export function readdirSync(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Dirent[]; - - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - export function close(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace close { - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - export function closeSync(fd: number): void; - - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - export function open(path: PathLike, flags: OpenMode, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - - /** - * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function open(path: PathLike, flags: OpenMode, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace open { - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; - } - - /** - * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace utimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; - } - - /** - * Synchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace futimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; - } - - /** - * Synchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - export function fsync(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fsync { - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - export function fsyncSync(fd: number): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - export function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - position: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - */ - export function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - */ - export function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - */ - export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - export function write( - fd: number, - string: string, - position: number | undefined | null, - encoding: BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, - ): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - export function write(fd: number, string: string, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. - */ - export function write(fd: number, string: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace write { - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function __promisify__( - fd: number, - buffer?: TBuffer, - offset?: number, - length?: number, - position?: number | null, - ): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function __promisify__(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): Promise<{ bytesWritten: number, buffer: string }>; - } - - /** - * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; - - /** - * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - export function writeSync(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): number; - - /** - * Asynchronously reads data from the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - export function read( - fd: number, - buffer: TBuffer, - offset: number, - length: number, - position: number | null, - callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, - ): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace read { - /** - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - function __promisify__( - fd: number, - buffer: TBuffer, - offset: number, - length: number, - position: number | null - ): Promise<{ bytesRead: number, buffer: TBuffer }>; - } - - export interface ReadSyncOptions { - /** - * @default 0 - */ - offset?: number; - /** - * @default `length of buffer` - */ - length?: number; - /** - * @default null - */ - position?: number | null; - } - - /** - * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: number | null): number; - - /** - * Similar to the above `fs.readSync` function, this version takes an optional `options` object. - * If no `options` object is specified, it will default with the above values. - */ - export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFile(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string; } | string, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFile( - path: PathLike | number, - options: BaseEncodingOptions & { flag?: string; } | string | undefined | null, - callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, - ): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - */ - export function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace readFile { - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string; } | string): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options?: BaseEncodingOptions & { flag?: string; } | string | null): Promise; - } - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. - */ - export function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFileSync(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string; } | BufferEncoding): string; - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFileSync(path: PathLike | number, options?: BaseEncodingOptions & { flag?: string; } | BufferEncoding | null): string | Buffer; - - export type WriteFileOptions = BaseEncodingOptions & { mode?: Mode; flag?: string; } | string | null; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - export function writeFile(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - export function writeFile(path: PathLike | number, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace writeFile { - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function __promisify__(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise; - } - - /** - * Synchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - export function writeFileSync(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - export function appendFile(file: PathLike | number, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): void; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - export function appendFile(file: PathLike | number, data: string | Uint8Array, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace appendFile { - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function __promisify__(file: PathLike | number, data: string | Uint8Array, options?: WriteFileOptions): Promise; - } - - /** - * Synchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - export function appendFileSync(file: PathLike | number, data: string | Uint8Array, options?: WriteFileOptions): void; - - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - */ - export function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; - - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; - - /** - * Stop watching for changes on `filename`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - export function watch( - filename: PathLike, - options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, - listener?: (event: string, filename: string) => void, - ): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - export function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - export function watch( - filename: PathLike, - options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | string | null, - listener?: (event: string, filename: string | Buffer) => void, - ): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; - - /** - * Asynchronously tests whether or not the given path exists by checking with the file system. - * @deprecated since v1.0.0 Use `fs.stat()` or `fs.access()` instead - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function exists(path: PathLike, callback: (exists: boolean) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace exists { - /** - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronously tests whether or not the given path exists by checking with the file system. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function existsSync(path: PathLike): boolean; - - export namespace constants { - // File Access Constants - - /** Constant for fs.access(). File is visible to the calling process. */ - const F_OK: number; - - /** Constant for fs.access(). File can be read by the calling process. */ - const R_OK: number; - - /** Constant for fs.access(). File can be written by the calling process. */ - const W_OK: number; - - /** Constant for fs.access(). File can be executed by the calling process. */ - const X_OK: number; - - // File Copy Constants - - /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ - const COPYFILE_EXCL: number; - - /** - * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. - * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. - */ - const COPYFILE_FICLONE: number; - - /** - * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. - * If the underlying platform does not support copy-on-write, then the operation will fail with an error. - */ - const COPYFILE_FICLONE_FORCE: number; - - // File Open Constants - - /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ - const O_RDONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ - const O_WRONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ - const O_RDWR: number; - - /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ - 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. */ - 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). - */ - 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. */ - const O_TRUNC: number; - - /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ - const O_APPEND: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ - 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. - */ - const O_NOATIME: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ - const O_NOFOLLOW: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ - const O_SYNC: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ - const O_DSYNC: number; - - /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ - const O_SYMLINK: number; - - /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ - const O_DIRECT: number; - - /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ - 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. */ - const S_IFMT: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ - const S_IFREG: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ - 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. */ - 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. */ - const S_IFBLK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ - const S_IFIFO: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ - const S_IFLNK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ - 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. */ - const S_IRWXU: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ - const S_IRUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ - const S_IWUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ - 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. */ - const S_IRWXG: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ - const S_IRGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ - const S_IWGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ - 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. */ - const S_IRWXO: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ - const S_IROTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ - const S_IWOTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ - const S_IXOTH: number; - - /** - * When set, a memory file mapping is used to access the file. This flag - * is available on Windows operating systems only. On other operating systems, - * this flag is ignored. - */ - const UV_FS_O_FILEMAP: number; - } - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function access(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace access { - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike, mode?: number): Promise; - } - - /** - * Synchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function accessSync(path: PathLike, mode?: number): void; - - /** - * Returns a new `ReadStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function createReadStream(path: PathLike, options?: string | { - flags?: string; - encoding?: BufferEncoding; - fd?: number; - mode?: number; - autoClose?: boolean; - /** - * @default false - */ - emitClose?: boolean; - start?: number; - end?: number; - highWaterMark?: number; - }): ReadStream; - - /** - * Returns a new `WriteStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function createWriteStream(path: PathLike, options?: string | { - flags?: string; - encoding?: BufferEncoding; - fd?: number; - mode?: number; - autoClose?: boolean; - emitClose?: boolean; - start?: number; - highWaterMark?: number; - }): WriteStream; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - export function fdatasync(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fdatasync { - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - export function fdatasyncSync(fd: number): void; - - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - */ - export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - export function copyFile(src: PathLike, dest: PathLike, flags: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace copyFile { - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. - * The only supported flag is fs.constants.COPYFILE_EXCL, - * which causes the copy operation to fail if dest already exists. - */ - function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; - } - - /** - * Synchronously copies src to dest. By default, dest is overwritten if it already exists. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. - * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - export function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; - - /** - * Write an array of ArrayBufferViews to the file specified by fd using writev(). - * position is the offset from the beginning of the file where this data should be written. - * It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use fs.createWriteStream(). - * 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 writev( - fd: number, - buffers: NodeJS.ArrayBufferView[], - cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - export function writev( - fd: number, - buffers: NodeJS.ArrayBufferView[], - position: number, - cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - - export interface WriteVResult { - bytesWritten: number; - buffers: NodeJS.ArrayBufferView[]; - } - - export namespace writev { - function __promisify__(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): Promise; - } - - /** - * See `writev`. - */ - export function writevSync(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): number; - - export function readv( - fd: number, - buffers: NodeJS.ArrayBufferView[], - cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - export function readv( - fd: number, - buffers: NodeJS.ArrayBufferView[], - position: number, - cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - - export interface ReadVResult { - bytesRead: number; - buffers: NodeJS.ArrayBufferView[]; - } - - export namespace readv { - function __promisify__(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): Promise; - } - - /** - * See `readv`. - */ - export function readvSync(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): number; - - export interface OpenDirOptions { - encoding?: BufferEncoding; - /** - * Number of directory entries that are buffered - * internally when reading from the directory. Higher values lead to better - * performance but higher memory usage. - * @default 32 - */ - bufferSize?: number; - } - - export function opendirSync(path: string, options?: OpenDirOptions): Dir; - - export function opendir(path: string, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; - export function opendir(path: string, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; - - export namespace opendir { - function __promisify__(path: string, options?: OpenDirOptions): Promise; - } -} diff --git a/types/node/ts3.1/globals.d.ts b/types/node/ts3.1/globals.d.ts deleted file mode 100644 index b7dc6241df..0000000000 --- a/types/node/ts3.1/globals.d.ts +++ /dev/null @@ -1,598 +0,0 @@ -// Declare "static" methods in Error -interface ErrorConstructor { - /** Create .stack property on a target object */ - captureStackTrace(targetObject: object, constructorOpt?: Function): void; - - /** - * Optional override for formatting stack traces - * - * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces - */ - prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; - - stackTraceLimit: number; -} - -// Node.js ESNEXT support -interface String { - /** Removes whitespace from the left end of a string. */ - trimLeft(): string; - /** Removes whitespace from the right end of a string. */ - trimRight(): string; - - /** Returns a copy with leading whitespace removed. */ - trimStart(): string; - /** Returns a copy with trailing whitespace removed. */ - trimEnd(): string; -} - -interface ImportMeta { - url: string; -} - -/*-----------------------------------------------* - * * - * GLOBAL * - * * - ------------------------------------------------*/ - -// For backwards compability -interface NodeRequire extends NodeJS.Require {} -interface RequireResolve extends NodeJS.RequireResolve {} -interface NodeModule extends NodeJS.Module {} - -declare var process: NodeJS.Process; -declare var console: Console; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare namespace setTimeout { - function __promisify__(ms: number): Promise; - function __promisify__(ms: number, value: T): Promise; -} -declare function clearTimeout(timeoutId: NodeJS.Timeout): void; -declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare function clearInterval(intervalId: NodeJS.Timeout): void; -declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; -declare namespace setImmediate { - function __promisify__(): Promise; - function __promisify__(value: T): Promise; -} -declare function clearImmediate(immediateId: NodeJS.Immediate): void; - -declare function queueMicrotask(callback: () => void): void; - -declare var require: NodeRequire; -declare var module: NodeModule; - -// Same as module.exports -declare var exports: any; - -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"; - -/** - * 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 class Buffer extends Uint8Array { - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. - */ - constructor(str: string, encoding?: BufferEncoding); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). - */ - constructor(size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - constructor(array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}/{SharedArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. - */ - constructor(arrayBuffer: ArrayBuffer | SharedArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - constructor(array: any[]); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. - */ - constructor(buffer: 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 any TypedArray or a new ArrayBuffer() - */ - static from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param data data to create a new Buffer - */ - static from(data: number[]): Buffer; - static from(data: Uint8Array): Buffer; - /** - * Creates a new buffer containing the coerced value of an object - * A `TypeError` will be thrown if {obj} has not mentioned methods or is not of other type appropriate for `Buffer.from()` variants. - * @param obj An object supporting `Symbol.toPrimitive` or `valueOf()`. - */ - static from(obj: { valueOf(): string | object } | { [Symbol.toPrimitive](hint: 'string'): string }, byteOffset?: number, length?: number): 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'. - */ - static from(str: string, encoding?: BufferEncoding): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param values to create a new Buffer - */ - static of(...items: number[]): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - static 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. - */ - static isEncoding(encoding: string): encoding is BufferEncoding; - /** - * 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 | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, - encoding?: BufferEncoding - ): 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: Uint8Array[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - static compare(buf1: Uint8Array, buf2: Uint8Array): 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 - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): 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 - */ - static 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 - */ - static allocUnsafeSlow(size: number): Buffer; - /** - * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. - */ - static poolSize: number; - - write(string: string, encoding?: BufferEncoding): number; - write(string: string, offset: number, encoding?: BufferEncoding): number; - write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; - toString(encoding?: BufferEncoding, start?: number, end?: number): string; - toJSON(): { type: 'Buffer'; data: number[] }; - equals(otherBuffer: Uint8Array): boolean; - compare( - otherBuffer: Uint8Array, - targetStart?: number, - targetEnd?: number, - sourceStart?: number, - sourceEnd?: number - ): number; - copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - /** - * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. - * - * This method is incompatible with `Uint8Array#slice()`, which returns a copy of the original memory. - * - * @param begin Where the new `Buffer` will start. Default: `0`. - * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. - */ - slice(begin?: number, end?: number): Buffer; - /** - * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. - * - * This method is compatible with `Uint8Array#subarray()`. - * - * @param begin Where the new `Buffer` will start. Default: `0`. - * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. - */ - subarray(begin?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number): number; - writeUIntBE(value: number, offset: number, byteLength: number): number; - writeIntLE(value: number, offset: number, byteLength: number): number; - writeIntBE(value: number, offset: number, byteLength: number): number; - readUIntLE(offset: number, byteLength: number): number; - readUIntBE(offset: number, byteLength: number): number; - readIntLE(offset: number, byteLength: number): number; - readIntBE(offset: number, byteLength: number): number; - readUInt8(offset?: number): number; - readUInt16LE(offset?: number): number; - readUInt16BE(offset?: number): number; - readUInt32LE(offset?: number): number; - readUInt32BE(offset?: number): number; - readInt8(offset?: number): number; - readInt16LE(offset?: number): number; - readInt16BE(offset?: number): number; - readInt32LE(offset?: number): number; - readInt32BE(offset?: number): number; - readFloatLE(offset?: number): number; - readFloatBE(offset?: number): number; - readDoubleLE(offset?: number): number; - readDoubleBE(offset?: number): number; - reverse(): this; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset?: number): number; - writeUInt16LE(value: number, offset?: number): number; - writeUInt16BE(value: number, offset?: number): number; - writeUInt32LE(value: number, offset?: number): number; - writeUInt32BE(value: number, offset?: number): number; - writeInt8(value: number, offset?: number): number; - writeInt16LE(value: number, offset?: number): number; - writeInt16BE(value: number, offset?: number): number; - writeInt32LE(value: number, offset?: number): number; - writeInt32BE(value: number, offset?: number): number; - writeFloatLE(value: number, offset?: number): number; - writeFloatBE(value: number, offset?: number): number; - writeDoubleLE(value: number, offset?: number): number; - writeDoubleBE(value: number, offset?: number): number; - - fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; - - indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; - lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; - keys(): IterableIterator; - values(): IterableIterator; -} - -/*----------------------------------------------* -* * -* GLOBAL INTERFACES * -* * -*-----------------------------------------------*/ -declare namespace NodeJS { - interface InspectOptions { - /** - * If set to `true`, getters are going to be - * inspected as well. If set to `'get'` only getters without setter are going - * to be inspected. If set to `'set'` only getters having a corresponding - * setter are going to be inspected. This might cause side effects depending on - * the getter function. - * @default `false` - */ - getters?: 'get' | 'set' | boolean; - showHidden?: boolean; - /** - * @default 2 - */ - depth?: number | null; - colors?: boolean; - customInspect?: boolean; - showProxy?: boolean; - maxArrayLength?: number | null; - /** - * Specifies the maximum number of characters to - * include when formatting. Set to `null` or `Infinity` to show all elements. - * Set to `0` or negative to show no characters. - * @default Infinity - */ - maxStringLength?: number | null; - breakLength?: number; - /** - * Setting this to `false` causes each object key - * to be displayed on a new line. It will also add new lines to text that is - * longer than `breakLength`. If set to a number, the most `n` inner elements - * are united on a single line as long as all properties fit into - * `breakLength`. Short array elements are also grouped together. Note that no - * text will be reduced below 16 characters, no matter the `breakLength` size. - * For more information, see the example below. - * @default `true` - */ - compact?: boolean | number; - sorted?: boolean | ((a: string, b: string) => number); - } - - interface CallSite { - /** - * Value of "this" - */ - getThis(): any; - - /** - * Type of "this" as a string. - * This is the name of the function stored in the constructor field of - * "this", if available. Otherwise the object's [[Class]] internal - * property. - */ - getTypeName(): string | null; - - /** - * Current function - */ - getFunction(): Function | undefined; - - /** - * Name of the current function, typically its name property. - * If a name property is not available an attempt will be made to try - * to infer a name from the function's context. - */ - getFunctionName(): string | null; - - /** - * Name of the property [of "this" or one of its prototypes] that holds - * the current function - */ - getMethodName(): string | null; - - /** - * Name of the script [if this function was defined in a script] - */ - getFileName(): string | null; - - /** - * Current line number [if this function was defined in a script] - */ - getLineNumber(): number | null; - - /** - * Current column number [if this function was defined in a script] - */ - getColumnNumber(): number | null; - - /** - * A call site object representing the location where eval was called - * [if this function was created using a call to eval] - */ - getEvalOrigin(): string | undefined; - - /** - * Is this a toplevel invocation, that is, is "this" the global object? - */ - isToplevel(): boolean; - - /** - * Does this call take place in code defined by a call to eval? - */ - isEval(): boolean; - - /** - * Is this call in native V8 code? - */ - isNative(): boolean; - - /** - * Is this a constructor call? - */ - isConstructor(): boolean; - } - - interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } - - interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: BufferEncoding): this; - pause(): this; - resume(): this; - isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: WritableStream): this; - unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; - wrap(oldStream: ReadableStream): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - interface WritableStream extends EventEmitter { - writable: boolean; - write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; - write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; - end(cb?: () => void): void; - end(data: string | Uint8Array, cb?: () => void): void; - end(str: string, encoding?: BufferEncoding, cb?: () => void): void; - } - - interface ReadWriteStream extends ReadableStream, WritableStream { } - - 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; - 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: typeof Promise; - 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: typeof Uint8ClampedArray; - WeakMap: WeakMapConstructor; - WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: Immediate) => void; - clearInterval: (intervalId: Timeout) => void; - clearTimeout: (timeoutId: Timeout) => void; - 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; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - queueMicrotask: typeof queueMicrotask; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } - - interface RefCounted { - ref(): this; - unref(): this; - } - - // compatibility with older typings - interface Timer extends RefCounted { - hasRef(): boolean; - refresh(): this; - } - - interface Immediate extends RefCounted { - hasRef(): boolean; - _onImmediate: Function; // to distinguish it from the Timeout class - } - - interface Timeout extends Timer { - hasRef(): boolean; - refresh(): this; - } - - type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; - type ArrayBufferView = TypedArray | DataView; - - interface Require { - /* tslint:disable-next-line:callable-types */ - (id: string): any; - resolve: RequireResolve; - cache: Dict; - /** - * @deprecated - */ - extensions: RequireExtensions; - main: Module | undefined; - } - - interface RequireResolve { - (id: string, options?: { paths?: string[]; }): string; - paths(request: string): string[] | null; - } - - interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { - '.js': (m: Module, filename: string) => any; - '.json': (m: Module, filename: string) => any; - '.node': (m: Module, filename: string) => any; - } - interface Module { - exports: any; - require: Require; - id: string; - filename: string; - loaded: boolean; - /** @deprecated since 14.6.0 Please use `require.main` and `module.children` instead. */ - parent: Module | null | undefined; - children: Module[]; - /** - * @since 11.14.0 - * - * The directory name of the module. This is usually the same as the path.dirname() of the module.id. - */ - path: string; - paths: string[]; - } - - interface Dict { - [key: string]: T | undefined; - } - - interface ReadOnlyDict { - readonly [key: string]: T | undefined; - } -} diff --git a/types/node/ts3.1/index.d.ts b/types/node/ts3.1/index.d.ts deleted file mode 100644 index 79b58d9ec5..0000000000 --- a/types/node/ts3.1/index.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.1. - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.8 -// - ~/ts3.5/index.d.ts - Definitions specific to TypeScript 3.5 - -// NOTE: Augmentations for TypeScript 3.5 and later should use individual files for overrides -// within the respective ~/ts3.5 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.5, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -/// - -// We can't include globals.global.d.ts in globals.d.ts, as it'll cause duplication errors in TypeScript 3.5+ -/// - -// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in TypeScript 3.7+ -/// - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files -// just to ensure the names are known and node typings can be used without importing these libs. -// if someone really needs these types the libs need to be added via --lib or in tsconfig.json -interface AsyncIterable { } -interface IterableIterator { } -interface AsyncIterableIterator {} -interface SymbolConstructor { - readonly asyncIterator: symbol; -} -declare var Symbol: SymbolConstructor; -// even this is just a forward declaration some properties are added otherwise -// it would be allowed to pass anything to e.g. Buffer.from() -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; -} - -declare module "util" { - namespace types { - function isBigInt64Array(value: any): boolean; - function isBigUint64Array(value: any): boolean; - } -} diff --git a/types/node/ts3.1/node-tests.ts b/types/node/ts3.1/node-tests.ts deleted file mode 100644 index f8b9c6cbf8..0000000000 --- a/types/node/ts3.1/node-tests.ts +++ /dev/null @@ -1,353 +0,0 @@ -import * as fs from "fs"; -import * as url from "url"; -import * as util from "util"; -import * as http from "http"; -import * as https from "https"; -import * as net from "net"; -import * as console2 from "console"; -import * as timers from "timers"; -import * as inspector from "inspector"; -import * as trace_events from "trace_events"; - -////////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html /// -////////////////////////////////////////////////////// - -{ - let agent: https.Agent = new https.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256, - maxCachedSessions: 100, - timeout: 15000 - }); - - agent = https.globalAgent; - - let sockets: NodeJS.ReadOnlyDict = agent.sockets; - sockets = agent.freeSockets; - - https.request({ - agent: false - }); - https.request({ - agent - }); - https.request({ - agent: undefined - }); - - https.get('http://www.example.com/xyz'); - https.request('http://www.example.com/xyz'); - - https.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - https.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - - https.get(new url.URL('http://www.example.com/xyz')); - https.request(new url.URL('http://www.example.com/xyz')); - - https.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - https.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - - const opts: https.RequestOptions = { - path: '/some/path' - }; - https.get(new url.URL('http://www.example.com'), opts); - https.request(new url.URL('http://www.example.com'), opts); - https.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - https.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - - https.globalAgent.options.ca = []; - - { - function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} - - class MyIncomingMessage extends http.IncomingMessage { - foo: number; - } - - class MyServerResponse extends http.ServerResponse { - foo: string; - } - - let server: https.Server; - - server = new https.Server(); - server = new https.Server(reqListener); - server = new https.Server({ IncomingMessage: MyIncomingMessage}); - - server = new https.Server({ - IncomingMessage: MyIncomingMessage, - ServerResponse: MyServerResponse - }, reqListener); - - server = https.createServer(); - server = https.createServer(reqListener); - server = https.createServer({ IncomingMessage: MyIncomingMessage }); - server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); - - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - const maxHeadersCount: number | null = server.maxHeadersCount; - const headersTimeout: number = server.headersTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } -} - -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - -{ - { - const immediate = timers - .setImmediate(() => { - console.log('immediate'); - }) - .unref() - .ref(); - const b: boolean = immediate.hasRef(); - timers.clearImmediate(immediate); - } - { - const timeout = timers - .setInterval(() => { - console.log('interval'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearInterval(timeout); - } - { - const timeout = timers - .setTimeout(() => { - console.log('timeout'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearTimeout(timeout); - } - async function testPromisify(doSomething: { - (foo: any, onSuccessCallback: (result: string) => void, onErrorCallback: (reason: any) => void): void; - [util.promisify.custom](foo: any): Promise; - }) { - const setTimeout = util.promisify(timers.setTimeout); - let v: void = await setTimeout(100); // tslint:disable-line no-void-expression void-return - let s: string = await setTimeout(100, ""); - - const setImmediate = util.promisify(timers.setImmediate); - v = await setImmediate(); // tslint:disable-line no-void-expression - s = await setImmediate(""); - - // $ExpectType (foo: any) => Promise - const doSomethingPromise = util.promisify(doSomething); - - // $ExpectType string - s = await doSomethingPromise('foo'); - } -} - -///////////////////////////////////////////////////////// -/// Errors Tests : https://nodejs.org/api/errors.html /// -///////////////////////////////////////////////////////// - -{ - { - Error.stackTraceLimit = Infinity; - } - { - const myObject = {}; - Error.captureStackTrace(myObject); - } - { - const frames: NodeJS.CallSite[] = []; - Error.prepareStackTrace!(new Error(), frames); - } - { - const frame: NodeJS.CallSite = null!; - const frameThis: any = frame.getThis(); - const typeName: string | null = frame.getTypeName(); - const func: Function | undefined = frame.getFunction(); - const funcName: string | null = frame.getFunctionName(); - const meth: string | null = frame.getMethodName(); - const fname: string | null = frame.getFileName(); - const lineno: number | null = frame.getLineNumber(); - const colno: number | null = frame.getColumnNumber(); - const evalOrigin: string | undefined = frame.getEvalOrigin(); - const isTop: boolean = frame.isToplevel(); - const isEval: boolean = frame.isEval(); - const isNative: boolean = frame.isNative(); - const isConstr: boolean = frame.isConstructor(); - } -} - -/////////////////////////////////////////////////////////// -/// Console Tests : https://nodejs.org/api/console.html /// -/////////////////////////////////////////////////////////// - -{ - { - let _c: Console = console; - _c = console2; - } - { - const writeStream = fs.createWriteStream('./index.d.ts'); - let consoleInstance: Console = new console.Console(writeStream); - - consoleInstance = new console.Console(writeStream, writeStream); - consoleInstance = new console.Console(writeStream, writeStream, true); - consoleInstance = new console.Console({ - stdout: writeStream, - stderr: writeStream, - colorMode: 'auto', - ignoreErrors: true - }); - consoleInstance = new console.Console({ - stdout: writeStream, - colorMode: false - }); - consoleInstance = new console.Console({ - stdout: writeStream - }); - } - { - console.assert('value'); - console.assert('value', 'message'); - console.assert('value', 'message', 'foo', 'bar'); - console.clear(); - console.count(); - console.count('label'); - console.countReset(); - console.countReset('label'); - console.debug(); - console.debug('message'); - console.debug('message', 'foo', 'bar'); - console.dir('obj'); - console.dir('obj', { depth: 1 }); - console.error(); - console.error('message'); - console.error('message', 'foo', 'bar'); - console.group(); - console.group('label'); - console.group('label1', 'label2'); - console.groupCollapsed(); - console.groupEnd(); - console.info(); - console.info('message'); - console.info('message', 'foo', 'bar'); - console.log(); - console.log('message'); - console.log('message', 'foo', 'bar'); - console.table({ foo: 'bar' }); - console.table([{ foo: 'bar' }]); - console.table([{ foo: 'bar' }], ['foo']); - console.time(); - console.time('label'); - console.timeEnd(); - console.timeEnd('label'); - console.timeLog(); - console.timeLog('label'); - console.timeLog('label', 'foo', 'bar'); - console.trace(); - console.trace('message'); - console.trace('message', 'foo', 'bar'); - console.warn(); - console.warn('message'); - console.warn('message', 'foo', 'bar'); - - // --- Inspector mode only --- - console.profile(); - console.profile('label'); - console.profileEnd(); - console.profileEnd('label'); - console.timeStamp(); - console.timeStamp('label'); - } -} - -/***************************************************************************** - * * - * The following tests are the modules not mentioned in document but existed * - * * - *****************************************************************************/ - -/////////////////////////////////////////////////////////// -/// Inspector Tests /// -/////////////////////////////////////////////////////////// - -{ - { - const b: inspector.Console.ConsoleMessage = {source: 'test', text: 'test', level: 'error' }; - inspector.open(); - inspector.open(0); - inspector.open(0, 'localhost'); - inspector.open(0, 'localhost', true); - inspector.close(); - const inspectorUrl: string | undefined = inspector.url(); - - const session = new inspector.Session(); - session.connect(); - session.disconnect(); - - // Unknown post method - session.post('A.b', { key: 'value' }, (err, params) => {}); - // TODO: parameters are implicitly 'any' and need type annotation - session.post('A.b', (err: Error | null, params?: {}) => {}); - session.post('A.b'); - // Known post method - const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; - session.post('Runtime.evaluate', parameter, - (err: Error | null, params: inspector.Runtime.EvaluateReturnType) => {}); - session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { - const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails!; - const resultClassName: string = params.result.className!; - }); - session.post('Runtime.evaluate'); - - // General event - session.on('inspectorNotification', message => { - message; // $ExpectType InspectorNotification<{}> - }); - // Known events - session.on('Debugger.paused', (message: inspector.InspectorNotification) => { - const method: string = message.method; - const pauseReason: string = message.params.reason; - }); - session.on('Debugger.resumed', () => {}); - // Node Inspector events - session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification) => { - const value: Array<{}> = message.params.value; - }); - } -} - -/////////////////////////////////////////////////////////// -/// Trace Events Tests /// -/////////////////////////////////////////////////////////// - -{ - const enabledCategories: string | undefined = trace_events.getEnabledCategories(); - const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] }); - const categories: string = tracing.categories; - const enabled: boolean = tracing.enabled; - tracing.enable(); - tracing.disable(); -} - -//////////////////////////////////////////////////// -/// Node.js ESNEXT Support -//////////////////////////////////////////////////// - -{ - const s = 'foo'; - const s1: string = s.trimLeft(); - const s2: string = s.trimRight(); - const s3: string = s.trimStart(); - const s4: string = s.trimEnd(); -} diff --git a/types/node/ts3.1/process.d.ts b/types/node/ts3.1/process.d.ts deleted file mode 100644 index d9267e4fb9..0000000000 --- a/types/node/ts3.1/process.d.ts +++ /dev/null @@ -1,405 +0,0 @@ -declare module "process" { - import * as tty from "tty"; - - global { - var process: NodeJS.Process; - - namespace NodeJS { - // this namespace merge is here because these are specifically used - // as the type for process.stdin, process.stdout, and process.stderr. - // they can't live in tty.d.ts because we need to disambiguate the imported name. - interface ReadStream extends tty.ReadStream {} - interface WriteStream extends tty.WriteStream {} - - interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - external: number; - arrayBuffers: number; - } - - interface CpuUsage { - user: number; - system: number; - } - - interface ProcessRelease { - name: string; - sourceUrl?: string; - headersUrl?: string; - libUrl?: string; - lts?: string; - } - - interface ProcessVersions extends Dict { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } - - type Platform = 'aix' - | 'android' - | 'darwin' - | 'freebsd' - | 'linux' - | 'openbsd' - | 'sunos' - | 'win32' - | 'cygwin' - | 'netbsd'; - - type Signals = - "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | - "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | - "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | - "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; - - type MultipleResolveType = 'resolve' | 'reject'; - - type BeforeExitListener = (code: number) => void; - type DisconnectListener = () => void; - type ExitListener = (code: number) => void; - type RejectionHandledListener = (promise: Promise) => void; - type UncaughtExceptionListener = (error: Error) => void; - type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; - type WarningListener = (warning: Error) => void; - type MessageListener = (message: any, sendHandle: any) => void; - type SignalsListener = (signal: Signals) => void; - type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; - - interface Socket extends ReadWriteStream { - isTTY?: true; - } - - // Alias for compatibility - interface ProcessEnv extends Dict {} - - interface HRTime { - (time?: [number, number]): [number, number]; - } - - interface ProcessReport { - /** - * Directory where the report is written. - * working directory of the Node.js process. - * @default '' indicating that reports are written to the current - */ - directory: string; - - /** - * Filename where the report is written. - * The default value is the empty string. - * @default '' the output filename will be comprised of a timestamp, - * PID, and sequence number. - */ - filename: string; - - /** - * Returns a JSON-formatted diagnostic report for the running process. - * The report's JavaScript stack trace is taken from err, if present. - */ - getReport(err?: Error): string; - - /** - * If true, a diagnostic report is generated on fatal errors, - * such as out of memory errors or failed C++ assertions. - * @default false - */ - reportOnFatalError: boolean; - - /** - * If true, a diagnostic report is generated when the process - * receives the signal specified by process.report.signal. - * @defaul false - */ - reportOnSignal: boolean; - - /** - * If true, a diagnostic report is generated on uncaught exception. - * @default false - */ - reportOnUncaughtException: boolean; - - /** - * The signal used to trigger the creation of a diagnostic report. - * @default 'SIGUSR2' - */ - signal: Signals; - - /** - * Writes a diagnostic report to a file. If filename is not provided, the default filename - * includes the date, time, PID, and a sequence number. - * The report's JavaScript stack trace is taken from err, if present. - * - * @param fileName Name of the file where the report is written. - * This should be a relative path, that will be appended to the directory specified in - * `process.report.directory`, or the current working directory of the Node.js process, - * if unspecified. - * @param error A custom error used for reporting the JavaScript stack. - * @return Filename of the generated report. - */ - writeReport(fileName?: string): string; - writeReport(error?: Error): string; - writeReport(fileName?: string, err?: Error): string; - } - - interface ResourceUsage { - fsRead: number; - fsWrite: number; - involuntaryContextSwitches: number; - ipcReceived: number; - ipcSent: number; - majorPageFault: number; - maxRSS: number; - minorPageFault: number; - sharedMemorySize: number; - signalsCount: number; - swappedOut: number; - systemCPUTime: number; - unsharedDataSize: number; - unsharedStackSize: number; - userCPUTime: number; - voluntaryContextSwitches: number; - } - - interface Process extends EventEmitter { - /** - * Can also be a tty.WriteStream, not typed due to limitations. - */ - stdout: WriteStream & { - fd: 1; - }; - /** - * Can also be a tty.WriteStream, not typed due to limitations. - */ - stderr: WriteStream & { - fd: 2; - }; - stdin: ReadStream & { - fd: 0; - }; - openStdin(): Socket; - argv: string[]; - argv0: string; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - debugPort: number; - emitWarning(warning: string | Error, name?: string, ctor?: Function): void; - env: ProcessEnv; - exit(code?: number): never; - exitCode?: number; - getgid(): number; - setgid(id: number | string): void; - getuid(): number; - setuid(id: number | string): void; - geteuid(): number; - seteuid(id: number | string): void; - getegid(): number; - setegid(id: number | string): void; - getgroups(): number[]; - setgroups(groups: Array): void; - setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; - hasUncaughtExceptionCaptureCallback(): boolean; - 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): true; - pid: number; - ppid: number; - title: string; - arch: string; - platform: Platform; - /** @deprecated since v14.0.0 - use `require.main` instead. */ - mainModule?: Module; - memoryUsage(): MemoryUsage; - cpuUsage(previousValue?: CpuUsage): CpuUsage; - nextTick(callback: Function, ...args: any[]): void; - release: ProcessRelease; - features: { - inspector: boolean; - debug: boolean; - uv: boolean; - ipv6: boolean; - tls_alpn: boolean; - tls_sni: boolean; - tls_ocsp: boolean; - tls: boolean; - }; - /** - * @deprecated since v14.0.0 - Calling process.umask() with no argument causes - * the process-wide umask to be written twice. This introduces a race condition between threads, - * and is a potential security vulnerability. There is no safe, cross-platform alternative API. - */ - umask(): number; - /** - * Can only be set if not in worker thread. - */ - umask(mask: number): number; - uptime(): number; - hrtime: HRTime; - domain: Domain; - - // Worker - send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; - disconnect(): void; - connected: boolean; - - /** - * The `process.allowedNodeEnvironmentFlags` property is a special, - * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] - * environment variable. - */ - allowedNodeEnvironmentFlags: ReadonlySet; - - /** - * Only available with `--experimental-report` - */ - report?: ProcessReport; - - resourceUsage(): ResourceUsage; - - /* EventEmitter */ - addListener(event: "beforeExit", listener: BeforeExitListener): this; - addListener(event: "disconnect", listener: DisconnectListener): this; - addListener(event: "exit", listener: ExitListener): this; - addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - addListener(event: "warning", listener: WarningListener): this; - addListener(event: "message", listener: MessageListener): this; - addListener(event: Signals, listener: SignalsListener): this; - addListener(event: "newListener", listener: NewListenerListener): this; - addListener(event: "removeListener", listener: RemoveListenerListener): this; - addListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - emit(event: "beforeExit", code: number): boolean; - emit(event: "disconnect"): boolean; - emit(event: "exit", code: number): boolean; - emit(event: "rejectionHandled", promise: Promise): boolean; - emit(event: "uncaughtException", error: Error): boolean; - emit(event: "uncaughtExceptionMonitor", error: Error): boolean; - emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; - emit(event: "warning", warning: Error): boolean; - emit(event: "message", message: any, sendHandle: any): this; - emit(event: Signals, signal: Signals): boolean; - emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; - emit(event: "multipleResolves", listener: MultipleResolveListener): this; - - on(event: "beforeExit", listener: BeforeExitListener): this; - on(event: "disconnect", listener: DisconnectListener): this; - on(event: "exit", listener: ExitListener): this; - on(event: "rejectionHandled", listener: RejectionHandledListener): this; - on(event: "uncaughtException", listener: UncaughtExceptionListener): this; - on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - on(event: "warning", listener: WarningListener): this; - on(event: "message", listener: MessageListener): this; - on(event: Signals, listener: SignalsListener): this; - on(event: "newListener", listener: NewListenerListener): this; - on(event: "removeListener", listener: RemoveListenerListener): this; - on(event: "multipleResolves", listener: MultipleResolveListener): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "beforeExit", listener: BeforeExitListener): this; - once(event: "disconnect", listener: DisconnectListener): this; - once(event: "exit", listener: ExitListener): this; - once(event: "rejectionHandled", listener: RejectionHandledListener): this; - once(event: "uncaughtException", listener: UncaughtExceptionListener): this; - once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - once(event: "warning", listener: WarningListener): this; - once(event: "message", listener: MessageListener): this; - once(event: Signals, listener: SignalsListener): this; - once(event: "newListener", listener: NewListenerListener): this; - once(event: "removeListener", listener: RemoveListenerListener): this; - once(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependListener(event: "beforeExit", listener: BeforeExitListener): this; - prependListener(event: "disconnect", listener: DisconnectListener): this; - prependListener(event: "exit", listener: ExitListener): this; - prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependListener(event: "warning", listener: WarningListener): this; - prependListener(event: "message", listener: MessageListener): this; - prependListener(event: Signals, listener: SignalsListener): this; - prependListener(event: "newListener", listener: NewListenerListener): this; - prependListener(event: "removeListener", listener: RemoveListenerListener): this; - prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; - prependOnceListener(event: "disconnect", listener: DisconnectListener): this; - prependOnceListener(event: "exit", listener: ExitListener): this; - prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependOnceListener(event: "warning", listener: WarningListener): this; - prependOnceListener(event: "message", listener: MessageListener): this; - prependOnceListener(event: Signals, listener: SignalsListener): this; - prependOnceListener(event: "newListener", listener: NewListenerListener): this; - prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; - prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - listeners(event: "beforeExit"): BeforeExitListener[]; - listeners(event: "disconnect"): DisconnectListener[]; - listeners(event: "exit"): ExitListener[]; - listeners(event: "rejectionHandled"): RejectionHandledListener[]; - listeners(event: "uncaughtException"): UncaughtExceptionListener[]; - listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; - listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; - listeners(event: "warning"): WarningListener[]; - listeners(event: "message"): MessageListener[]; - listeners(event: Signals): SignalsListener[]; - listeners(event: "newListener"): NewListenerListener[]; - listeners(event: "removeListener"): RemoveListenerListener[]; - listeners(event: "multipleResolves"): MultipleResolveListener[]; - } - - interface Global { - process: Process; - } - } - } - - export = process; -} diff --git a/types/node/ts3.1/tsconfig.json b/types/node/ts3.1/tsconfig.json deleted file mode 100644 index cc6def6c6d..0000000000 --- a/types/node/ts3.1/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "files": [ - "index.d.ts", - "node-tests.ts" - ], - "compilerOptions": { - "module": "commonjs", - "target": "esnext", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../../", - "typeRoots": [ - "../../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - } -} diff --git a/types/node/ts3.1/tslint.json b/types/node/ts3.1/tslint.json deleted file mode 100644 index 65e8b18d2a..0000000000 --- a/types/node/ts3.1/tslint.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "no-bad-reference": false, - "no-empty-interface": false, - "no-single-declare-module": false, - "unified-signatures": false - } -} diff --git a/types/node/ts3.1/util.d.ts b/types/node/ts3.1/util.d.ts deleted file mode 100644 index 542ad76524..0000000000 --- a/types/node/ts3.1/util.d.ts +++ /dev/null @@ -1,194 +0,0 @@ -declare module "util" { - interface InspectOptions extends NodeJS.InspectOptions { } - type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; - type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; - interface InspectOptionsStylized extends InspectOptions { - stylize(text: string, styleType: Style): string; - } - function format(format: any, ...param: any[]): string; - function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; - /** @deprecated since v0.11.3 - use a third party module instead. */ - function log(string: string): void; - function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - function inspect(object: any, options: InspectOptions): string; - namespace inspect { - let colors: NodeJS.Dict<[number, number]>; - let styles: { - [K in Style]: string - }; - let defaultOptions: InspectOptions; - /** - * Allows changing inspect settings from the repl. - */ - let replDefaults: InspectOptions; - const custom: unique symbol; - } - /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ - function isArray(object: any): object is any[]; - /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ - function isRegExp(object: any): object is RegExp; - /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ - function isDate(object: any): object is Date; - /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ - function isError(object: any): object is Error; - function inherits(constructor: any, superConstructor: any): void; - function debuglog(key: string): (msg: string, ...param: any[]) => void; - /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ - function isBoolean(object: any): object is boolean; - /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ - function isBuffer(object: any): object is Buffer; - /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ - function isFunction(object: any): boolean; - /** @deprecated since v4.0.0 - use `value === null` instead. */ - function isNull(object: any): object is null; - /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ - function isNullOrUndefined(object: any): object is null | undefined; - /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ - function isNumber(object: any): object is number; - /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ - function isObject(object: any): boolean; - /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ - function isPrimitive(object: any): boolean; - /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ - function isString(object: any): object is string; - /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ - function isSymbol(object: any): object is symbol; - /** @deprecated since v4.0.0 - use `value === undefined` instead. */ - function isUndefined(object: any): object is undefined; - function deprecate(fn: T, message: string, code?: string): T; - function isDeepStrictEqual(val1: any, val2: any): boolean; - - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - - interface CustomPromisifyLegacy extends Function { - __promisify__: TCustom; - } - - interface CustomPromisifySymbol extends Function { - [promisify.custom]: TCustom; - } - - type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; - - function promisify(fn: CustomPromisify): TCustom; - function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; - function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; - function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): - (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): - (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify(fn: Function): Function; - namespace promisify { - const custom: unique symbol; - } - - namespace types { - function isAnyArrayBuffer(object: any): boolean; - function isArgumentsObject(object: any): object is IArguments; - function isArrayBuffer(object: any): object is ArrayBuffer; - function isArrayBufferView(object: any): object is ArrayBufferView; - function isAsyncFunction(object: any): boolean; - function isBooleanObject(object: any): object is Boolean; - function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); - function isDataView(object: any): object is DataView; - function isDate(object: any): object is Date; - function isExternal(object: any): boolean; - function isFloat32Array(object: any): object is Float32Array; - function isFloat64Array(object: any): object is Float64Array; - function isGeneratorFunction(object: any): boolean; - function isGeneratorObject(object: any): boolean; - function isInt8Array(object: any): object is Int8Array; - function isInt16Array(object: any): object is Int16Array; - function isInt32Array(object: any): object is Int32Array; - function isMap(object: any): boolean; - function isMapIterator(object: any): boolean; - function isModuleNamespaceObject(value: any): boolean; - function isNativeError(object: any): object is Error; - function isNumberObject(object: any): object is Number; - function isPromise(object: any): boolean; - function isProxy(object: any): boolean; - function isRegExp(object: any): object is RegExp; - function isSet(object: any): boolean; - function isSetIterator(object: any): boolean; - function isSharedArrayBuffer(object: any): boolean; - function isStringObject(object: any): boolean; - function isSymbolObject(object: any): boolean; - function isTypedArray(object: any): object is NodeJS.TypedArray; - function isUint8Array(object: any): object is Uint8Array; - function isUint8ClampedArray(object: any): object is Uint8ClampedArray; - function isUint16Array(object: any): object is Uint16Array; - function isUint32Array(object: any): object is Uint32Array; - function isWeakMap(object: any): boolean; - function isWeakSet(object: any): boolean; - function isWebAssemblyCompiledModule(object: any): boolean; - } - - class TextDecoder { - readonly encoding: string; - readonly fatal: boolean; - readonly ignoreBOM: boolean; - constructor( - encoding?: string, - options?: { fatal?: boolean; ignoreBOM?: boolean } - ); - decode( - input?: NodeJS.ArrayBufferView | ArrayBuffer | null, - options?: { stream?: boolean } - ): string; - } - - interface EncodeIntoResult { - /** - * The read Unicode code units of input. - */ - - read: number; - /** - * The written UTF-8 bytes of output. - */ - written: number; - } - - class TextEncoder { - readonly encoding: string; - encode(input?: string): Uint8Array; - encodeInto(input: string, output: Uint8Array): EncodeIntoResult; - } -} diff --git a/types/node/ts3.1/assert.d.ts b/types/node/ts3.4/assert.d.ts similarity index 100% rename from types/node/ts3.1/assert.d.ts rename to types/node/ts3.4/assert.d.ts diff --git a/types/node/ts3.4/base.d.ts b/types/node/ts3.4/base.d.ts index 4b315049d1..2ea04f58fc 100644 --- a/types/node/ts3.4/base.d.ts +++ b/types/node/ts3.4/base.d.ts @@ -13,11 +13,44 @@ /// // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -// tslint:disable-next-line:no-bad-reference -/// -// TypeScript 3.2-specific augmentations: -/// -/// -/// /// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/node/ts3.1/globals.global.d.ts b/types/node/ts3.4/globals.global.d.ts similarity index 100% rename from types/node/ts3.1/globals.global.d.ts rename to types/node/ts3.4/globals.global.d.ts diff --git a/types/node/ts3.4/index.d.ts b/types/node/ts3.4/index.d.ts index a9c9defebb..506b32a598 100644 --- a/types/node/ts3.4/index.d.ts +++ b/types/node/ts3.4/index.d.ts @@ -4,9 +4,5 @@ // Typically type modifiations should be made in base.d.ts instead of here /// - -// tslint:disable-next-line:no-bad-reference -/// - -// tslint:disable-next-line:no-bad-reference -/// +/// +/// diff --git a/types/node/ts3.4/node-tests.ts b/types/node/ts3.4/node-tests.ts index 56f949002e..7c0caab463 100644 --- a/types/node/ts3.4/node-tests.ts +++ b/types/node/ts3.4/node-tests.ts @@ -1,31 +1,356 @@ -// tslint:disable-next-line:no-bad-reference -import '../ts3.1/node-tests'; -import '../ts3.1/assert'; -import '../ts3.1/buffer'; -import '../ts3.1/child_process'; -import '../ts3.1/cluster'; -import '../ts3.1/crypto'; -import '../ts3.1/dgram'; -import '../ts3.1/global'; -import '../ts3.1/http'; -import '../ts3.1/http2'; -import '../ts3.1/net'; -import '../ts3.1/os'; -import '../ts3.1/path'; -import '../ts3.1/perf_hooks'; -import '../ts3.1/process'; -import '../ts3.1/querystring'; -import '../ts3.1/readline'; -import '../ts3.1/repl'; -import '../ts3.1/stream'; -import '../ts3.1/tls'; -import '../ts3.1/tty'; -import '../ts3.1/util'; -import '../ts3.1/worker_threads'; -import '../ts3.1/zlib'; +import * as fs from "fs"; +import * as url from "url"; +import * as util from "util"; +import * as http from "http"; +import * as https from "https"; +import * as net from "net"; +import * as console2 from "console"; +import * as timers from "timers"; +import * as inspector from "inspector"; +import * as trace_events from "trace_events"; -import { types, promisify } from 'util'; -import { BigIntStats, statSync, Stats } from 'fs'; +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + +{ + let agent: https.Agent = new https.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256, + maxCachedSessions: 100, + timeout: 15000 + }); + + agent = https.globalAgent; + + let sockets: NodeJS.ReadOnlyDict = agent.sockets; + sockets = agent.freeSockets; + + https.request({ + agent: false + }); + https.request({ + agent + }); + https.request({ + agent: undefined + }); + + https.get('http://www.example.com/xyz'); + https.request('http://www.example.com/xyz'); + + https.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + https.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + + https.get(new url.URL('http://www.example.com/xyz')); + https.request(new url.URL('http://www.example.com/xyz')); + + https.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + https.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + + const opts: https.RequestOptions = { + path: '/some/path' + }; + https.get(new url.URL('http://www.example.com'), opts); + https.request(new url.URL('http://www.example.com'), opts); + https.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + https.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + + https.globalAgent.options.ca = []; + + { + function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} + + class MyIncomingMessage extends http.IncomingMessage { + foo: number; + } + + class MyServerResponse extends http.ServerResponse { + foo: string; + } + + let server: https.Server; + + server = new https.Server(); + server = new https.Server(reqListener); + server = new https.Server({ IncomingMessage: MyIncomingMessage}); + + server = new https.Server({ + IncomingMessage: MyIncomingMessage, + ServerResponse: MyServerResponse + }, reqListener); + + server = https.createServer(); + server = https.createServer(reqListener); + server = https.createServer({ IncomingMessage: MyIncomingMessage }); + server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); + + const timeout: number = server.timeout; + const listening: boolean = server.listening; + const keepAliveTimeout: number = server.keepAliveTimeout; + const maxHeadersCount: number | null = server.maxHeadersCount; + const headersTimeout: number = server.headersTimeout; + server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); + } +} + +///////////////////////////////////////////////////// +/// Timers tests : https://nodejs.org/api/timers.html +///////////////////////////////////////////////////// + +{ + { + const immediate = timers + .setImmediate(() => { + console.log('immediate'); + }) + .unref() + .ref(); + const b: boolean = immediate.hasRef(); + timers.clearImmediate(immediate); + } + { + const timeout = timers + .setInterval(() => { + console.log('interval'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearInterval(timeout); + } + { + const timeout = timers + .setTimeout(() => { + console.log('timeout'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearTimeout(timeout); + } + async function testPromisify(doSomething: { + (foo: any, onSuccessCallback: (result: string) => void, onErrorCallback: (reason: any) => void): void; + [util.promisify.custom](foo: any): Promise; + }) { + const setTimeout = util.promisify(timers.setTimeout); + let v: void = await setTimeout(100); // tslint:disable-line no-void-expression void-return + let s: string = await setTimeout(100, ""); + + const setImmediate = util.promisify(timers.setImmediate); + v = await setImmediate(); // tslint:disable-line no-void-expression + s = await setImmediate(""); + + // $ExpectType (foo: any) => Promise + const doSomethingPromise = util.promisify(doSomething); + + // $ExpectType string + s = await doSomethingPromise('foo'); + } +} + +///////////////////////////////////////////////////////// +/// Errors Tests : https://nodejs.org/api/errors.html /// +///////////////////////////////////////////////////////// + +{ + { + Error.stackTraceLimit = Infinity; + } + { + const myObject = {}; + Error.captureStackTrace(myObject); + } + { + const frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace!(new Error(), frames); + } + { + const frame: NodeJS.CallSite = null!; + const frameThis: any = frame.getThis(); + const typeName: string | null = frame.getTypeName(); + const func: Function | undefined = frame.getFunction(); + const funcName: string | null = frame.getFunctionName(); + const meth: string | null = frame.getMethodName(); + const fname: string | null = frame.getFileName(); + const lineno: number | null = frame.getLineNumber(); + const colno: number | null = frame.getColumnNumber(); + const evalOrigin: string | undefined = frame.getEvalOrigin(); + const isTop: boolean = frame.isToplevel(); + const isEval: boolean = frame.isEval(); + const isNative: boolean = frame.isNative(); + const isConstr: boolean = frame.isConstructor(); + } +} + +/////////////////////////////////////////////////////////// +/// Console Tests : https://nodejs.org/api/console.html /// +/////////////////////////////////////////////////////////// + +{ + { + let _c: Console = console; + _c = console2; + } + { + const writeStream = fs.createWriteStream('./index.d.ts'); + let consoleInstance: Console = new console.Console(writeStream); + + consoleInstance = new console.Console(writeStream, writeStream); + consoleInstance = new console.Console(writeStream, writeStream, true); + consoleInstance = new console.Console({ + stdout: writeStream, + stderr: writeStream, + colorMode: 'auto', + ignoreErrors: true + }); + consoleInstance = new console.Console({ + stdout: writeStream, + colorMode: false + }); + consoleInstance = new console.Console({ + stdout: writeStream + }); + } + { + console.assert('value'); + console.assert('value', 'message'); + console.assert('value', 'message', 'foo', 'bar'); + console.clear(); + console.count(); + console.count('label'); + console.countReset(); + console.countReset('label'); + console.debug(); + console.debug('message'); + console.debug('message', 'foo', 'bar'); + console.dir('obj'); + console.dir('obj', { depth: 1 }); + console.error(); + console.error('message'); + console.error('message', 'foo', 'bar'); + console.group(); + console.group('label'); + console.group('label1', 'label2'); + console.groupCollapsed(); + console.groupEnd(); + console.info(); + console.info('message'); + console.info('message', 'foo', 'bar'); + console.log(); + console.log('message'); + console.log('message', 'foo', 'bar'); + console.table({ foo: 'bar' }); + console.table([{ foo: 'bar' }]); + console.table([{ foo: 'bar' }], ['foo']); + console.time(); + console.time('label'); + console.timeEnd(); + console.timeEnd('label'); + console.timeLog(); + console.timeLog('label'); + console.timeLog('label', 'foo', 'bar'); + console.trace(); + console.trace('message'); + console.trace('message', 'foo', 'bar'); + console.warn(); + console.warn('message'); + console.warn('message', 'foo', 'bar'); + + // --- Inspector mode only --- + console.profile(); + console.profile('label'); + console.profileEnd(); + console.profileEnd('label'); + console.timeStamp(); + console.timeStamp('label'); + } +} + +/***************************************************************************** + * * + * The following tests are the modules not mentioned in document but existed * + * * + *****************************************************************************/ + +/////////////////////////////////////////////////////////// +/// Inspector Tests /// +/////////////////////////////////////////////////////////// + +{ + { + const b: inspector.Console.ConsoleMessage = {source: 'test', text: 'test', level: 'error' }; + inspector.open(); + inspector.open(0); + inspector.open(0, 'localhost'); + inspector.open(0, 'localhost', true); + inspector.close(); + const inspectorUrl: string | undefined = inspector.url(); + + const session = new inspector.Session(); + session.connect(); + session.disconnect(); + + // Unknown post method + session.post('A.b', { key: 'value' }, (err, params) => {}); + // TODO: parameters are implicitly 'any' and need type annotation + session.post('A.b', (err: Error | null, params?: {}) => {}); + session.post('A.b'); + // Known post method + const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; + session.post('Runtime.evaluate', parameter, + (err: Error | null, params: inspector.Runtime.EvaluateReturnType) => {}); + session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { + const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails!; + const resultClassName: string = params.result.className!; + }); + session.post('Runtime.evaluate'); + + // General event + session.on('inspectorNotification', message => { + message; // $ExpectType InspectorNotification<{}> + }); + // Known events + session.on('Debugger.paused', (message: inspector.InspectorNotification) => { + const method: string = message.method; + const pauseReason: string = message.params.reason; + }); + session.on('Debugger.resumed', () => {}); + // Node Inspector events + session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification) => { + const value: Array<{}> = message.params.value; + }); + } +} + +/////////////////////////////////////////////////////////// +/// Trace Events Tests /// +/////////////////////////////////////////////////////////// + +{ + const enabledCategories: string | undefined = trace_events.getEnabledCategories(); + const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] }); + const categories: string = tracing.categories; + const enabled: boolean = tracing.enabled; + tracing.enable(); + tracing.disable(); +} + +//////////////////////////////////////////////////// +/// Node.js ESNEXT Support +//////////////////////////////////////////////////// + +{ + const s = 'foo'; + const s1: string = s.trimLeft(); + const s2: string = s.trimRight(); + const s3: string = s.trimStart(); + const s4: string = s.trimEnd(); +} ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -39,10 +364,10 @@ import { BigIntStats, statSync, Stats } from 'fs'; // Util Tests { const value: BigInt64Array | BigUint64Array | number = [] as any; - if (types.isBigInt64Array(value)) { + if (util.types.isBigInt64Array(value)) { // $ExpectType BigInt64Array const b = value; - } else if (types.isBigUint64Array(value)) { + } else if (util.types.isBigUint64Array(value)) { // $ExpectType BigUint64Array const b = value; } else { @@ -50,15 +375,15 @@ import { BigIntStats, statSync, Stats } from 'fs'; const b = value; } - const arg1UnknownError: (arg: string) => Promise = promisify((arg: string, cb: (err: unknown, result: number) => void): void => { }); - const arg1AnyError: (arg: string) => Promise = promisify((arg: string, cb: (err: any, result: number) => void): void => { }); + const arg1UnknownError: (arg: string) => Promise = util.promisify((arg: string, cb: (err: unknown, result: number) => void): void => { }); + const arg1AnyError: (arg: string) => Promise = util.promisify((arg: string, cb: (err: any, result: number) => void): void => { }); } // FS Tests { - const bigStats: BigIntStats = statSync('.', { bigint: true }); + const bigStats: fs.BigIntStats = fs.statSync('.', { bigint: true }); const bigIntStat: bigint = bigStats.atimeNs; - const anyStats: Stats | BigIntStats = statSync('.', { bigint: Math.random() > 0.5 }); + const anyStats: fs.Stats | fs.BigIntStats = fs.statSync('.', { bigint: Math.random() > 0.5 }); } // Global Tests diff --git a/types/node/ts3.4/tslint.json b/types/node/ts3.4/tslint.json index 9061fbd0e3..65e8b18d2a 100644 --- a/types/node/ts3.4/tslint.json +++ b/types/node/ts3.4/tslint.json @@ -1,6 +1,10 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-bad-reference": false - } + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "no-bad-reference": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "unified-signatures": false + } } diff --git a/types/node/ts3.6/index.d.ts b/types/node/ts3.6/index.d.ts index 8a427bb210..23b9a61dde 100644 --- a/types/node/ts3.6/index.d.ts +++ b/types/node/ts3.6/index.d.ts @@ -5,4 +5,4 @@ /// // tslint:disable-next-line:no-bad-reference -/// +/// diff --git a/types/node/ts3.6/node-tests.ts b/types/node/ts3.6/node-tests.ts index 5f1cc57a79..b341061ae0 100644 --- a/types/node/ts3.6/node-tests.ts +++ b/types/node/ts3.6/node-tests.ts @@ -1,29 +1,5 @@ // tslint:disable-next-line:no-bad-reference -import '../ts3.1/node-tests'; -import '../ts3.1/assert'; -import '../ts3.1/buffer'; -import '../ts3.1/child_process'; -import '../ts3.1/cluster'; -import '../ts3.1/crypto'; -import '../ts3.1/dgram'; -import '../ts3.1/ts3.2/fs'; -import '../ts3.1/ts3.2/global'; -import '../ts3.1/http'; -import '../ts3.1/http2'; -import '../ts3.1/net'; -import '../ts3.1/os'; -import '../ts3.1/path'; -import '../ts3.1/perf_hooks'; -import '../ts3.1/process'; -import '../ts3.1/querystring'; -import '../ts3.1/readline'; -import '../ts3.1/repl'; -import '../ts3.1/stream'; -import '../ts3.1/tls'; -import '../ts3.1/tty'; -import '../ts3.1/ts3.2/util'; -import '../ts3.1/worker_threads'; -import '../ts3.1/zlib'; +import '../ts3.4/node-tests'; ///////////////////////////////////////////////////// /// WASI tests : https://nodejs.org/api/wasi.html /// diff --git a/types/node/util.d.ts b/types/node/util.d.ts index 84d7ae2c0b..f4d1bda167 100644 --- a/types/node/util.d.ts +++ b/types/node/util.d.ts @@ -1,9 +1,196 @@ -// tslint:disable-next-line:no-bad-reference -/// - declare module "util" { + interface InspectOptions extends NodeJS.InspectOptions { } + type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; + type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; + interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + function format(format: any, ...param: any[]): string; + function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; + /** @deprecated since v0.11.3 - use a third party module instead. */ + function log(string: string): void; + function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + function inspect(object: any, options: InspectOptions): string; + namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + const custom: unique symbol; + } + /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ + function isArray(object: any): object is any[]; + /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ + function isRegExp(object: any): object is RegExp; + /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ + function isDate(object: any): object is Date; + /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ + function isError(object: any): object is Error; + function inherits(constructor: any, superConstructor: any): void; + function debuglog(key: string): (msg: string, ...param: any[]) => void; + /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ + function isBoolean(object: any): object is boolean; + /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ + function isBuffer(object: any): object is Buffer; + /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ + function isFunction(object: any): boolean; + /** @deprecated since v4.0.0 - use `value === null` instead. */ + function isNull(object: any): object is null; + /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ + function isNullOrUndefined(object: any): object is null | undefined; + /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ + function isNumber(object: any): object is number; + /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ + function isObject(object: any): boolean; + /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ + function isPrimitive(object: any): boolean; + /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ + function isString(object: any): object is string; + /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ + function isSymbol(object: any): object is symbol; + /** @deprecated since v4.0.0 - use `value === undefined` instead. */ + function isUndefined(object: any): object is undefined; + function deprecate(fn: T, message: string, code?: string): T; + function isDeepStrictEqual(val1: any, val2: any): boolean; + + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + + interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + + interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + + type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; + + function promisify(fn: CustomPromisify): TCustom; + function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; + function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): + (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): + (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify(fn: Function): Function; + namespace promisify { + const custom: unique symbol; + } + namespace types { + function isAnyArrayBuffer(object: any): boolean; + function isArgumentsObject(object: any): object is IArguments; + function isArrayBuffer(object: any): object is ArrayBuffer; + function isArrayBufferView(object: any): object is ArrayBufferView; + function isAsyncFunction(object: any): boolean; function isBigInt64Array(value: any): value is BigInt64Array; function isBigUint64Array(value: any): value is BigUint64Array; + function isBooleanObject(object: any): object is Boolean; + function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); + function isDataView(object: any): object is DataView; + function isDate(object: any): object is Date; + function isExternal(object: any): boolean; + function isFloat32Array(object: any): object is Float32Array; + function isFloat64Array(object: any): object is Float64Array; + function isGeneratorFunction(object: any): boolean; + function isGeneratorObject(object: any): boolean; + function isInt8Array(object: any): object is Int8Array; + function isInt16Array(object: any): object is Int16Array; + function isInt32Array(object: any): object is Int32Array; + function isMap(object: any): boolean; + function isMapIterator(object: any): boolean; + function isModuleNamespaceObject(value: any): boolean; + function isNativeError(object: any): object is Error; + function isNumberObject(object: any): object is Number; + function isPromise(object: any): boolean; + function isProxy(object: any): boolean; + function isRegExp(object: any): object is RegExp; + function isSet(object: any): boolean; + function isSetIterator(object: any): boolean; + function isSharedArrayBuffer(object: any): boolean; + function isStringObject(object: any): boolean; + function isSymbolObject(object: any): boolean; + function isTypedArray(object: any): object is NodeJS.TypedArray; + function isUint8Array(object: any): object is Uint8Array; + function isUint8ClampedArray(object: any): object is Uint8ClampedArray; + function isUint16Array(object: any): object is Uint16Array; + function isUint32Array(object: any): object is Uint32Array; + function isWeakMap(object: any): boolean; + function isWeakSet(object: any): boolean; + function isWebAssemblyCompiledModule(object: any): boolean; + } + + class TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { fatal?: boolean; ignoreBOM?: boolean } + ); + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { stream?: boolean } + ): string; + } + + interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + + class TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; + encodeInto(input: string, output: Uint8Array): EncodeIntoResult; } } diff --git a/types/node/v10/globals.d.ts b/types/node/v10/globals.d.ts index 81078e31d1..43d40d8c48 100644 --- a/types/node/v10/globals.d.ts +++ b/types/node/v10/globals.d.ts @@ -1,8 +1,1014 @@ -// tslint:disable-next-line:no-bad-reference -/// +// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build +interface Console { + Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * The console.markTimeline() method is the deprecated form of console.timeStamp(). + * + * @deprecated Use console.timeStamp() instead. + */ + markTimeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timeline() method is the deprecated form of console.time(). + * + * @deprecated Use console.time() instead. + */ + timeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timelineEnd() method is the deprecated form of console.timeEnd(). + * + * @deprecated Use console.timeEnd() instead. + */ + timelineEnd(label?: string): void; +} + +interface Error { + stack?: string; +} + +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + + stackTraceLimit: number; +} + +interface SymbolConstructor { + readonly observable: symbol; +} + +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; + + /** Returns a copy with leading whitespace removed. */ + trimStart(): string; + /** Returns a copy with trailing whitespace removed. */ + trimEnd(): string; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T): Promise; +} +declare function clearTimeout(timeoutId: NodeJS.Timeout): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare function clearInterval(intervalId: NodeJS.Timeout): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; +declare namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T): Promise; +} +declare function clearImmediate(immediateId: NodeJS.Immediate): void; + +// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. +interface NodeRequireFunction { + /* tslint:disable-next-line:callable-types */ + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve: RequireResolve; + cache: any; + extensions: NodeExtensions; + main: NodeModule | undefined; +} + +interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; +} + +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[]; + paths: string[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; +interface Buffer extends Uint8Array { + constructor: typeof Buffer; + 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: Uint8Array): boolean; + compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Uint8Array, 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 | Uint8Array, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + 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 const 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' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): Buffer; + prototype: 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 any TypedArray or a new ArrayBuffer() + */ + from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: any[]): Buffer; + from(data: Uint8Array): Buffer; + /** + * Creates a new buffer containing the coerced value of an object + * A `TypeError` will be thrown if {obj} has not mentioned methods or is not of other type appropriate for `Buffer.from()` variants. + * @param obj An object supporting `Symbol.toPrimitive` or `valueOf()`. + */ + from(obj: { valueOf(): string | object } | { [Symbol.toPrimitive](hint: 'string'): string }, byteOffset?: number, length?: number): 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'. + */ + from(str: string, encoding?: string): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): 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 | undefined; + /** + * 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 | NodeJS.TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, 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: Uint8Array[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Uint8Array, buf2: Uint8Array): 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; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + poolSize: number; +}; + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ declare namespace NodeJS { + interface InspectOptions { + showHidden?: boolean; + depth?: number | null; + colors?: boolean; + customInspect?: boolean; + showProxy?: boolean; + maxArrayLength?: number | null; + breakLength?: number; + compact?: boolean; + sorted?: boolean | ((a: string, b: string) => number); + } + + interface ConsoleConstructorOptions { + stdout: WritableStream; + stderr?: WritableStream; + ignoreErrors?: boolean; + colorMode?: boolean | 'auto'; + } + + interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + + interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + class EventEmitter { + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(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: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + eventNames(): Array; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer | string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(cb?: Function): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface Events extends EventEmitter { } + + 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; + + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + } + + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + } + + interface CpuUsage { + user: number; + system: number; + } + + interface ProcessRelease { + name: string; + sourceUrl?: string; + headersUrl?: string; + libUrl?: string; + lts?: string; + } + + interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | 'cygwin'; + + type Signals = + "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | + "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | + "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type MultipleResolveType = 'resolve' | 'reject'; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = (signal: Signals) => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; + + interface Socket extends ReadWriteStream { + isTTY?: true; + } + + interface ProcessEnv { + [key: string]: string | undefined; + } + + interface WriteStream extends Socket { + readonly writableHighWaterMark: number; + readonly writableLength: number; + columns?: number; + rows?: number; + _write(chunk: any, encoding: string, callback: Function): void; + _destroy(err: Error | null, callback: Function): void; + _final(callback: Function): void; + setDefaultEncoding(encoding: string): this; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + } + interface ReadStream extends Socket { + readonly readableFlowing: boolean | null; + readonly readableHighWaterMark: number; + readonly readableLength: number; + isRaw?: boolean; + setRawMode?(mode: boolean): void; + _read(size: number): void; + _destroy(err: Error | null, callback: Function): void; + push(chunk: any, encoding?: string): boolean; + destroy(error?: Error): void; + } + interface HRTime { + (time?: [number, number]): [number, number]; bigint(): bigint; } + + interface Process extends EventEmitter { + stdout: WriteStream; + stderr: WriteStream; + stdin: ReadStream; + openStdin(): Socket; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + debugPort: number; + emitWarning(warning: string | Error, name?: string, ctor?: Function): void; + env: ProcessEnv; + exit(code?: number): never; + exitCode?: number; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: Array): void; + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + hasUncaughtExceptionCaptureCallback(): boolean; + 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; + ppid: number; + title: string; + arch: string; + platform: Platform; + mainModule?: NodeModule; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + release: ProcessRelease; + umask(mask?: number): number; + uptime(): number; + hrtime: HRTime; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] + * environment variable. + */ + allowedNodeEnvironmentFlags: ReadonlySet; + + /** + * EventEmitter + * 1. beforeExit + * 2. disconnect + * 3. exit + * 4. message + * 5. rejectionHandled + * 6. uncaughtException + * 7. unhandledRejection + * 8. warning + * 9. message + * 10. + * 11. newListener/removeListener inherited from EventEmitter + */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; + + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + } + + 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: Immediate) => void; + clearInterval: (intervalId: Timeout) => void; + clearTimeout: (timeoutId: Timeout) => 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[]) => Immediate; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + interface Timer { + ref(): this; + refresh(): this; + unref(): this; + } + + class Immediate { + ref(): this; + refresh(): this; + unref(): this; + _onImmediate: Function; // to distinguish it from the Timeout class + } + + class Timeout implements Timer { + ref(): this; + refresh(): this; + unref(): this; + } + + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequireFromPath(path: string): (path: string) => any; + static builtinModules: string[]; + + static Module: typeof Module; + + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: Module | null; + children: Module[]; + paths: string[]; + + constructor(id: string, parent?: Module); + } + + type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; } diff --git a/types/node/v10/package.json b/types/node/v10/package.json index d70cf2b291..b0c8bbe606 100644 --- a/types/node/v10/package.json +++ b/types/node/v10/package.json @@ -2,11 +2,6 @@ "private": true, "types": "index", "typesVersions": { - "<=3.1": { - "*": [ - "ts3.1/*" - ] - }, "<=3.6": { "*": [ "ts3.6/*" diff --git a/types/node/v10/ts3.1/base.d.ts b/types/node/v10/ts3.1/base.d.ts deleted file mode 100644 index cf77532198..0000000000 --- a/types/node/v10/ts3.1/base.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -// base definitions for all NodeJS modules that are not specific to any version of TypeScript -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// diff --git a/types/node/v10/ts3.1/globals.d.ts b/types/node/v10/ts3.1/globals.d.ts deleted file mode 100644 index 9e28dcd886..0000000000 --- a/types/node/v10/ts3.1/globals.d.ts +++ /dev/null @@ -1,1013 +0,0 @@ -// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build -interface Console { - Console: NodeJS.ConsoleConstructor; - /** - * A simple assertion test that verifies whether `value` is truthy. - * If it is not, an `AssertionError` is thrown. - * If provided, the error `message` is formatted using `util.format()` and used as the error message. - */ - assert(value: any, message?: string, ...optionalParams: any[]): void; - /** - * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. - * When `stdout` is not a TTY, this method does nothing. - */ - clear(): void; - /** - * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. - */ - count(label?: string): void; - /** - * Resets the internal counter specific to `label`. - */ - countReset(label?: string): void; - /** - * The `console.debug()` function is an alias for {@link console.log()}. - */ - debug(message?: any, ...optionalParams: any[]): void; - /** - * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. - * This function bypasses any custom `inspect()` function defined on `obj`. - */ - dir(obj: any, options?: NodeJS.InspectOptions): void; - /** - * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting - */ - dirxml(...data: any[]): void; - /** - * Prints to `stderr` with newline. - */ - error(message?: any, ...optionalParams: any[]): void; - /** - * Increases indentation of subsequent lines by two spaces. - * If one or more `label`s are provided, those are printed first without the additional indentation. - */ - group(...label: any[]): void; - /** - * The `console.groupCollapsed()` function is an alias for {@link console.group()}. - */ - groupCollapsed(): void; - /** - * Decreases indentation of subsequent lines by two spaces. - */ - groupEnd(): void; - /** - * The {@link console.info()} function is an alias for {@link console.log()}. - */ - info(message?: any, ...optionalParams: any[]): void; - /** - * Prints to `stdout` with newline. - */ - log(message?: any, ...optionalParams: any[]): void; - /** - * This method does not display anything unless used in the inspector. - * Prints to `stdout` the array `array` formatted as a table. - */ - table(tabularData: any, properties?: string[]): void; - /** - * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. - */ - time(label?: string): void; - /** - * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. - */ - timeEnd(label?: string): void; - /** - * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. - */ - timeLog(label?: string, ...data: any[]): void; - /** - * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. - */ - trace(message?: any, ...optionalParams: any[]): void; - /** - * The {@link console.warn()} function is an alias for {@link console.error()}. - */ - warn(message?: any, ...optionalParams: any[]): void; - - // --- Inspector mode only --- - /** - * This method does not display anything unless used in the inspector. - * The console.markTimeline() method is the deprecated form of console.timeStamp(). - * - * @deprecated Use console.timeStamp() instead. - */ - markTimeline(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Starts a JavaScript CPU profile with an optional label. - */ - profile(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. - */ - profileEnd(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Adds an event with the label `label` to the Timeline panel of the inspector. - */ - timeStamp(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * The console.timeline() method is the deprecated form of console.time(). - * - * @deprecated Use console.time() instead. - */ - timeline(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * The console.timelineEnd() method is the deprecated form of console.timeEnd(). - * - * @deprecated Use console.timeEnd() instead. - */ - timelineEnd(label?: string): void; -} - -interface Error { - stack?: string; -} - -// Declare "static" methods in Error -interface ErrorConstructor { - /** Create .stack property on a target object */ - captureStackTrace(targetObject: Object, constructorOpt?: Function): void; - - /** - * Optional override for formatting stack traces - * - * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces - */ - prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; - - stackTraceLimit: number; -} - -interface SymbolConstructor { - readonly observable: symbol; -} - -// Node.js ESNEXT support -interface String { - /** Removes whitespace from the left end of a string. */ - trimLeft(): string; - /** Removes whitespace from the right end of a string. */ - trimRight(): string; - - /** Returns a copy with leading whitespace removed. */ - trimStart(): string; - /** Returns a copy with trailing whitespace removed. */ - trimEnd(): string; -} - -/*-----------------------------------------------* - * * - * GLOBAL * - * * - ------------------------------------------------*/ -declare var process: NodeJS.Process; -declare var global: NodeJS.Global; -declare var console: Console; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare namespace setTimeout { - function __promisify__(ms: number): Promise; - function __promisify__(ms: number, value: T): Promise; -} -declare function clearTimeout(timeoutId: NodeJS.Timeout): void; -declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare function clearInterval(intervalId: NodeJS.Timeout): void; -declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; -declare namespace setImmediate { - function __promisify__(): Promise; - function __promisify__(value: T): Promise; -} -declare function clearImmediate(immediateId: NodeJS.Immediate): void; - -// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. -interface NodeRequireFunction { - /* tslint:disable-next-line:callable-types */ - (id: string): any; -} - -interface NodeRequire extends NodeRequireFunction { - resolve: RequireResolve; - cache: any; - extensions: NodeExtensions; - main: NodeModule | undefined; -} - -interface RequireResolve { - (id: string, options?: { paths?: string[]; }): string; - paths(request: string): string[] | null; -} - -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[]; - paths: string[]; -} - -declare var module: NodeModule; - -// Same as module.exports -declare var exports: any; - -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; -interface Buffer extends Uint8Array { - constructor: typeof Buffer; - 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: Uint8Array): boolean; - compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Uint8Array, 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 | Uint8Array, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - 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 const 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' - * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. - */ - new(str: string, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). - */ - new(size: number): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - new(array: Uint8Array): Buffer; - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}/{SharedArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. - */ - new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - new(array: any[]): Buffer; - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. - */ - new(buffer: Buffer): Buffer; - prototype: 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 any TypedArray or a new ArrayBuffer() - */ - from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param data data to create a new Buffer - */ - from(data: any[]): Buffer; - from(data: Uint8Array): Buffer; - /** - * Creates a new buffer containing the coerced value of an object - * A `TypeError` will be thrown if {obj} has not mentioned methods or is not of other type appropriate for `Buffer.from()` variants. - * @param obj An object supporting `Symbol.toPrimitive` or `valueOf()`. - */ - from(obj: { valueOf(): string | object } | { [Symbol.toPrimitive](hint: 'string'): string }, byteOffset?: number, length?: number): 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'. - */ - from(str: string, encoding?: string): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param values to create a new Buffer - */ - of(...items: number[]): 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 | undefined; - /** - * 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 | NodeJS.TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, 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: Uint8Array[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - compare(buf1: Uint8Array, buf2: Uint8Array): 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; - /** - * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. - */ - poolSize: number; -}; - -/*----------------------------------------------* -* * -* GLOBAL INTERFACES * -* * -*-----------------------------------------------*/ -declare namespace NodeJS { - interface InspectOptions { - showHidden?: boolean; - depth?: number | null; - colors?: boolean; - customInspect?: boolean; - showProxy?: boolean; - maxArrayLength?: number | null; - breakLength?: number; - compact?: boolean; - sorted?: boolean | ((a: string, b: string) => number); - } - - interface ConsoleConstructorOptions { - stdout: WritableStream; - stderr?: WritableStream; - ignoreErrors?: boolean; - colorMode?: boolean | 'auto'; - } - - interface ConsoleConstructor { - prototype: Console; - new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; - new(options: ConsoleConstructorOptions): Console; - } - - interface CallSite { - /** - * Value of "this" - */ - getThis(): any; - - /** - * Type of "this" as a string. - * This is the name of the function stored in the constructor field of - * "this", if available. Otherwise the object's [[Class]] internal - * property. - */ - getTypeName(): string | null; - - /** - * Current function - */ - getFunction(): Function | undefined; - - /** - * Name of the current function, typically its name property. - * If a name property is not available an attempt will be made to try - * to infer a name from the function's context. - */ - getFunctionName(): string | null; - - /** - * Name of the property [of "this" or one of its prototypes] that holds - * the current function - */ - getMethodName(): string | null; - - /** - * Name of the script [if this function was defined in a script] - */ - getFileName(): string | null; - - /** - * Current line number [if this function was defined in a script] - */ - getLineNumber(): number | null; - - /** - * Current column number [if this function was defined in a script] - */ - getColumnNumber(): number | null; - - /** - * A call site object representing the location where eval was called - * [if this function was created using a call to eval] - */ - getEvalOrigin(): string | undefined; - - /** - * Is this a toplevel invocation, that is, is "this" the global object? - */ - isToplevel(): boolean; - - /** - * Does this call take place in code defined by a call to eval? - */ - isEval(): boolean; - - /** - * Is this call in native V8 code? - */ - isNative(): boolean; - - /** - * Is this a constructor call? - */ - isConstructor(): boolean; - } - - interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } - - class EventEmitter { - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - rawListeners(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: (...args: any[]) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - eventNames(): Array; - } - - interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: WritableStream): this; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: ReadableStream): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - interface WritableStream extends EventEmitter { - writable: boolean; - write(buffer: Buffer | string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(cb?: Function): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - interface ReadWriteStream extends ReadableStream, WritableStream { } - - interface Events extends EventEmitter { } - - 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; - - addListener(event: string, listener: (...args: any[]) => void): this; - on(event: string, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - removeListener(event: string, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string): this; - } - - interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - external: number; - } - - interface CpuUsage { - user: number; - system: number; - } - - interface ProcessRelease { - name: string; - sourceUrl?: string; - headersUrl?: string; - libUrl?: string; - lts?: string; - } - - interface ProcessVersions { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } - - type Platform = 'aix' - | 'android' - | 'darwin' - | 'freebsd' - | 'linux' - | 'openbsd' - | 'sunos' - | 'win32' - | 'cygwin'; - - type Signals = - "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | - "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | - "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | - "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; - - type MultipleResolveType = 'resolve' | 'reject'; - - type BeforeExitListener = (code: number) => void; - type DisconnectListener = () => void; - type ExitListener = (code: number) => void; - type RejectionHandledListener = (promise: Promise) => void; - type UncaughtExceptionListener = (error: Error) => void; - type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; - type WarningListener = (warning: Error) => void; - type MessageListener = (message: any, sendHandle: any) => void; - type SignalsListener = (signal: Signals) => void; - type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; - - interface Socket extends ReadWriteStream { - isTTY?: true; - } - - interface ProcessEnv { - [key: string]: string | undefined; - } - - interface WriteStream extends Socket { - readonly writableHighWaterMark: number; - readonly writableLength: number; - columns?: number; - rows?: number; - _write(chunk: any, encoding: string, callback: Function): void; - _destroy(err: Error | null, callback: Function): void; - _final(callback: Function): void; - setDefaultEncoding(encoding: string): this; - cork(): void; - uncork(): void; - destroy(error?: Error): void; - } - interface ReadStream extends Socket { - readonly readableFlowing: boolean | null; - readonly readableHighWaterMark: number; - readonly readableLength: number; - isRaw?: boolean; - setRawMode?(mode: boolean): void; - _read(size: number): void; - _destroy(err: Error | null, callback: Function): void; - push(chunk: any, encoding?: string): boolean; - destroy(error?: Error): void; - } - - interface HRTime { - (time?: [number, number]): [number, number]; - } - - interface Process extends EventEmitter { - stdout: WriteStream; - stderr: WriteStream; - stdin: ReadStream; - openStdin(): Socket; - argv: string[]; - argv0: string; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - debugPort: number; - emitWarning(warning: string | Error, name?: string, ctor?: Function): void; - env: ProcessEnv; - exit(code?: number): never; - exitCode?: number; - getgid(): number; - setgid(id: number | string): void; - getuid(): number; - setuid(id: number | string): void; - geteuid(): number; - seteuid(id: number | string): void; - getegid(): number; - setegid(id: number | string): void; - getgroups(): number[]; - setgroups(groups: Array): void; - setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; - hasUncaughtExceptionCaptureCallback(): boolean; - 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; - ppid: number; - title: string; - arch: string; - platform: Platform; - mainModule?: NodeModule; - memoryUsage(): MemoryUsage; - cpuUsage(previousValue?: CpuUsage): CpuUsage; - nextTick(callback: Function, ...args: any[]): void; - release: ProcessRelease; - umask(mask?: number): number; - uptime(): number; - hrtime: HRTime; - domain: Domain; - - // Worker - send?(message: any, sendHandle?: any): void; - disconnect(): void; - connected: boolean; - - /** - * The `process.allowedNodeEnvironmentFlags` property is a special, - * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] - * environment variable. - */ - allowedNodeEnvironmentFlags: ReadonlySet; - - /** - * EventEmitter - * 1. beforeExit - * 2. disconnect - * 3. exit - * 4. message - * 5. rejectionHandled - * 6. uncaughtException - * 7. unhandledRejection - * 8. warning - * 9. message - * 10. - * 11. newListener/removeListener inherited from EventEmitter - */ - addListener(event: "beforeExit", listener: BeforeExitListener): this; - addListener(event: "disconnect", listener: DisconnectListener): this; - addListener(event: "exit", listener: ExitListener): this; - addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - addListener(event: "warning", listener: WarningListener): this; - addListener(event: "message", listener: MessageListener): this; - addListener(event: Signals, listener: SignalsListener): this; - addListener(event: "newListener", listener: NewListenerListener): this; - addListener(event: "removeListener", listener: RemoveListenerListener): this; - addListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - emit(event: "beforeExit", code: number): boolean; - emit(event: "disconnect"): boolean; - emit(event: "exit", code: number): boolean; - emit(event: "rejectionHandled", promise: Promise): boolean; - emit(event: "uncaughtException", error: Error): boolean; - emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; - emit(event: "warning", warning: Error): boolean; - emit(event: "message", message: any, sendHandle: any): this; - emit(event: Signals, signal: Signals): boolean; - emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; - emit(event: "multipleResolves", listener: MultipleResolveListener): this; - - on(event: "beforeExit", listener: BeforeExitListener): this; - on(event: "disconnect", listener: DisconnectListener): this; - on(event: "exit", listener: ExitListener): this; - on(event: "rejectionHandled", listener: RejectionHandledListener): this; - on(event: "uncaughtException", listener: UncaughtExceptionListener): this; - on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - on(event: "warning", listener: WarningListener): this; - on(event: "message", listener: MessageListener): this; - on(event: Signals, listener: SignalsListener): this; - on(event: "newListener", listener: NewListenerListener): this; - on(event: "removeListener", listener: RemoveListenerListener): this; - on(event: "multipleResolves", listener: MultipleResolveListener): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "beforeExit", listener: BeforeExitListener): this; - once(event: "disconnect", listener: DisconnectListener): this; - once(event: "exit", listener: ExitListener): this; - once(event: "rejectionHandled", listener: RejectionHandledListener): this; - once(event: "uncaughtException", listener: UncaughtExceptionListener): this; - once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - once(event: "warning", listener: WarningListener): this; - once(event: "message", listener: MessageListener): this; - once(event: Signals, listener: SignalsListener): this; - once(event: "newListener", listener: NewListenerListener): this; - once(event: "removeListener", listener: RemoveListenerListener): this; - once(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependListener(event: "beforeExit", listener: BeforeExitListener): this; - prependListener(event: "disconnect", listener: DisconnectListener): this; - prependListener(event: "exit", listener: ExitListener): this; - prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependListener(event: "warning", listener: WarningListener): this; - prependListener(event: "message", listener: MessageListener): this; - prependListener(event: Signals, listener: SignalsListener): this; - prependListener(event: "newListener", listener: NewListenerListener): this; - prependListener(event: "removeListener", listener: RemoveListenerListener): this; - prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; - prependOnceListener(event: "disconnect", listener: DisconnectListener): this; - prependOnceListener(event: "exit", listener: ExitListener): this; - prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependOnceListener(event: "warning", listener: WarningListener): this; - prependOnceListener(event: "message", listener: MessageListener): this; - prependOnceListener(event: Signals, listener: SignalsListener): this; - prependOnceListener(event: "newListener", listener: NewListenerListener): this; - prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; - prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - listeners(event: "beforeExit"): BeforeExitListener[]; - listeners(event: "disconnect"): DisconnectListener[]; - listeners(event: "exit"): ExitListener[]; - listeners(event: "rejectionHandled"): RejectionHandledListener[]; - listeners(event: "uncaughtException"): UncaughtExceptionListener[]; - listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; - listeners(event: "warning"): WarningListener[]; - listeners(event: "message"): MessageListener[]; - listeners(event: Signals): SignalsListener[]; - listeners(event: "newListener"): NewListenerListener[]; - listeners(event: "removeListener"): RemoveListenerListener[]; - listeners(event: "multipleResolves"): MultipleResolveListener[]; - } - - 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: Immediate) => void; - clearInterval: (intervalId: Timeout) => void; - clearTimeout: (timeoutId: Timeout) => 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[]) => Immediate; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } - - interface Timer { - ref(): this; - refresh(): this; - unref(): this; - } - - class Immediate { - ref(): this; - refresh(): this; - unref(): this; - _onImmediate: Function; // to distinguish it from the Timeout class - } - - class Timeout implements Timer { - ref(): this; - refresh(): this; - unref(): this; - } - - class Module { - static runMain(): void; - static wrap(code: string): string; - static createRequireFromPath(path: string): (path: string) => any; - static builtinModules: string[]; - - static Module: typeof Module; - - exports: any; - require: NodeRequireFunction; - id: string; - filename: string; - loaded: boolean; - parent: Module | null; - children: Module[]; - paths: string[]; - - constructor(id: string, parent?: Module); - } - - type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; -} diff --git a/types/node/v10/ts3.1/index.d.ts b/types/node/v10/ts3.1/index.d.ts deleted file mode 100644 index 91e372a14c..0000000000 --- a/types/node/v10/ts3.1/index.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.1. - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 - -// NOTE: Augmentations for TypeScript 3.1 and later should use individual files for overrides -// within the respective ~/ts3.1 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.1, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -/// - -// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in +ts3.7 -/// - -// TypeScript 2.1-specific augmentations: - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } -interface Set {} -interface ReadonlySet {} -interface IteratorResult { } -interface Iterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IterableIterator { } -interface AsyncIterableIterator {} -interface SymbolConstructor { - readonly iterator: symbol; - readonly asyncIterator: symbol; -} -declare var Symbol: SymbolConstructor; -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; -} - -declare module "util" { - namespace inspect { - const custom: symbol; - } - namespace promisify { - const custom: symbol; - } - namespace types { - function isBigInt64Array(value: any): boolean; - function isBigUint64Array(value: any): boolean; - } -} diff --git a/types/node/v10/ts3.1/node-tests.ts b/types/node/v10/ts3.1/node-tests.ts deleted file mode 100644 index fbf8d657fe..0000000000 --- a/types/node/v10/ts3.1/node-tests.ts +++ /dev/null @@ -1,5061 +0,0 @@ -import assert = require("assert"); -import * as fs from "fs"; -import * as events from "events"; -import events2 = require("events"); -import * as zlib from "zlib"; -import * as url from "url"; -import * as util from "util"; -import * as crypto from "crypto"; -import * as tls from "tls"; -import * as http from "http"; -import * as https from "https"; -import * as net from "net"; -import * as tty from "tty"; -import * as dgram from "dgram"; -import * as querystring from "querystring"; -import * as path from "path"; -import * as readline from "readline"; -import * as childProcess from "child_process"; -import * as cluster from "cluster"; -import * as workerThreads from "worker_threads"; -import * as os from "os"; -import * as vm from "vm"; -import * as console2 from "console"; -import * as string_decoder from "string_decoder"; -import * as stream from "stream"; -import * as timers from "timers"; -import * as repl from "repl"; -import * as v8 from "v8"; -import * as dns from "dns"; -import * as async_hooks from "async_hooks"; -import * as http2 from "http2"; -import * as inspector from "inspector"; -import * as perf_hooks from "perf_hooks"; -import * as trace_events from "trace_events"; -import Module = require("module"); - -// Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; - -////////////////////////////////////////////////////////// -/// Global Tests : https://nodejs.org/api/global.html /// -////////////////////////////////////////////////////////// -{ - { - const x: NodeModule = {} as any; - const y: NodeModule = {} as any; - x.children.push(y); - x.parent = require.main; - require.main = y; - const hrtimeArray: [number, number] = process.hrtime(); - } -} - -////////////////////////////////////////////////////////// -/// Assert Tests : https://nodejs.org/api/assert.html /// -////////////////////////////////////////////////////////// - -{ - { - assert(1 + 1 - 2 === 0, "The universe isn't how it should."); - - assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - - assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); - - assert.doesNotThrow(() => { - const b = false; - if (b) { throw new Error("a hammer at your face"); } - }, undefined, "What the...*crunch*"); - - assert.equal(3, "3", "uses == comparator"); - - if (!!true) assert.fail('stuff broke'); - - if (!!true) assert.fail('actual', 'expected', 'message'); - - if (!!true) assert.fail(1, 2, undefined, '>'); - - assert.ifError(0); - - assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - - assert.notEqual(1, 2, "uses != comparator"); - - assert.notStrictEqual(2, "2", "uses === comparator"); - - assert.ok(true); - assert.ok(1); - - assert.strictEqual(1, 1, "uses === comparator"); - - assert.throws(() => { throw new Error("a hammer at your face"); }, undefined, "DODGED IT"); - - assert.strict.strict.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); - } -} - -//////////////////////////////////////////////////// -/// Events tests : http://nodejs.org/api/events.html -//////////////////////////////////////////////////// - -{ - const emitter: events.EventEmitter = new events.EventEmitter(); - const event: string | symbol = ''; - const listener: (...args: any[]) => void = () => {}; - const any: any = 1; - - { - let result: events.EventEmitter; - - result = emitter.addListener(event, listener); - result = emitter.on(event, listener); - result = emitter.once(event, listener); - result = emitter.prependListener(event, listener); - result = emitter.prependOnceListener(event, listener); - result = emitter.removeListener(event, listener); - result = emitter.off(event, listener); - result = emitter.removeAllListeners(); - result = emitter.removeAllListeners(event); - result = emitter.setMaxListeners(42); - } - - { - let result: number; - - result = events.EventEmitter.defaultMaxListeners; - result = events.EventEmitter.listenerCount(emitter, event); // deprecated - - result = emitter.getMaxListeners(); - result = emitter.listenerCount(event); - } - - { - let result: Function[]; - - result = emitter.listeners(event); - } - - { - let result: boolean; - - result = emitter.emit(event); - result = emitter.emit(event, any); - result = emitter.emit(event, any, any); - result = emitter.emit(event, any, any, any); - } - - { - let result: Array; - - result = emitter.eventNames(); - } - - { - class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } - } - } - - { - new events2(); - } -} - -//////////////////////////////////////////////////// -/// File system tests : http://nodejs.org/api/fs.html -//////////////////////////////////////////////////// - -{ - { - fs.writeFile("thebible.txt", - "Do unto others as you would have them do unto you.", - assert.ifError); - - fs.write(1234, "test", () => { }); - - fs.writeFile("Harry Potter", - "\"You be wizzing, Harry,\" jived Dumbledore.", - { - encoding: "ascii" - }, - assert.ifError); - - fs.writeFile("testfile", "content", "utf8", assert.ifError); - - fs.writeFileSync("testfile", "content", "utf8"); - fs.writeFileSync("testfile", "content", { encoding: "utf8" }); - fs.writeFileSync("testfile", new DataView(new ArrayBuffer(1)), { encoding: "utf8" }); - } - - { - fs.appendFile("testfile", "foobar", "utf8", assert.ifError); - fs.appendFile("testfile", "foobar", { encoding: "utf8" }, assert.ifError); - fs.appendFileSync("testfile", "foobar", "utf8"); - fs.appendFileSync("testfile", "foobar", { encoding: "utf8" }); - } - - { - let content: string; - let buffer: Buffer; - let stringOrBuffer: string | Buffer; - const nullEncoding: string | null = null; - const stringEncoding: string | null = 'utf8'; - - content = fs.readFileSync('testfile', 'utf8'); - content = fs.readFileSync('testfile', { encoding: 'utf8' }); - stringOrBuffer = fs.readFileSync('testfile', stringEncoding); - stringOrBuffer = fs.readFileSync('testfile', { encoding: stringEncoding }); - - buffer = fs.readFileSync('testfile'); - buffer = fs.readFileSync('testfile', null); - buffer = fs.readFileSync('testfile', { encoding: null }); - stringOrBuffer = fs.readFileSync('testfile', nullEncoding); - stringOrBuffer = fs.readFileSync('testfile', { encoding: nullEncoding }); - - buffer = fs.readFileSync('testfile', { flag: 'r' }); - - fs.readFile('testfile', 'utf8', (err, data) => content = data); - fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); - fs.readFile('testfile', stringEncoding, (err, data) => stringOrBuffer = data); - fs.readFile('testfile', { encoding: stringEncoding }, (err, data) => stringOrBuffer = data); - - fs.readFile('testfile', (err, data) => buffer = data); - fs.readFile('testfile', null, (err, data) => buffer = data); - fs.readFile('testfile', { encoding: null }, (err, data) => buffer = data); - fs.readFile('testfile', nullEncoding, (err, data) => stringOrBuffer = data); - fs.readFile('testfile', { encoding: nullEncoding }, (err, data) => stringOrBuffer = data); - - fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); - } - - { - fs.read(1, new DataView(new ArrayBuffer(1)), 0, 1, 0, (err: NodeJS.ErrnoException, bytesRead: number, buffer: DataView) => {}); - } - - { - fs.readSync(1, new DataView(new ArrayBuffer(1)), 0, 1, 0); - } - - { - let errno: number; - fs.readFile('testfile', (err, data) => { - if (err && err.errno) { - errno = err.errno; - } - }); - } - - { - let listS: string[]; - listS = fs.readdirSync('path'); - listS = fs.readdirSync('path', { encoding: 'utf8' }); - listS = fs.readdirSync('path', { encoding: null }); - listS = fs.readdirSync('path', { encoding: undefined }); - listS = fs.readdirSync('path', 'utf8'); - listS = fs.readdirSync('path', null); - listS = fs.readdirSync('path', undefined); - const listDir: fs.Dirent[] = fs.readdirSync('path', { withFileTypes: true }); - const listDir2: Buffer[] = fs.readdirSync('path', { withFileTypes: false, encoding: 'buffer' }); - const listDir3: fs.Dirent[] = fs.readdirSync('path', { encoding: 'utf8', withFileTypes: true }); - - let listB: Buffer[]; - listB = fs.readdirSync('path', { encoding: 'buffer' }); - listB = fs.readdirSync("path", 'buffer'); - - const enc = 'buffer'; - fs.readdirSync('path', { encoding: enc }); - fs.readdirSync('path', { }); - - fs.readdir('path', { withFileTypes: true }, (err: NodeJS.ErrnoException, files: fs.Dirent[]) => {}); - } - - async function testPromisify() { - const rd = util.promisify(fs.readdir); - let listS: string[]; - listS = await rd('path'); - listS = await rd('path', 'utf8'); - listS = await rd('path', null); - listS = await rd('path', undefined); - listS = await rd('path', { encoding: 'utf8' }); - listS = await rd('path', { encoding: null }); - listS = await rd('path', { encoding: null, withFileTypes: false }); - listS = await rd('path', { encoding: 'utf8', withFileTypes: false }); - const listDir: fs.Dirent[] = await rd('path', { withFileTypes: true }); - const listDir2: Buffer[] = await rd('path', { withFileTypes: false, encoding: 'buffer' }); - const listDir3: fs.Dirent[] = await rd('path', { encoding: 'utf8', withFileTypes: true }); - } - - { - fs.mkdtemp('/tmp/foo-', (err, folder) => { - console.log(folder); - // Prints: /tmp/foo-itXde2 - }); - } - - { - let tempDir: string; - tempDir = fs.mkdtempSync('/tmp/foo-'); - } - - { - fs.watch('/tmp/foo-', (event, filename) => { - console.log(event, filename); - }); - - fs.watch('/tmp/foo-', 'utf8', (event, filename) => { - console.log(event, filename); - }); - - fs.watch('/tmp/foo-', { - recursive: true, - persistent: true, - encoding: 'utf8' - }, (event, filename) => { - console.log(event, filename); - }); - } - - { - fs.access('/path/to/folder', (err) => { }); - - fs.access(Buffer.from(''), (err) => { }); - - fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - - fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - - fs.accessSync('/path/to/folder'); - - fs.accessSync(Buffer.from('')); - - fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); - - fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); - } - - { - let s: string; - let b: Buffer; - fs.readlink('/path/to/folder', (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', undefined, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', 'utf8', (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', 'buffer', (err, linkString) => b = linkString); - fs.readlink('/path/to/folder', s, (err, linkString) => typeof linkString === 'string' ? s = linkString : b = linkString); - fs.readlink('/path/to/folder', {}, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', { encoding: undefined }, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', { encoding: 'utf8' }, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', { encoding: 'buffer' }, (err, linkString) => b = linkString); - fs.readlink('/path/to/folder', { encoding: s }, (err, linkString) => typeof linkString === "string" ? s = linkString : b = linkString); - - s = fs.readlinkSync('/path/to/folder'); - s = fs.readlinkSync('/path/to/folder', undefined); - s = fs.readlinkSync('/path/to/folder', 'utf8'); - b = fs.readlinkSync('/path/to/folder', 'buffer'); - const v1 = fs.readlinkSync('/path/to/folder', s); - typeof v1 === "string" ? s = v1 : b = v1; - - s = fs.readlinkSync('/path/to/folder', {}); - s = fs.readlinkSync('/path/to/folder', { encoding: undefined }); - s = fs.readlinkSync('/path/to/folder', { encoding: 'utf8' }); - b = fs.readlinkSync('/path/to/folder', { encoding: 'buffer' }); - const v2 = fs.readlinkSync('/path/to/folder', { encoding: s }); - typeof v2 === "string" ? s = v2 : b = v2; - } - - { - let s: string; - let b: Buffer; - fs.realpath('/path/to/folder', (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath); - fs.realpath('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath); - fs.realpath('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath); - fs.realpath('/path/to/folder', { encoding: s }, (err, resolvedPath) => typeof resolvedPath === "string" ? s = resolvedPath : b = resolvedPath); - - s = fs.realpathSync('/path/to/folder'); - s = fs.realpathSync('/path/to/folder', undefined); - s = fs.realpathSync('/path/to/folder', 'utf8'); - b = fs.realpathSync('/path/to/folder', 'buffer'); - const v1 = fs.realpathSync('/path/to/folder', s); - typeof v1 === "string" ? s = v1 : b = v1; - - s = fs.realpathSync('/path/to/folder', {}); - s = fs.realpathSync('/path/to/folder', { encoding: undefined }); - s = fs.realpathSync('/path/to/folder', { encoding: 'utf8' }); - b = fs.realpathSync('/path/to/folder', { encoding: 'buffer' }); - const v2 = fs.realpathSync('/path/to/folder', { encoding: s }); - typeof v2 === "string" ? s = v2 : b = v2; - - // native - fs.realpath.native('/path/to/folder', (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath); - fs.realpath.native('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath); - fs.realpath.native('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath); - fs.realpath.native('/path/to/folder', { encoding: s }, (err, resolvedPath) => typeof resolvedPath === "string" ? s = resolvedPath : b = resolvedPath); - - s = fs.realpathSync.native('/path/to/folder'); - s = fs.realpathSync.native('/path/to/folder', undefined); - s = fs.realpathSync.native('/path/to/folder', 'utf8'); - b = fs.realpathSync.native('/path/to/folder', 'buffer'); - const v3 = fs.realpathSync.native('/path/to/folder', s); - typeof v3 === "string" ? s = v3 : b = v3; - - s = fs.realpathSync.native('/path/to/folder', {}); - s = fs.realpathSync.native('/path/to/folder', { encoding: undefined }); - s = fs.realpathSync.native('/path/to/folder', { encoding: 'utf8' }); - b = fs.realpathSync.native('/path/to/folder', { encoding: 'buffer' }); - const v4 = fs.realpathSync.native('/path/to/folder', { encoding: s }); - typeof v4 === "string" ? s = v4 : b = v4; - } - - { - fs.copyFile('/path/to/src', '/path/to/dest', (err) => console.error(err)); - fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL, (err) => console.error(err)); - fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE, (err) => console.error(err)); - fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE_FORCE, (err) => console.error(err)); - - fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL); - fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE); - fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE_FORCE); - - const cf = util.promisify(fs.copyFile); - cf('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL).then(console.log); - } - - { - fs.mkdir('some/test/path', { - recursive: true, - mode: 0o777, - }, () => { - }); - - fs.mkdirSync('some/test/path', { - recursive: true, - mode: 0o777, - }); - } - - { - let names: Promise; - let buffers: Promise; - let namesOrBuffers: Promise; - let entries: Promise; - - names = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: false }); - buffers = fs.promises.readdir('/path/to/dir', { encoding: 'buffer', withFileTypes: false }); - namesOrBuffers = fs.promises.readdir('/path/to/dir', { encoding: 'SOME OTHER', withFileTypes: false }); - entries = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: true }); - } -} - -/////////////////////////////////////////////////////// -/// Buffer tests : https://nodejs.org/api/buffer.html -/////////////////////////////////////////////////////// - -function bufferTests() { - const utf8Buffer = new Buffer('test'); - const base64Buffer = new Buffer('', 'base64'); - const octets: Uint8Array = null; - const octetBuffer = new Buffer(octets); - const sharedBuffer = new Buffer(octets.buffer); - const copiedBuffer = new Buffer(utf8Buffer); - console.log(Buffer.isBuffer(octetBuffer)); - console.log(Buffer.isEncoding('utf8')); - console.log(Buffer.byteLength('xyz123')); - console.log(Buffer.byteLength('xyz123', 'ascii')); - const result1 = Buffer.concat([utf8Buffer, base64Buffer]); - const result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999); - - // Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64() - { - const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); - buf.swap16(); - buf.swap32(); - buf.swap64(); - } - - // Class Method: Buffer.from(data) - { - // Array - const buf1: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); - // Buffer - const buf2: Buffer = Buffer.from(buf1); - // String - const buf3: Buffer = Buffer.from('this is a tést'); - // ArrayBuffer - const arrUint16: Uint16Array = new Uint16Array(2); - arrUint16[0] = 5000; - arrUint16[1] = 4000; - const buf4: Buffer = Buffer.from(arrUint16.buffer); - const arrUint8: Uint8Array = new Uint8Array(2); - const buf5: Buffer = Buffer.from(arrUint8); - const buf6: Buffer = Buffer.from(buf1); - const buf7: Buffer = Buffer.from(undefined as SharedArrayBuffer); - } - - // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) - { - const arr: Uint16Array = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; - - let buf: Buffer; - buf = Buffer.from(arr.buffer, 1); - buf = Buffer.from(arr.buffer, 0, 1); - } - - // Class Method: Buffer.from(str[, encoding]) - { - const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); - } - - // Class Method: Buffer.alloc(size[, fill[, encoding]]) - { - const buf1: Buffer = Buffer.alloc(5); - const buf2: Buffer = Buffer.alloc(5, 'a'); - const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); - } - // Class Method: Buffer.allocUnsafe(size) - { - const buf: Buffer = Buffer.allocUnsafe(5); - } - // Class Method: Buffer.allocUnsafeSlow(size) - { - const buf: Buffer = Buffer.allocUnsafeSlow(10); - } - - // Class Method byteLenght - { - let len: number; - len = Buffer.byteLength("foo"); - len = Buffer.byteLength("foo", "utf8"); - - const b = Buffer.from("bar"); - len = Buffer.byteLength(b); - len = Buffer.byteLength(b, "utf16le"); - - const ab = new ArrayBuffer(15); - len = Buffer.byteLength(ab); - len = Buffer.byteLength(ab, "ascii"); - - const dv = new DataView(ab); - len = Buffer.byteLength(dv); - len = Buffer.byteLength(dv, "utf16le"); - } - - // Class Method poolSize - { - let s: number; - s = Buffer.poolSize; - Buffer.poolSize = 4096; - } - - // Test that TS 1.6 works with the 'as Buffer' annotation - // on isBuffer. - let a: Buffer | number; - a = new Buffer(10); - if (Buffer.isBuffer(a)) { - a.writeUInt8(3, 4); - } - - // write* methods return offsets. - const b = new Buffer(16); - let result: number = b.writeUInt32LE(0, 0); - result = b.writeUInt16LE(0, 4); - result = b.writeUInt8(0, 6); - result = b.writeInt8(0, 7); - result = b.writeDoubleLE(0, 8); - - // fill returns the input buffer. - b.fill('a').fill('b'); - - { - const buffer = new Buffer('123'); - let index: number; - index = buffer.indexOf("23"); - index = buffer.indexOf("23", 1); - index = buffer.indexOf("23", 1, "utf8"); - index = buffer.indexOf(23); - index = buffer.indexOf(buffer); - } - - { - const buffer = new Buffer('123'); - let index: number; - index = buffer.lastIndexOf("23"); - index = buffer.lastIndexOf("23", 1); - index = buffer.lastIndexOf("23", 1, "utf8"); - index = buffer.lastIndexOf(23); - index = buffer.lastIndexOf(buffer); - } - - { - const buffer = new Buffer('123'); - const val: [number, number] = [1, 1]; - - /* comment out for --target es5 - for (let entry of buffer.entries()) { - val = entry; - } - */ - } - - { - const buffer = new Buffer('123'); - let includes: boolean; - includes = buffer.includes("23"); - includes = buffer.includes("23", 1); - includes = buffer.includes("23", 1, "utf8"); - includes = buffer.includes(23); - includes = buffer.includes(23, 1); - includes = buffer.includes(23, 1, "utf8"); - includes = buffer.includes(buffer); - includes = buffer.includes(buffer, 1); - includes = buffer.includes(buffer, 1, "utf8"); - } - - { - const buffer = new Buffer('123'); - const val = 1; - - /* comment out for --target es5 - for (let key of buffer.keys()) { - val = key; - } - */ - } - - { - const buffer = new Buffer('123'); - const val = 1; - - /* comment out for --target es5 - for (let value of buffer.values()) { - val = value; - } - */ - } - - // Imported Buffer from buffer module works properly - { - const b = new ImportedBuffer('123'); - b.writeUInt8(0, 6); - const sb = new ImportedSlowBuffer(43); - b.writeUInt8(0, 6); - } - - // Buffer has Uint8Array's buffer field (an ArrayBuffer). - { - const buffer = new Buffer('123'); - const octets = new Uint8Array(buffer.buffer); - } - - // Buffer module, transcode function - { - transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer - - const source: TranscodeEncoding = 'utf8'; - const target: TranscodeEncoding = 'ascii'; - transcode(Buffer.from('€'), source, target); // $ExpectType Buffer - } -} - -//////////////////////////////////////////////////// -/// Url tests : http://nodejs.org/api/url.html -//////////////////////////////////////////////////// - -{ - { - url.format(url.parse('http://www.example.com/xyz')); - - url.format('http://www.example.com/xyz'); - - // https://google.com/search?q=you're%20a%20lizard%2C%20gary - url.format({ - protocol: 'https', - host: "google.com", - pathname: 'search', - query: { q: "you're a lizard, gary" } - }); - - const myURL = new url.URL('https://a:b@你好你好?abc#foo'); - url.format(myURL, { fragment: false, unicode: true, auth: false }); - } - - { - const helloUrl = url.parse('http://example.com/?hello=world', true); - let helloQuery = helloUrl.query['hello']; - assert.equal(helloUrl.query['hello'], 'world'); - - let strUrl = url.parse('http://example.com/?hello=world'); - let queryStr: string = strUrl.query; - - strUrl = url.parse('http://example.com/?hello=world', false); - queryStr = strUrl.query; - - function getBoolean(): boolean { return false; } - const urlUrl = url.parse('http://example.com/?hello=world', getBoolean()); - if (typeof(urlUrl.query) === 'string') { - queryStr = urlUrl.query; - } else if (urlUrl.query) { - helloQuery = urlUrl.query['hello']; - } - } - - { - const ascii: string = url.domainToASCII('español.com'); - const unicode: string = url.domainToUnicode('xn--espaol-zwa.com'); - } - - { - let myURL = new url.URL('https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.hash, '#bar'); - assert.equal(myURL.host, 'example.org:81'); - assert.equal(myURL.hostname, 'example.org'); - assert.equal(myURL.href, 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.origin, 'https://example.org:81'); - assert.equal(myURL.password, 'thepwd'); - assert.equal(myURL.username, 'theuser'); - assert.equal(myURL.pathname, '/foo/path'); - assert.equal(myURL.port, "81"); - assert.equal(myURL.protocol, "https:"); - assert.equal(myURL.search, "?query=string"); - assert.equal(myURL.toString(), 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert(myURL.searchParams instanceof url.URLSearchParams); - - myURL.host = 'example.org:82'; - myURL.hostname = 'example.com'; - myURL.href = 'http://other.com'; - myURL.hash = 'baz'; - myURL.password = "otherpwd"; - myURL.username = "otheruser"; - myURL.pathname = "/otherPath"; - myURL.port = "82"; - myURL.protocol = "http"; - myURL.search = "a=b"; - assert.equal(myURL.href, 'http://otheruser:otherpwd@other.com:82/otherPath?a=b#baz'); - - myURL = new url.URL('/foo', 'https://example.org/'); - assert.equal(myURL.href, 'https://example.org/foo'); - assert.equal(myURL.toJSON(), myURL.href); - } - - { - const searchParams = new url.URLSearchParams('abc=123'); - - assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { - assert.equal(name, 'abc'); - assert.equal(value, '123'); - assert.equal(me, searchParams); - }); - - assert.equal(searchParams.get('abc'), '123'); - - searchParams.append('abc', 'xyz'); - - assert.deepEqual(searchParams.getAll('abc'), ['123', 'xyz']); - - const entries = searchParams.entries(); - assert.deepEqual(entries.next(), { value: ["abc", "123"], done: false }); - assert.deepEqual(entries.next(), { value: ["abc", "xyz"], done: false }); - assert.deepEqual(entries.next(), { value: undefined, done: true }); - - const keys = searchParams.keys(); - assert.deepEqual(keys.next(), { value: "abc", done: false }); - assert.deepEqual(keys.next(), { value: "abc", done: false }); - assert.deepEqual(keys.next(), { value: undefined, done: true }); - - const values = searchParams.values(); - assert.deepEqual(values.next(), { value: "123", done: false }); - assert.deepEqual(values.next(), { value: "xyz", done: false }); - assert.deepEqual(values.next(), { value: undefined, done: true }); - - searchParams.set('abc', 'b'); - assert.deepEqual(searchParams.getAll('abc'), ['b']); - - searchParams.delete('a'); - assert(!searchParams.has('a')); - assert.equal(searchParams.get('a'), null); - - searchParams.sort(); - } - - { - const searchParams = new url.URLSearchParams({ - user: 'abc', - query: ['first', 'second'] - }); - - assert.equal(searchParams.toString(), 'user=abc&query=first%2Csecond'); - assert.deepEqual(searchParams.getAll('query'), ['first,second']); - } - - { - // Using an array - const params = new url.URLSearchParams([ - ['user', 'abc'], - ['query', 'first'], - ['query', 'second'] - ]); - assert.equal(params.toString(), 'user=abc&query=first&query=second'); - } - - { - let path: string = url.fileURLToPath('file://test'); - path = url.fileURLToPath(new url.URL('file://test')); - } - - { - const path: url.URL = url.pathToFileURL('file://test'); - } -} - -///////////////////////////////////////////////////// -/// util tests : https://nodejs.org/api/util.html /// -///////////////////////////////////////////////////// - -{ - { - // Old and new util.inspect APIs - util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], false, null); - util.inspect(["This is nice"], { - colors: true, - depth: 5, - customInspect: false, - showProxy: true, - maxArrayLength: 10, - breakLength: 20, - compact: true, - sorted(a, b) { - return b.localeCompare(a); - }, - }); - util.inspect(["This is nice"], { - colors: true, - depth: null, - customInspect: false, - showProxy: true, - maxArrayLength: null, - breakLength: Infinity, - compact: false, - sorted: true, - }); - assert(typeof util.inspect.custom === 'symbol'); - - util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); - - // util.callbackify - // tslint:disable-next-line no-unnecessary-class - class callbackifyTest { - static fn(): Promise { - assert(arguments.length === 0); - - return Promise.resolve(); - } - - static fnE(): Promise { - assert(arguments.length === 0); - - return Promise.reject(new Error('fail')); - } - - static fnT1(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.resolve(); - } - - static fnT1E(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.reject(new Error('fail')); - } - - static fnTResult(): Promise { - assert(arguments.length === 0); - - return Promise.resolve('result'); - } - - static fnTResultE(): Promise { - assert(arguments.length === 0); - - return Promise.reject(new Error('fail')); - } - - static fnT1TResult(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.resolve('result'); - } - - static fnT1TResultE(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.reject(new Error('fail')); - } - - static test(): void { - const cfn = util.callbackify(callbackifyTest.fn); - const cfnE = util.callbackify(callbackifyTest.fnE); - const cfnT1 = util.callbackify(callbackifyTest.fnT1); - const cfnT1E = util.callbackify(callbackifyTest.fnT1E); - const cfnTResult = util.callbackify(callbackifyTest.fnTResult); - const cfnTResultE = util.callbackify(callbackifyTest.fnTResultE); - const cfnT1TResult = util.callbackify(callbackifyTest.fnT1TResult); - const cfnT1TResultE = util.callbackify(callbackifyTest.fnT1TResultE); - - cfn((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); - cfnE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - cfnT1('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); - cfnT1E('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - cfnTResult((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); - cfnTResultE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - cfnT1TResult('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); - cfnT1TResultE('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - } - } - callbackifyTest.test(); - - // util.promisify - const readPromised = util.promisify(fs.readFile); - const sampleRead: Promise = readPromised(__filename).then((data: Buffer): void => { }).catch((error: Error): void => { }); - const arg0: () => Promise = util.promisify((cb: (err: Error, result: number) => void): void => { }); - const arg0NoResult: () => Promise = util.promisify((cb: (err: Error) => void): void => { }); - const arg1: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error, result: number) => void): void => { }); - const arg1NoResult: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error) => void): void => { }); - const cbOptionalError: () => Promise = util.promisify((cb: (err?: Error | null) => void): void => { cb(); }); // tslint:disable-line void-return - assert(typeof util.promisify.custom === 'symbol'); - // util.deprecate - const foo = () => {}; - // $ExpectType () => void - util.deprecate(foo, 'foo() is deprecated, use bar() instead'); - // $ExpectType (fn: T, message: string, code?: string) => T - util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); - // $ExpectType (fn: T, message: string, code?: string) => T - util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead', 'DEP0001'); - - // util.isDeepStrictEqual - util.isDeepStrictEqual({foo: 'bar'}, {foo: 'bar'}); - - // util.TextDecoder() - const td = new util.TextDecoder(); - new util.TextDecoder("utf-8"); - new util.TextDecoder("utf-8", { fatal: true }); - new util.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); - const ignoreBom: boolean = td.ignoreBOM; - const fatal: boolean = td.fatal; - const encoding: string = td.encoding; - td.decode(new Int8Array(1)); - td.decode(new Int16Array(1)); - td.decode(new Int32Array(1)); - td.decode(new Uint8Array(1)); - td.decode(new Uint16Array(1)); - td.decode(new Uint32Array(1)); - td.decode(new Uint8ClampedArray(1)); - td.decode(new Float32Array(1)); - td.decode(new Float64Array(1)); - td.decode(new DataView(new Int8Array(1).buffer)); - td.decode(new ArrayBuffer(1)); - td.decode(null); - td.decode(null, { stream: true }); - td.decode(new Int8Array(1), { stream: true }); - const decode: string = td.decode(new Int8Array(1)); - - // util.TextEncoder() - const te = new util.TextEncoder(); - const teEncoding: string = te.encoding; - const teEncodeRes: Uint8Array = te.encode("TextEncoder"); - - // util.types - let b: boolean; - b = util.types.isBigInt64Array(15); - b = util.types.isBigUint64Array(15); - b = util.types.isModuleNamespaceObject(15); - - // tslint:disable-next-line:no-construct ban-types - const maybeBoxed: number | Number = new Number(1); - if (util.types.isBoxedPrimitive(maybeBoxed)) { - const boxed: Number = maybeBoxed; - } - const maybeBoxed2: number | Number = 1; - if (!util.types.isBoxedPrimitive(maybeBoxed2)) { - const boxed: number = maybeBoxed2; - } - } -} - -//////////////////////////////////////////////////// -/// Stream tests : http://nodejs.org/api/stream.html -//////////////////////////////////////////////////// - -// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options -function stream_readable_pipe_test() { - const rs = fs.createReadStream(Buffer.from('file.txt')); - const r = fs.createReadStream('file.txt'); - const z = zlib.createGzip({ finishFlush: zlib.constants.Z_FINISH }); - const w = fs.createWriteStream('file.txt.gz'); - - assert(typeof z.bytesRead === 'number'); - assert(typeof r.bytesRead === 'number'); - assert(typeof r.path === 'string'); - assert(rs.path instanceof Buffer); - - r.pipe(z).pipe(w); - - z.flush(); - r.close(); - z.close(); - rs.close(); -} - -// helpers -const compressMe = new Buffer("some data"); -const compressMeString = "compress me!"; - -zlib.deflate(compressMe, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflate(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMeString, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMeString, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflate(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -const inflated = zlib.inflateSync(zlib.deflateSync(compressMe)); -const inflatedString = zlib.inflateSync(zlib.deflateSync(compressMeString)); - -zlib.deflateRaw(compressMe, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); -zlib.deflateRaw(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -zlib.deflateRaw(compressMeString, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); -zlib.deflateRaw( - compressMeString, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result), -); -const inflatedRaw: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMe)); -const inflatedRawString: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMeString)); - -zlib.gzip(compressMe, (err: Error, result: Buffer) => zlib.gunzip(result, (err: Error, result: Buffer) => result)); -zlib.gzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.gunzip(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -const gunzipped: Buffer = zlib.gunzipSync(zlib.gzipSync(compressMe)); - -zlib.unzip(compressMe, (err: Error, result: Buffer) => result); -zlib.unzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result); -const unzipped: Buffer = zlib.unzipSync(compressMe); - -// Simplified constructors -function simplified_stream_ctor_test() { - new stream.Readable({ - read(size) { - // $ExpectType Readable - this; - // $ExpectType number - size; - }, - destroy(error, cb) { - // $ExpectType Error - error; - // $ExpectType (error: Error) => void - cb; - } - }); - - new stream.Writable({ - write(chunk, enc, cb) { - // $ExpectType Writable - this; - // $ExpectType any - chunk; - // $ExpectType string - enc; - // $ExpectType (error?: Error) => void - cb; - }, - writev(chunks, cb) { - // $ExpectType Writable - this; - // $ExpectType { chunk: any; encoding: string; }[] - chunks; - // $ExpectType (error?: Error) => void - cb; - }, - destroy(error, cb) { - // $ExpectType Writable - this; - // $ExpectType Error - error; - // $ExpectType (error: Error) => void - cb; - }, - final(cb) { - // $ExpectType Writable - this; - // $ExpectType (error?: Error) => void - cb; - } - }); - - new stream.Duplex({ - read(size) { - // $ExpectType Duplex - this; - // $ExpectType number - size; - }, - write(chunk, enc, cb) { - // $ExpectType Duplex - this; - // $ExpectType any - chunk; - // $ExpectType string - enc; - // $ExpectType (error?: Error) => void - cb; - }, - writev(chunks, cb) { - // $ExpectType Duplex - this; - // $ExpectType { chunk: any; encoding: string; }[] - chunks; - // $ExpectType (error?: Error) => void - cb; - }, - destroy(error, cb) { - // $ExpectType Duplex - this; - // $ExpectType Error - error; - // $ExpectType (error: Error) => void - cb; - }, - final(cb) { - // $ExpectType Duplex - this; - // $ExpectType (error?: Error) => void - cb; - }, - readableObjectMode: true, - writableObjectMode: true, - readableHighWaterMark: 2048, - writableHighWaterMark: 1024 - }); - - new stream.Transform({ - read(size) { - // $ExpectType Transform - this; - // $ExpectType number - size; - }, - write(chunk, enc, cb) { - // $ExpectType Transform - this; - // $ExpectType any - chunk; - // $ExpectType string - enc; - // $ExpectType (error?: Error) => void - cb; - }, - writev(chunks, cb) { - // $ExpectType Transform - this; - // $ExpectType { chunk: any; encoding: string; }[] - chunks; - // $ExpectType (error?: Error) => void - cb; - }, - destroy(error, cb) { - // $ExpectType Transform - this; - // $ExpectType Error - error; - // $ExpectType (error: Error) => void - cb; - }, - final(cb) { - // $ExpectType Transform - this; - // $ExpectType (error?: Error) => void - cb; - }, - transform(chunk, enc, cb) { - // $ExpectType Transform - this; - // $ExpectType any - chunk; - // $ExpectType string - enc; - // $ExpectType TransformCallback - cb; - }, - flush(cb) { - // $ExpectType TransformCallback - cb; - }, - allowHalfOpen: true, - readableObjectMode: true, - writableObjectMode: true, - readableHighWaterMark: 2048, - writableHighWaterMark: 1024 - }); -} - -function streamPipelineFinished() { - const cancel = stream.finished(process.stdin, (err?: Error) => {}); - cancel(); - - stream.pipeline(process.stdin, process.stdout, (err?: Error) => {}); -} - -async function asyncStreamPipelineFinished() { - const finished = util.promisify(stream.finished); - await finished(process.stdin); - - const pipeline = util.promisify(stream.pipeline); - await pipeline(process.stdin, process.stdout); -} - -//////////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html /// -//////////////////////////////////////////////////////// - -{ - { - // crypto_hash_string_test - const hashResult: string = crypto.createHash('md5').update('world').digest('hex'); - } - - { - // crypto_hash_buffer_test - const hashResult: string = crypto.createHash('md5') - .update(new Buffer('world')).digest('hex'); - } - - { - // crypto_hash_dataview_test - const hashResult: string = crypto.createHash('md5') - .update(new DataView(new Buffer('world').buffer)).digest('hex'); - } - - { - // crypto_hash_int8array_test - const hashResult: string = crypto.createHash('md5') - .update(new Int8Array(new Buffer('world').buffer)).digest('hex'); - } - - { - // crypto_hmac_string_test - const hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); - } - - { - // crypto_hmac_buffer_test - const hmacResult: string = crypto.createHmac('md5', 'hello') - .update(new Buffer('world')).digest('hex'); - } - - { - // crypto_hmac_dataview_test - const hmacResult: string = crypto.createHmac('md5', 'hello') - .update(new DataView(new Buffer('world').buffer)).digest('hex'); - } - - { - // crypto_hmac_int8array_test - const hmacResult: string = crypto.createHmac('md5', 'hello') - .update(new Int8Array(new Buffer('world').buffer)).digest('hex'); - } - - { - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - const hash: Buffer | string = hmac.read(); - }); - } - - { - // crypto_cipher_decipher_string_test - const key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - const clearText = "This is the clear text."; - const cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - let cipherText: string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); - - const decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - let clearText2: string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); - - assert.equal(clearText2, clearText); - } - - { - // crypto_cipher_decipher_buffer_test - const key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - const clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - const cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - const cipherBuffers: Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); - - const cipherText: Buffer = Buffer.concat(cipherBuffers); - - const decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - const decipherBuffers: Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - const clearText2: Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); - } - - { - // crypto_cipher_decipher_dataview_test - const key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - const clearText: DataView = new DataView(new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]).buffer); - const cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - const cipherBuffers: Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); - - const cipherText: DataView = new DataView(Buffer.concat(cipherBuffers).buffer); - - const decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - const decipherBuffers: Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - const clearText2: Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); - } - - { - const key = 'keykeykeykeykeykeykeykey'; - const nonce = crypto.randomBytes(12); - const aad = Buffer.from('0123456789', 'hex'); - - const cipher = crypto.createCipheriv('aes-192-ccm', key, nonce, { - authTagLength: 16 - }); - const plaintext = 'Hello world'; - cipher.setAAD(aad, { - plaintextLength: Buffer.byteLength(plaintext) - }); - const ciphertext = cipher.update(plaintext, 'utf8'); - cipher.final(); - const tag = cipher.getAuthTag(); - - const decipher = crypto.createDecipheriv('aes-192-ccm', key, nonce, { - authTagLength: 16 - }); - decipher.setAuthTag(tag); - decipher.setAAD(aad, { - plaintextLength: ciphertext.length - }); - const receivedPlaintext: string = decipher.update(ciphertext, null, 'utf8'); - decipher.final(); - } - - { - const key = 'keykeykeykeykeykeykeykey'; - const nonce = crypto.randomBytes(12); - const aad = Buffer.from('0123456789', 'hex'); - - const cipher = crypto.createCipheriv('aes-192-gcm', key, nonce); - const plaintext = 'Hello world'; - cipher.setAAD(aad, { - plaintextLength: Buffer.byteLength(plaintext) - }); - const ciphertext = cipher.update(plaintext, 'utf8'); - cipher.final(); - const tag = cipher.getAuthTag(); - - const decipher = crypto.createDecipheriv('aes-192-gcm', key, nonce); - decipher.setAuthTag(tag); - decipher.setAAD(aad, { - plaintextLength: ciphertext.length - }); - const receivedPlaintext: string = decipher.update(ciphertext, null, 'utf8'); - decipher.final(); - } - - { - const key: string | null = 'keykeykeykeykeykeykeykey'; - const nonce = crypto.randomBytes(12); - const aad = Buffer.from('0123456789', 'hex'); - - const cipher = crypto.createCipheriv('aes-192-ccm', key, nonce, { - authTagLength: 16 - }); - const plaintext = 'Hello world'; - cipher.setAAD(aad, { - plaintextLength: Buffer.byteLength(plaintext) - }); - const ciphertext = cipher.update(plaintext, 'utf8'); - cipher.final(); - const tag = cipher.getAuthTag(); - - const decipher = crypto.createDecipheriv('aes-192-ccm', key, nonce, { - authTagLength: 16 - }); - decipher.setAuthTag(tag); - decipher.setAAD(aad, { - plaintextLength: ciphertext.length - }); - const receivedPlaintext: string = decipher.update(ciphertext, 'binary', 'utf8'); - decipher.final(); - } - - { - // crypto_timingsafeequal_buffer_test - const buffer1: Buffer = new Buffer([1, 2, 3, 4, 5]); - const buffer2: Buffer = new Buffer([1, 2, 3, 4, 5]); - const buffer3: Buffer = new Buffer([5, 4, 3, 2, 1]); - - assert(crypto.timingSafeEqual(buffer1, buffer2)); - assert(!crypto.timingSafeEqual(buffer1, buffer3)); - } - - { - // crypto_timingsafeequal_uint32array_test - const arr1: Uint32Array = Uint32Array.of(1, 2, 3, 4, 5); - const arr2: Uint32Array = Uint32Array.of(1, 2, 3, 4, 5); - const arr3: Uint32Array = Uint32Array.of(5, 4, 3, 2, 1); - - assert(crypto.timingSafeEqual(arr1, arr2)); - assert(!crypto.timingSafeEqual(arr1, arr3)); - } - - { - // crypto_timingsafeequal_safe_typedarray_variant_test - const arr1: Uint32Array = Uint32Array.of(1, 2, 3, 4, 5); - const arr2: Int32Array = Int32Array.of(1, 2, 3, 4, 5); - const arr3: Uint32Array = Uint32Array.of(5, 4, 3, 2, 1); - - assert(crypto.timingSafeEqual(arr1, arr2)); - assert(!crypto.timingSafeEqual(arr1, arr3)); - } - - { - // crypto_timingsafeequal_safe_int8array_variant_test - const arr1: Int8Array = Int8Array.of(1, 2, 3, 4, 5, ~0, ~1, ~2, ~3, ~4); - const arr2: Uint8Array = Uint8Array.of(1, 2, 3, 4, 5, ~0, ~1, ~2, ~3, ~4); - const arr3: Uint8ClampedArray = Uint8ClampedArray.of(1, 2, 3, 4, 5, ~0, ~1, ~2, ~3, ~4); - - assert(crypto.timingSafeEqual(arr1, arr2)); // binary same - assert(!crypto.timingSafeEqual(arr1, arr3)); // binary differ - } - - { - // crypto_timingsafeequal_safe_arraybufferiew_variant_test - /* throws as of v10.4.1 */ - // let arr1: Uint8Array = Uint8Array.of(1, 0, 2, 0, 3, 0, 4, 0); - // let arr2: Uint16Array = Uint16Array.of(1, 2, 3, 4); - // let arr3: Uint32Array = Uint8ClampedArray.of(131073, 262147); - - // assert(crypto.timingSafeEqual(arr1, arr2)); // binary same - // assert(crypto.timingSafeEqual(arr1, arr3)); // binary same - } - - { - // crypto_timingsafeequal_unsafe_arraybufferiew_variant_test - /* dumps core as of v10.4.1 */ - // let arr1: Uint8Array = Uint8Array.of(1, 2, 3, 4); - // let arr2: Uint16Array = Uint16Array.of(1, 2, 3, 4); - // let arr3: Uint32Array = Uint8ClampedArray.of(1, 2, 3, 4); - - // assert(!crypto.timingSafeEqual(arr1, arr2)); // dumps core - // assert(!crypto.timingSafeEqual(arr1, arr3)); // dumps core - } - - { - // crypto_timingsafeequal_dataview_test - const dv1B: Uint8Array = Uint8Array.of(1, 2, 3, 4, 5); - const dv2B: Int8Array = Int8Array.of(1, 2, 3, 4, 5); - const dv3B: Buffer = Buffer.of(5, 4, 3, 2, 1); - const dv4B: Uint8ClampedArray = Uint8ClampedArray.of(5, 4, 3, 2, 1); - const dv1: DataView = new DataView(dv1B.buffer, dv1B.byteOffset, dv1B.byteLength); - const dv2: DataView = new DataView(dv2B.buffer, dv2B.byteOffset, dv2B.byteLength); - const dv3: DataView = new DataView(dv3B.buffer, dv3B.byteOffset, dv3B.byteLength); - const dv4: DataView = new DataView(dv4B.buffer, dv4B.byteOffset, dv4B.byteLength); - - assert(crypto.timingSafeEqual(dv1, dv2)); - assert(crypto.timingSafeEqual(dv1, dv1B)); - assert(crypto.timingSafeEqual(dv2, dv1B)); - assert(crypto.timingSafeEqual(dv3, dv4)); - - assert(!crypto.timingSafeEqual(dv1, dv3)); - assert(!crypto.timingSafeEqual(dv2, dv3)); - assert(!crypto.timingSafeEqual(dv1, dv4)); - // ... I'm not going to write all those tests. - } - - { - // crypto_timingsafeequal_uint32array_test - const ui32_1: Uint32Array = Uint32Array.of(1, 2, 3, 4, 5); - const ui32_2: Uint32Array = Uint32Array.of(1, 2, 3, 4, 5); - const ui32_3: Uint32Array = Uint32Array.of(5, 4, 3, 2, 1); - - assert(crypto.timingSafeEqual(ui32_1, ui32_2)); - assert(!crypto.timingSafeEqual(ui32_1, ui32_3)); - } - - { - // crypto_randomfill_buffer_test - const buffer: Buffer = new Buffer(10); - crypto.randomFillSync(buffer); - crypto.randomFillSync(buffer, 2); - crypto.randomFillSync(buffer, 2, 3); - - crypto.randomFill(buffer, (err: Error, buf: Buffer) => void {}); - crypto.randomFill(buffer, 2, (err: Error, buf: Buffer) => void {}); - crypto.randomFill(buffer, 2, 3, (err: Error, buf: Buffer) => void {}); - - // crypto_randomfill_uint8array_test - const ui8arr: Uint8Array = new Uint8Array(10); - crypto.randomFillSync(ui8arr); - crypto.randomFillSync(ui8arr, 2); - crypto.randomFillSync(ui8arr, 2, 3); - - crypto.randomFill(ui8arr, (err: Error, buf: Uint8Array) => void {}); - crypto.randomFill(ui8arr, 2, (err: Error, buf: Uint8Array) => void {}); - crypto.randomFill(ui8arr, 2, 3, (err: Error, buf: Uint8Array) => void {}); - - // crypto_randomfill_int32array_test - const i32arr: Int32Array = new Int32Array(10); - crypto.randomFillSync(i32arr); - crypto.randomFillSync(i32arr, 2); - crypto.randomFillSync(i32arr, 2, 3); - - crypto.randomFill(i32arr, (err: Error, buf: Int32Array) => void {}); - crypto.randomFill(i32arr, 2, (err: Error, buf: Int32Array) => void {}); - crypto.randomFill(i32arr, 2, 3, (err: Error, buf: Int32Array) => void {}); - } - - { - // scrypt - const pwd: string | Buffer | Int32Array | DataView = Buffer.alloc(16); - const salt: string | Buffer | Int32Array | DataView = Buffer.alloc(16); - crypto.scrypt(pwd, salt, 64, (err: Error | null, derivedKey: Buffer): void => {}); - const opts: crypto.ScryptOptions = { - N: 16384, - r: 8, - p: 1, - maxmem: 32 * 1024 * 1024 - }; - crypto.scrypt(pwd, salt, 64, opts, (err: Error | null, derivedKey: Buffer): void => {}); - crypto.scrypt(pwd, salt, 64, { maxmem: 16 * 1024 * 1024 }, (err: Error | null, derivedKey: Buffer): void => {}); - let buf: Buffer = crypto.scryptSync(pwd, salt, 64); - buf = crypto.scryptSync(pwd, salt, 64, opts); - buf = crypto.scryptSync(pwd, salt, 64, { N: 1024 }); - } - - { - let key: string | Buffer = Buffer.from("buf"); - const curve = "secp256k1"; - let ret: string | Buffer = crypto.ECDH.convertKey(key, curve); - key = "0xfff"; - ret = crypto.ECDH.convertKey(key, curve); - ret = crypto.ECDH.convertKey(key, curve, "hex"); - ret = crypto.ECDH.convertKey(key, curve, "hex", "hex"); - ret = crypto.ECDH.convertKey(key, curve, "hex", "hex", "uncompressed"); - ret = crypto.ECDH.convertKey(key, curve, "hex", "hex", "compressed"); - ret = crypto.ECDH.convertKey(key, curve, "hex", "hex", "hybrid"); - } - - { - const rsaRes: { - publicKey: Buffer; - privateKey: string; - } = crypto.generateKeyPairSync('rsa', { - modulusLength: 123, - publicKeyEncoding: { - format: 'der', - type: 'pkcs1', - }, - privateKeyEncoding: { - cipher: 'some-cipher', - format: 'pem', - passphrase: 'secret', - type: 'pkcs8', - }, - }); - - const dsaRes: { - publicKey: string; - privateKey: Buffer; - } = crypto.generateKeyPairSync('dsa', { - modulusLength: 123, - divisorLength: 123, - publicKeyEncoding: { - format: 'pem', - type: 'spki', - }, - privateKeyEncoding: { - cipher: 'some-cipher', - format: 'der', - passphrase: 'secret', - type: 'pkcs8', - }, - }); - - const ecRes: { - publicKey: string; - privateKey: string; - } = crypto.generateKeyPairSync('ec', { - namedCurve: 'curve', - publicKeyEncoding: { - format: 'pem', - type: 'pkcs1', - }, - privateKeyEncoding: { - cipher: 'some-cipher', - format: 'pem', - passphrase: 'secret', - type: 'pkcs8', - }, - }); - } - - { - crypto.generateKeyPair('rsa', { - modulusLength: 123, - publicKeyEncoding: { - format: 'der', - type: 'pkcs1', - }, - privateKeyEncoding: { - cipher: 'some-cipher', - format: 'pem', - passphrase: 'secret', - type: 'pkcs8', - }, - }, (err: NodeJS.ErrnoException | null, publicKey: Buffer, privateKey: string) => {}); - - crypto.generateKeyPair('dsa', { - modulusLength: 123, - divisorLength: 123, - publicKeyEncoding: { - format: 'pem', - type: 'spki', - }, - privateKeyEncoding: { - cipher: 'some-cipher', - format: 'der', - passphrase: 'secret', - type: 'pkcs8', - }, - }, (err: NodeJS.ErrnoException | null, publicKey: string, privateKey: Buffer) => {}); - - crypto.generateKeyPair('ec', { - namedCurve: 'curve', - publicKeyEncoding: { - format: 'pem', - type: 'pkcs1', - }, - privateKeyEncoding: { - cipher: 'some-cipher', - format: 'pem', - passphrase: 'secret', - type: 'pkcs8', - }, - }, (err: NodeJS.ErrnoException | null, publicKey: string, privateKey: string) => {}); - } - - { - const generateKeyPairPromisified = util.promisify(crypto.generateKeyPair); - - const rsaRes: Promise<{ - publicKey: Buffer; - privateKey: string; - }> = generateKeyPairPromisified('rsa', { - modulusLength: 123, - publicKeyEncoding: { - format: 'der', - type: 'pkcs1', - }, - privateKeyEncoding: { - cipher: 'some-cipher', - format: 'pem', - passphrase: 'secret', - type: 'pkcs8', - }, - }); - - const dsaRes: Promise<{ - publicKey: string; - privateKey: Buffer; - }> = generateKeyPairPromisified('dsa', { - modulusLength: 123, - divisorLength: 123, - publicKeyEncoding: { - format: 'pem', - type: 'spki', - }, - privateKeyEncoding: { - cipher: 'some-cipher', - format: 'der', - passphrase: 'secret', - type: 'pkcs8', - }, - }); - - const ecRes: Promise<{ - publicKey: string; - privateKey: string; - }> = generateKeyPairPromisified('ec', { - namedCurve: 'curve', - publicKeyEncoding: { - format: 'pem', - type: 'pkcs1', - }, - privateKeyEncoding: { - cipher: 'some-cipher', - format: 'pem', - passphrase: 'secret', - type: 'pkcs8', - }, - }); - } -} - -////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html /// -////////////////////////////////////////////////// - -{ - { - const ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", - }); - const blah = ctx.context; - - const connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 - }; - const tlsSocket = tls.connect(connOpts); - - const ciphers: string[] = tls.getCiphers(); - const curve: string = tls.DEFAULT_ECDH_CURVE; - } - - { - let _server: tls.Server; - let _boolean: boolean; - const _func1 = (err: Error, resp: Buffer) => { }; - const _func2 = (err: Error, sessionData: any) => { }; - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - */ - - _server = _server.addListener("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.addListener("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.addListener("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.addListener("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - const _err: Error = new Error(); - const _tlsSocket: tls.TLSSocket = tls.connect(1); - const _any: any = 1; - const _func: Function = () => {}; - const _buffer: Buffer = Buffer.from('a'); - _boolean = _server.emit("tlsClientError", _err, _tlsSocket); - _boolean = _server.emit("newSession", _any, _any, _func1); - _boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func); - _boolean = _server.emit("resumeSession", _any, _func2); - _boolean = _server.emit("secureConnection", _tlsSocket); - - _server = _server.on("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.on("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.on("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.on("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.on("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.once("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.once("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.once("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.once("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.once("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.prependListener("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.prependListener("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.prependListener("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.prependListener("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.prependOnceListener("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - // close callback parameter is optional - _server = _server.close(); - - // close callback parameter can be either nothing (undefined) or an error - _server = _server.close(() => { }); - _server = _server.close((err) => { - if (typeof err !== 'undefined') { const _err: Error = err; } - }); - } - - { - let _TLSSocket: tls.TLSSocket; - let _boolean: boolean; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - */ - - _TLSSocket = _TLSSocket.addListener("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.addListener("secureConnect", () => { }); - - const _buffer: Buffer = Buffer.from(""); - _boolean = _TLSSocket.emit("OCSPResponse", _buffer); - _boolean = _TLSSocket.emit("secureConnect"); - - _TLSSocket = _TLSSocket.on("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.on("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.once("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.once("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependListener("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.prependListener("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependOnceListener("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.prependOnceListener("secureConnect", () => { }); - } -} - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html /// -//////////////////////////////////////////////////// - -{ - // http Server - { - function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} - - let server: http.Server = new http.Server(); - - class MyIncomingMessage extends http.IncomingMessage { - foo: number; - } - - class MyServerResponse extends http.ServerResponse { - foo: string; - } - - server = new http.Server({ IncomingMessage: MyIncomingMessage}); - - server = new http.Server({ - IncomingMessage: MyIncomingMessage, - ServerResponse: MyServerResponse - }, reqListener); - - server = http.createServer(reqListener); - server = http.createServer({ IncomingMessage: MyIncomingMessage }); - server = http.createServer({ ServerResponse: MyServerResponse }, reqListener); - - // test public props - const maxHeadersCount: number = server.maxHeadersCount; - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } - - // http IncomingMessage - // http ServerResponse - { - // incoming - const incoming: http.IncomingMessage = new http.IncomingMessage(new net.Socket()); - - incoming.setEncoding('utf8'); - - // stream - incoming.pause(); - incoming.resume(); - - // response - const res: http.ServerResponse = new http.ServerResponse(incoming); - - // test headers - res.setHeader('Content-Type', 'text/plain'); - const bool: boolean = res.hasHeader('Content-Type'); - const headers: string[] = res.getHeaderNames(); - - // trailers - res.addTrailers([ - ['x-fOo', 'xOxOxOx'], - ['x-foO', 'OxOxOxO'], - ['X-fOo', 'xOxOxOx'], - ['X-foO', 'OxOxOxO'] - ]); - res.addTrailers({ 'x-foo': 'bar' }); - - // writeHead - res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n'); - res.writeHead(200, { 'Transfer-Encoding': 'chunked' }); - res.writeHead(200); - - // write string - res.write('Part of my res.'); - // write buffer - const chunk = Buffer.alloc(16390, 'Й'); - res.write(chunk); - res.write(chunk, 'hex'); - - // end - res.end("end msg"); - // without msg - res.end(); - - // flush - res.flushHeaders(); - } - - // http ClientRequest - { - let req: http.ClientRequest = new http.ClientRequest("https://www.google.com"); - req = new http.ClientRequest(new url.URL("https://www.google.com")); - req = new http.ClientRequest({ path: 'http://0.0.0.0' }); - req = new http.ClientRequest({ setHost: false }); - - // header - req.setHeader('Content-Type', 'text/plain'); - const bool: boolean = req.hasHeader('Content-Type'); - const headers: string[] = req.getHeaderNames(); - req.removeHeader('Date'); - - // write - const chunk = Buffer.alloc(16390, 'Й'); - req.write(chunk); - req.write('a'); - req.end(); - - // abort - req.abort(); - - // connection - req.connection.on('pause', () => { }); - - // event - req.on('data', () => { }); - } - - { - // Status codes - let codeMessage: string = http.STATUS_CODES['400']; - codeMessage = http.STATUS_CODES[400]; - } - - { - let agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256, - timeout: 15000 - }); - - agent = http.globalAgent; - - http.request({ agent: false }); - http.request({ agent }); - http.request({ agent: undefined }); - } - - { - http.get('http://www.example.com/xyz'); - http.request('http://www.example.com/xyz'); - - http.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - http.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - - http.get(new url.URL('http://www.example.com/xyz')); - http.request(new url.URL('http://www.example.com/xyz')); - - http.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - http.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - - const opts: http.RequestOptions = { - path: '"/some/path' - }; - http.get(new url.URL('http://www.example.com'), opts); - http.request(new url.URL('http://www.example.com'), opts); - http.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - http.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - } - - { - // Make sure .listen() and .close() return a Server instance - http.createServer().listen(0).close().address(); - net.createServer().listen(0).close().address(); - } - - { - const request = http.request({ path: 'http://0.0.0.0' }); - request.once('error', () => { }); - request.setNoDelay(true); - request.abort(); - } - - // http request options - { - const requestOpts: http.RequestOptions = { - timeout: 30000 - }; - - const clientArgs: http.ClientRequestArgs = { - timeout: 30000 - }; - } - - // http headers - { - const headers: http.IncomingHttpHeaders = { - 'content-type': 'application/json', - 'set-cookie': [ 'type=ninja', 'language=javascript' ] - }; - } -} - -////////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html /// -////////////////////////////////////////////////////// - -{ - let agent: https.Agent = new https.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256, - maxCachedSessions: 100, - timeout: 15000 - }); - - agent = https.globalAgent; - - https.request({ - agent: false - }); - https.request({ - agent - }); - https.request({ - agent: undefined - }); - - https.get('http://www.example.com/xyz'); - https.request('http://www.example.com/xyz'); - - https.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - https.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - - https.get(new url.URL('http://www.example.com/xyz')); - https.request(new url.URL('http://www.example.com/xyz')); - - https.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - https.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - - const opts: https.RequestOptions = { - path: '/some/path' - }; - https.get(new url.URL('http://www.example.com'), opts); - https.request(new url.URL('http://www.example.com'), opts); - https.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - https.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - - https.globalAgent.options.ca = []; - - { - function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} - - class MyIncomingMessage extends http.IncomingMessage { - foo: number; - } - - class MyServerResponse extends http.ServerResponse { - foo: string; - } - - let server = new https.Server({ IncomingMessage: MyIncomingMessage}); - - server = new https.Server({ - IncomingMessage: MyIncomingMessage, - ServerResponse: MyServerResponse - }, reqListener); - - server = https.createServer({ IncomingMessage: MyIncomingMessage }); - server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); - - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } -} - -//////////////////////////////////////////////////// -/// TTY tests : http://nodejs.org/api/tty.html -//////////////////////////////////////////////////// - -{ - const rs: tty.ReadStream = new tty.ReadStream(0); - const ws: tty.WriteStream = new tty.WriteStream(1); - - const rsIsRaw: boolean = rs.isRaw; - const rsRaw: tty.ReadStream = rs.setRawMode(true); - - const wsColumns: number = ws.columns; - const wsRows: number = ws.rows; - - const isTTY: boolean = tty.isatty(1); -} - -//////////////////////////////////////////////////// -/// Dgram tests : http://nodejs.org/api/dgram.html -//////////////////////////////////////////////////// - -{ - { - let ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { - }); - ds.bind(); - ds.bind(41234); - ds.bind(4123, 'localhost'); - ds.bind(4123, 'localhost', () => { }); - ds.bind(4123, () => { }); - ds.bind(() => { }); - const addr: net.AddressInfo | string = ds.address(); - ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { - }); - ds.send(new Buffer("hello"), 5000, "127.0.0.1"); - ds.setMulticastInterface("127.0.0.1"); - ds = dgram.createSocket({ type: "udp4", reuseAddr: true, recvBufferSize: 1000, sendBufferSize: 1000, lookup: dns.lookup }); - } - - { - let _socket: dgram.Socket; - let _boolean: boolean; - const _err: Error = new Error(); - const _str = ''; - const _rinfo: net.AddressInfo = { - address: 'asd', - family: 'asd', - port: 1, - }; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - */ - - _socket = _socket.addListener("close", () => { }); - _socket = _socket.addListener("error", (err) => { - const _err: Error = err; - }); - _socket = _socket.addListener("listening", () => { }); - _socket = _socket.addListener("message", (msg, rinfo) => { - const _msg: Buffer = msg; - const _rinfo: net.AddressInfo = rinfo; - }); - - _boolean = _socket.emit("close"); - _boolean = _socket.emit("error", _err); - _boolean = _socket.emit("listening"); - _boolean = _socket.emit("message", _str, _rinfo); - - _socket = _socket.on("close", () => { }); - _socket = _socket.on("error", (err) => { - const _err: Error = err; - }); - _socket = _socket.on("listening", () => { }); - _socket = _socket.on("message", (msg, rinfo) => { - const _msg: Buffer = msg; - const _rinfo: net.AddressInfo = rinfo; - }); - - _socket = _socket.once("close", () => { }); - _socket = _socket.once("error", (err) => { - const _err: Error = err; - }); - _socket = _socket.once("listening", () => { }); - _socket = _socket.once("message", (msg, rinfo) => { - const _msg: Buffer = msg; - const _rinfo: net.AddressInfo = rinfo; - }); - - _socket = _socket.prependListener("close", () => { }); - _socket = _socket.prependListener("error", (err) => { - const _err: Error = err; - }); - _socket = _socket.prependListener("listening", () => { }); - _socket = _socket.prependListener("message", (msg, rinfo) => { - const _msg: Buffer = msg; - const _rinfo: net.AddressInfo = rinfo; - }); - - _socket = _socket.prependOnceListener("close", () => { }); - _socket = _socket.prependOnceListener("error", (err) => { - const _err: Error = err; - }); - _socket = _socket.prependOnceListener("listening", () => { }); - _socket = _socket.prependOnceListener("message", (msg, rinfo) => { - const _msg: Buffer = msg; - const _rinfo: net.AddressInfo = rinfo; - }); - } - - { - const ds: dgram.Socket = dgram.createSocket({ - type: 'udp4', - recvBufferSize: 10000, - sendBufferSize: 15000 - }); - - let size: number; - size = ds.getRecvBufferSize(); - ds.setRecvBufferSize(size); - size = ds.getSendBufferSize(); - ds.setSendBufferSize(size); - } -} - -//////////////////////////////////////////////////// -/// Querystring tests : https://nodejs.org/api/querystring.html -//////////////////////////////////////////////////// - -{ - interface SampleObject { a: string; } - - { - const obj: SampleObject = { a: "" }; - const sep = ''; - const eq = ''; - const options: querystring.StringifyOptions = {}; - let result: string; - - result = querystring.stringify(obj); - result = querystring.stringify(obj, sep); - result = querystring.stringify(obj, sep, eq); - result = querystring.stringify(obj, sep, eq); - result = querystring.stringify(obj, sep, eq, options); - } - - { - const str = ''; - const sep = ''; - const eq = ''; - const options: querystring.ParseOptions = {}; - let result: querystring.ParsedUrlQuery; - - result = querystring.parse(str); - result = querystring.parse(str, sep); - result = querystring.parse(str, sep, eq); - result = querystring.parse(str, sep, eq, options); - } - - { - const str = ''; - let result: string; - - result = querystring.escape(str); - result = querystring.unescape(str); - } -} - -//////////////////////////////////////////////////// -/// path tests : http://nodejs.org/api/path.html -//////////////////////////////////////////////////// - -{ - path.normalize('/foo/bar//baz/asdf/quux/..'); - - path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); - // returns - // '/foo/bar/baz/asdf' - - try { - path.join('foo', 'bar'); - } catch (error) { } - - path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile'); - // Is similar to: - // - // cd foo/bar - // cd /tmp/file/ - // cd .. - // cd a/../subfile - // pwd - - path.resolve('/foo/bar', './baz'); - // returns - // '/foo/bar/baz' - - path.resolve('/foo/bar', '/tmp/file/'); - // returns - // '/tmp/file' - - path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); - // if currently in /home/myself/node, it returns - // '/home/myself/node/wwwroot/static_files/gif/image.gif' - - path.isAbsolute('/foo/bar'); // true - path.isAbsolute('/baz/..'); // true - path.isAbsolute('qux/'); // false - path.isAbsolute('.'); // false - - path.isAbsolute('//server'); // true - path.isAbsolute('C:/foo/..'); // true - path.isAbsolute('bar\\baz'); // false - path.isAbsolute('.'); // false - - path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'); - // returns - // '..\\..\\impl\\bbb' - - path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); - // returns - // '../../impl/bbb' - - path.dirname('/foo/bar/baz/asdf/quux'); - // returns - // '/foo/bar/baz/asdf' - - path.basename('/foo/bar/baz/asdf/quux.html'); - // returns - // 'quux.html' - - path.basename('/foo/bar/baz/asdf/quux.html', '.html'); - // returns - // 'quux' - - path.extname('index.html'); - // returns - // '.html' - - path.extname('index.coffee.md'); - // returns - // '.md' - - path.extname('index.'); - // returns - // '.' - - path.extname('index'); - // returns - // '' - - 'foo/bar/baz'.split(path.sep); - // returns - // ['foo', 'bar', 'baz'] - - 'foo\\bar\\baz'.split(path.sep); - // returns - // ['foo', 'bar', 'baz'] - - process.env["PATH"]; // $ExpectType string - - path.parse('/home/user/dir/file.txt'); - // returns - // { - // root : "/", - // dir : "/home/user/dir", - // base : "file.txt", - // ext : ".txt", - // name : "file" - // } - - path.parse('C:\\path\\dir\\index.html'); - // returns - // { - // root : "C:\", - // dir : "C:\path\dir", - // base : "index.html", - // ext : ".html", - // name : "index" - // } - - path.format({ - root: "/", - dir: "/home/user/dir", - base: "file.txt", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - path.format({ - root: "/", - dir: "/home/user/dir", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - path.format({ - dir: "/home/user/dir", - base: "file.txt" - }); - // returns - // '/home/user/dir/file.txt' - - path.posix.format({ - root: "/", - dir: "/home/user/dir", - base: "file.txt", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - path.posix.format({ - dir: "/home/user/dir", - base: "file.txt" - }); - // returns - // '/home/user/dir/file.txt' - - path.win32.format({ - root: "C:\\", - dir: "C:\\home\\user\\dir", - ext: ".txt", - name: "file" - }); - // returns - // 'C:\home\user\dir\file.txt' - - path.win32.format({ - dir: "C:\\home\\user\\dir", - base: "file.txt" - }); - // returns - // 'C:\home\user\dir\file.txt' -} - -//////////////////////////////////////////////////// -/// readline tests : https://nodejs.org/api/readline.html -//////////////////////////////////////////////////// - -{ - const rl: readline.ReadLine = readline.createInterface(new stream.Readable()); - - { - const options: readline.ReadLineOptions = { - input: new fs.ReadStream() - }; - const input: NodeJS.ReadableStream = new stream.Readable(); - const output: NodeJS.WritableStream = new stream.Writable(); - const completer: readline.Completer = str => [['asd'], 'asd']; - const terminal = false; - - let result: readline.ReadLine; - - result = readline.createInterface(options); - result = readline.createInterface(input); - result = readline.createInterface(input, output); - result = readline.createInterface(input, output, completer); - result = readline.createInterface(input, output, completer, terminal); - result = readline.createInterface({ - input, - completer(str: string): readline.CompleterResult { - return [['test'], 'test']; - } - }); - result = readline.createInterface({ - input, - completer(str: string, callback: (err: any, result: readline.CompleterResult) => void): any { - callback(null, [['test'], 'test']); - } - }); - } - - { - rl.setPrompt("prompt"); - } - - { - rl.prompt(); - rl.prompt(true); - } - - { - rl.question("query", (answer: string) => {}); - } - - { - let result: readline.ReadLine; - - result = rl.pause(); - } - - { - let result: readline.ReadLine; - - result = rl.resume(); - } - - { - rl.close(); - } - - { - const data: string | Buffer = "asd"; - const key: readline.Key = {}; - - rl.write(data); - rl.write(null, key); - } - - { - const strm: NodeJS.WritableStream = new stream.Writable(); - const x = 1; - const y = 1; - - readline.cursorTo(strm, x); - readline.cursorTo(strm, x, y); - } - - { - const strm: NodeJS.ReadableStream = new stream.Readable(); - const readLineInterface: readline.ReadLine = readline.createInterface(new stream.Readable()); - - readline.emitKeypressEvents(strm); - readline.emitKeypressEvents(strm, readLineInterface); - } - - { - const strm: NodeJS.WritableStream = new stream.Writable(); - const dx: number | string = 1; - const dy: number | string = 1; - - readline.moveCursor(strm, dx, dy); - } - - { - const strm: NodeJS.WritableStream = new stream.Writable(); - readline.clearLine(strm, 1); - } - - { - const strm: NodeJS.WritableStream = new stream.Writable(); - - readline.clearScreenDown(strm); - } - - { - let _rl: readline.ReadLine; - let _boolean: boolean; - - _rl = _rl.addListener("close", () => { }); - _rl = _rl.addListener("line", (input) => { - const _input: any = input; - }); - _rl = _rl.addListener("pause", () => { }); - _rl = _rl.addListener("resume", () => { }); - _rl = _rl.addListener("SIGCONT", () => { }); - _rl = _rl.addListener("SIGINT", () => { }); - _rl = _rl.addListener("SIGTSTP", () => { }); - - _boolean = _rl.emit("close", () => { }); - _boolean = _rl.emit("line", () => { }); - _boolean = _rl.emit("pause", () => { }); - _boolean = _rl.emit("resume", () => { }); - _boolean = _rl.emit("SIGCONT", () => { }); - _boolean = _rl.emit("SIGINT", () => { }); - _boolean = _rl.emit("SIGTSTP", () => { }); - - _rl = _rl.on("close", () => { }); - _rl = _rl.on("line", (input) => { - const _input: any = input; - }); - _rl = _rl.on("pause", () => { }); - _rl = _rl.on("resume", () => { }); - _rl = _rl.on("SIGCONT", () => { }); - _rl = _rl.on("SIGINT", () => { }); - _rl = _rl.on("SIGTSTP", () => { }); - - _rl = _rl.once("close", () => { }); - _rl = _rl.once("line", (input) => { - const _input: any = input; - }); - _rl = _rl.once("pause", () => { }); - _rl = _rl.once("resume", () => { }); - _rl = _rl.once("SIGCONT", () => { }); - _rl = _rl.once("SIGINT", () => { }); - _rl = _rl.once("SIGTSTP", () => { }); - - _rl = _rl.prependListener("close", () => { }); - _rl = _rl.prependListener("line", (input) => { - const _input: any = input; - }); - _rl = _rl.prependListener("pause", () => { }); - _rl = _rl.prependListener("resume", () => { }); - _rl = _rl.prependListener("SIGCONT", () => { }); - _rl = _rl.prependListener("SIGINT", () => { }); - _rl = _rl.prependListener("SIGTSTP", () => { }); - - _rl = _rl.prependOnceListener("close", () => { }); - _rl = _rl.prependOnceListener("line", (input) => { - const _input: any = input; - }); - _rl = _rl.prependOnceListener("pause", () => { }); - _rl = _rl.prependOnceListener("resume", () => { }); - _rl = _rl.prependOnceListener("SIGCONT", () => { }); - _rl = _rl.prependOnceListener("SIGINT", () => { }); - _rl = _rl.prependOnceListener("SIGTSTP", () => { }); - } -} - -//////////////////////////////////////////////////// -/// string_decoder tests : https://nodejs.org/api/string_decoder.html -//////////////////////////////////////////////////// - -{ - const StringDecoder = string_decoder.StringDecoder; - const buffer = new Buffer('test'); - const decoder1 = new StringDecoder(); - const decoder2 = new StringDecoder('utf8'); - const part1: string = decoder1.write(new Buffer('test')); - const end1: string = decoder1.end(); - const part2: string = decoder2.write(new Buffer('test')); - const end2: string = decoder1.end(new Buffer('test')); -} - -////////////////////////////////////////////////////////////////////// -/// Child Process tests: https://nodejs.org/api/child_process.html /// -////////////////////////////////////////////////////////////////////// - -{ - { - childProcess.exec("echo test"); - childProcess.exec("echo test", { windowsHide: true }); - childProcess.spawn("echo"); - childProcess.spawn("echo", { windowsHide: true }); - childProcess.spawn("echo", ["test"], { windowsHide: true }); - childProcess.spawn("echo", ["test"], { windowsHide: true, argv0: "echo-test" }); - childProcess.spawn("echo", ["test"], { stdio: [0xdeadbeef, "inherit", undefined, "pipe"] }); - childProcess.spawnSync("echo test"); - childProcess.spawnSync("echo test", {windowsVerbatimArguments: false}); - childProcess.spawnSync("echo test", {windowsVerbatimArguments: false, argv0: "echo-test"}); - childProcess.spawnSync("echo test", {input: new Uint8Array([])}); - childProcess.spawnSync("echo test", {input: new DataView(new ArrayBuffer(1))}); - } - - { - childProcess.execFile("npm", () => {}); - childProcess.execFile("npm", { windowsHide: true }, () => {}); - childProcess.execFile("npm", ["-v"], () => {}); - childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); - childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); - childProcess.execFile("npm", { encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); - childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); - } - - { - childProcess.execFileSync("echo test", {input: new Uint8Array([])}); - childProcess.execFileSync("echo test", {input: new DataView(new ArrayBuffer(1))}); - } - - { - const forked = childProcess.fork('./', ['asd'], { - windowsVerbatimArguments: true, - silent: false, - stdio: "inherit", - execPath: '', - execArgv: ['asda'] - }); - const exitCode: number | null = forked.exitCode; - const signalCode: number | null = forked.signalCode; - const ipc: stream.Pipe = forked.channel; - const hasRef: boolean = ipc.hasRef(); - ipc.close(); - ipc.unref(); - ipc.ref(); - } - - { - const forked = childProcess.fork('./', { - windowsVerbatimArguments: true, - silent: false, - stdio: ["inherit"], - execPath: '', - execArgv: ['asda'] - }); - } - - { - const forked = childProcess.fork('./'); - } - - async function testPromisify() { - const execFile = util.promisify(childProcess.execFile); - let r: { stdout: string | Buffer, stderr: string | Buffer } = await execFile("npm"); - r = await execFile("npm", ["-v"]); - r = await execFile("npm", ["-v"], { encoding: 'utf-8' }); - r = await execFile("npm", ["-v"], { encoding: 'buffer' }); - r = await execFile("npm", { encoding: 'utf-8' }); - r = await execFile("npm", { encoding: 'buffer' }); - } - - { - let _cp: childProcess.ChildProcess; - const _socket: net.Socket = net.createConnection(1); - const _server: net.Server = net.createServer(); - let _boolean: boolean; - - _boolean = _cp.send(1); - _boolean = _cp.send('one'); - _boolean = _cp.send({ - type: 'test' - }); - - _boolean = _cp.send(1, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, (error) => { - const _err: Error = error; - }); - - _boolean = _cp.send(1, _socket); - _boolean = _cp.send('one', _socket); - _boolean = _cp.send({ - type: 'test' - }, _socket); - - _boolean = _cp.send(1, _socket, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', _socket, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, (error) => { - const _err: Error = error; - }); - - _boolean = _cp.send(1, _socket, { - keepOpen: true - }); - _boolean = _cp.send('one', _socket, { - keepOpen: true - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, { - keepOpen: true - }); - - _boolean = _cp.send(1, _socket, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', _socket, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - - _boolean = _cp.send(1, _server); - _boolean = _cp.send('one', _server); - _boolean = _cp.send({ - type: 'test' - }, _server); - - _boolean = _cp.send(1, _server, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', _server, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _server, (error) => { - const _err: Error = error; - }); - - _boolean = _cp.send(1, _server, { - keepOpen: true - }); - _boolean = _cp.send('one', _server, { - keepOpen: true - }); - _boolean = _cp.send({ - type: 'test' - }, _server, { - keepOpen: true - }); - - _boolean = _cp.send(1, _server, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', _server, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _server, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - - _cp = _cp.addListener("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.addListener("disconnect", () => { }); - _cp = _cp.addListener("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.addListener("exit", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.addListener("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _boolean = _cp.emit("close", () => { }); - _boolean = _cp.emit("disconnect", () => { }); - _boolean = _cp.emit("error", () => { }); - _boolean = _cp.emit("exit", () => { }); - _boolean = _cp.emit("message", () => { }); - - _cp = _cp.on("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.on("disconnect", () => { }); - _cp = _cp.on("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.on("exit", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.on("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.once("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.once("disconnect", () => { }); - _cp = _cp.once("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.once("exit", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.once("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.prependListener("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.prependListener("disconnect", () => { }); - _cp = _cp.prependListener("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.prependListener("exit", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.prependListener("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.prependOnceListener("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.prependOnceListener("disconnect", () => { }); - _cp = _cp.prependOnceListener("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.prependOnceListener("exit", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.prependOnceListener("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - } - { - process.stdin.setEncoding('utf8'); - - process.stdin.on('readable', () => { - const chunk = process.stdin.read(); - if (chunk !== null) { - process.stdout.write(`data: ${chunk}`); - } - }); - - process.stdin.on('end', () => { - process.stdout.write('end'); - }); - - process.stdin.pipe(process.stdout); - - console.log(process.stdin.isTTY); - console.log(process.stdout.isTTY); - - console.log(process.stdin instanceof net.Socket); - console.log(process.stdout instanceof fs.ReadStream); - - const stdin: stream.Readable = process.stdin; - console.log(stdin instanceof net.Socket); - console.log(stdin instanceof fs.ReadStream); - - const stdout: stream.Writable = process.stdout; - console.log(stdout instanceof net.Socket); - console.log(stdout instanceof fs.WriteStream); - } -} - -////////////////////////////////////////////////////////////////////// -/// cluster tests: https://nodejs.org/api/cluster.html /// -////////////////////////////////////////////////////////////////////// - -{ - { - cluster.fork(); - Object.keys(cluster.workers).forEach(key => { - const worker = cluster.workers[key]; - if (worker.isDead()) { - console.log('worker %d is dead', worker.process.pid); - } - }); - } -} - -////////////////////////////////////////////////////////////////////// -/// worker_threads tests: https://nodejs.org/api/worker_threads.html /// -////////////////////////////////////////////////////////////////////// - -{ - { - if (workerThreads.isMainThread) { - module.exports = async function parseJSAsync(script: string) { - return new Promise((resolve, reject) => { - const worker = new workerThreads.Worker(__filename, { - workerData: script - }); - worker.on('message', resolve); - worker.on('error', reject); - worker.on('exit', (code) => { - if (code !== 0) - reject(new Error(`Worker stopped with exit code ${code}`)); - }); - }); - }; - } else { - const script = workerThreads.workerData; - workerThreads.parentPort.postMessage(script); - } - } - - { - const { port1, port2 } = new workerThreads.MessageChannel(); - port1.on('message', (message) => console.log('received', message)); - port2.postMessage({ foo: 'bar' }); - } - - { - if (workerThreads.isMainThread) { - const worker = new workerThreads.Worker(__filename); - const subChannel = new workerThreads.MessageChannel(); - worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); - subChannel.port2.on('message', (value) => { - console.log('received:', value); - }); - } else { - workerThreads.parentPort.once('message', (value) => { - assert(value.hereIsYourPort instanceof MessagePort); - value.hereIsYourPort.postMessage('the worker is sending this'); - value.hereIsYourPort.close(); - }); - } - } -} - -//////////////////////////////////////////////////// -/// os tests : https://nodejs.org/api/os.html -//////////////////////////////////////////////////// - -{ - { - let result: string; - - result = os.tmpdir(); - result = os.homedir(); - result = os.endianness(); - result = os.hostname(); - result = os.type(); - result = os.arch(); - result = os.release(); - result = os.EOL; - } - - { - let result: number; - - result = os.uptime(); - result = os.totalmem(); - result = os.freemem(); - } - - { - let result: number[]; - - result = os.loadavg(); - } - - { - let result: os.CpuInfo[]; - - result = os.cpus(); - } - - { - let result: { [index: string]: os.NetworkInterfaceInfo[] }; - - result = os.networkInterfaces(); - } - - { - let result: number; - - result = os.constants.signals.SIGHUP; - result = os.constants.signals.SIGINT; - result = os.constants.signals.SIGQUIT; - result = os.constants.signals.SIGILL; - result = os.constants.signals.SIGTRAP; - result = os.constants.signals.SIGABRT; - result = os.constants.signals.SIGIOT; - result = os.constants.signals.SIGBUS; - result = os.constants.signals.SIGFPE; - result = os.constants.signals.SIGKILL; - result = os.constants.signals.SIGUSR1; - result = os.constants.signals.SIGSEGV; - result = os.constants.signals.SIGUSR2; - result = os.constants.signals.SIGPIPE; - result = os.constants.signals.SIGALRM; - result = os.constants.signals.SIGTERM; - result = os.constants.signals.SIGCHLD; - result = os.constants.signals.SIGSTKFLT; - result = os.constants.signals.SIGCONT; - result = os.constants.signals.SIGSTOP; - result = os.constants.signals.SIGTSTP; - result = os.constants.signals.SIGTTIN; - result = os.constants.signals.SIGTTOU; - result = os.constants.signals.SIGURG; - result = os.constants.signals.SIGXCPU; - result = os.constants.signals.SIGXFSZ; - result = os.constants.signals.SIGVTALRM; - result = os.constants.signals.SIGPROF; - result = os.constants.signals.SIGWINCH; - result = os.constants.signals.SIGIO; - result = os.constants.signals.SIGPOLL; - result = os.constants.signals.SIGPWR; - result = os.constants.signals.SIGSYS; - result = os.constants.signals.SIGUNUSED; - } - - { - let result: number; - - result = os.constants.errno.E2BIG; - result = os.constants.errno.EACCES; - result = os.constants.errno.EADDRINUSE; - result = os.constants.errno.EADDRNOTAVAIL; - result = os.constants.errno.EAFNOSUPPORT; - result = os.constants.errno.EAGAIN; - result = os.constants.errno.EALREADY; - result = os.constants.errno.EBADF; - result = os.constants.errno.EBADMSG; - result = os.constants.errno.EBUSY; - result = os.constants.errno.ECANCELED; - result = os.constants.errno.ECHILD; - result = os.constants.errno.ECONNABORTED; - result = os.constants.errno.ECONNREFUSED; - result = os.constants.errno.ECONNRESET; - result = os.constants.errno.EDEADLK; - result = os.constants.errno.EDESTADDRREQ; - result = os.constants.errno.EDOM; - result = os.constants.errno.EDQUOT; - result = os.constants.errno.EEXIST; - result = os.constants.errno.EFAULT; - result = os.constants.errno.EFBIG; - result = os.constants.errno.EHOSTUNREACH; - result = os.constants.errno.EIDRM; - result = os.constants.errno.EILSEQ; - result = os.constants.errno.EINPROGRESS; - result = os.constants.errno.EINTR; - result = os.constants.errno.EINVAL; - result = os.constants.errno.EIO; - result = os.constants.errno.EISCONN; - result = os.constants.errno.EISDIR; - result = os.constants.errno.ELOOP; - result = os.constants.errno.EMFILE; - result = os.constants.errno.EMLINK; - result = os.constants.errno.EMSGSIZE; - result = os.constants.errno.EMULTIHOP; - result = os.constants.errno.ENAMETOOLONG; - result = os.constants.errno.ENETDOWN; - result = os.constants.errno.ENETRESET; - result = os.constants.errno.ENETUNREACH; - result = os.constants.errno.ENFILE; - result = os.constants.errno.ENOBUFS; - result = os.constants.errno.ENODATA; - result = os.constants.errno.ENODEV; - result = os.constants.errno.ENOENT; - result = os.constants.errno.ENOEXEC; - result = os.constants.errno.ENOLCK; - result = os.constants.errno.ENOLINK; - result = os.constants.errno.ENOMEM; - result = os.constants.errno.ENOMSG; - result = os.constants.errno.ENOPROTOOPT; - result = os.constants.errno.ENOSPC; - result = os.constants.errno.ENOSR; - result = os.constants.errno.ENOSTR; - result = os.constants.errno.ENOSYS; - result = os.constants.errno.ENOTCONN; - result = os.constants.errno.ENOTDIR; - result = os.constants.errno.ENOTEMPTY; - result = os.constants.errno.ENOTSOCK; - result = os.constants.errno.ENOTSUP; - result = os.constants.errno.ENOTTY; - result = os.constants.errno.ENXIO; - result = os.constants.errno.EOPNOTSUPP; - result = os.constants.errno.EOVERFLOW; - result = os.constants.errno.EPERM; - result = os.constants.errno.EPIPE; - result = os.constants.errno.EPROTO; - result = os.constants.errno.EPROTONOSUPPORT; - result = os.constants.errno.EPROTOTYPE; - result = os.constants.errno.ERANGE; - result = os.constants.errno.EROFS; - result = os.constants.errno.ESPIPE; - result = os.constants.errno.ESRCH; - result = os.constants.errno.ESTALE; - result = os.constants.errno.ETIME; - result = os.constants.errno.ETIMEDOUT; - result = os.constants.errno.ETXTBSY; - result = os.constants.errno.EWOULDBLOCK; - result = os.constants.errno.EXDEV; - } - - if (os.platform() === 'win32') { - let result: number; - - result = os.constants.errno.WSAEINTR; - result = os.constants.errno.WSAEBADF; - result = os.constants.errno.WSAEACCES; - result = os.constants.errno.WSAEFAULT; - result = os.constants.errno.WSAEINVAL; - result = os.constants.errno.WSAEMFILE; - result = os.constants.errno.WSAEWOULDBLOCK; - result = os.constants.errno.WSAEINPROGRESS; - result = os.constants.errno.WSAEALREADY; - result = os.constants.errno.WSAENOTSOCK; - result = os.constants.errno.WSAEDESTADDRREQ; - result = os.constants.errno.WSAEMSGSIZE; - result = os.constants.errno.WSAEPROTOTYPE; - result = os.constants.errno.WSAENOPROTOOPT; - result = os.constants.errno.WSAEPROTONOSUPPORT; - result = os.constants.errno.WSAESOCKTNOSUPPORT; - result = os.constants.errno.WSAEOPNOTSUPP; - result = os.constants.errno.WSAEPFNOSUPPORT; - result = os.constants.errno.WSAEAFNOSUPPORT; - result = os.constants.errno.WSAEADDRINUSE; - result = os.constants.errno.WSAEADDRNOTAVAIL; - result = os.constants.errno.WSAENETDOWN; - result = os.constants.errno.WSAENETUNREACH; - result = os.constants.errno.WSAENETRESET; - result = os.constants.errno.WSAECONNABORTED; - result = os.constants.errno.WSAECONNRESET; - result = os.constants.errno.WSAENOBUFS; - result = os.constants.errno.WSAEISCONN; - result = os.constants.errno.WSAENOTCONN; - result = os.constants.errno.WSAESHUTDOWN; - result = os.constants.errno.WSAETOOMANYREFS; - result = os.constants.errno.WSAETIMEDOUT; - result = os.constants.errno.WSAECONNREFUSED; - result = os.constants.errno.WSAELOOP; - result = os.constants.errno.WSAENAMETOOLONG; - result = os.constants.errno.WSAEHOSTDOWN; - result = os.constants.errno.WSAEHOSTUNREACH; - result = os.constants.errno.WSAENOTEMPTY; - result = os.constants.errno.WSAEPROCLIM; - result = os.constants.errno.WSAEUSERS; - result = os.constants.errno.WSAEDQUOT; - result = os.constants.errno.WSAESTALE; - result = os.constants.errno.WSAEREMOTE; - result = os.constants.errno.WSASYSNOTREADY; - result = os.constants.errno.WSAVERNOTSUPPORTED; - result = os.constants.errno.WSANOTINITIALISED; - result = os.constants.errno.WSAEDISCON; - result = os.constants.errno.WSAENOMORE; - result = os.constants.errno.WSAECANCELLED; - result = os.constants.errno.WSAEINVALIDPROCTABLE; - result = os.constants.errno.WSAEINVALIDPROVIDER; - result = os.constants.errno.WSAEPROVIDERFAILEDINIT; - result = os.constants.errno.WSASYSCALLFAILURE; - result = os.constants.errno.WSASERVICE_NOT_FOUND; - result = os.constants.errno.WSATYPE_NOT_FOUND; - result = os.constants.errno.WSA_E_NO_MORE; - result = os.constants.errno.WSA_E_CANCELLED; - result = os.constants.errno.WSAEREFUSED; - } - - { - const prio = os.getPriority(); - os.setPriority(prio + 1); - - const prio2 = os.getPriority(1); - os.setPriority(2, prio + 1); - - os.setPriority(os.constants.priority.PRIORITY_LOW); - } -} - -//////////////////////////////////////////////////// -/// vm tests : https://nodejs.org/api/vm.html -//////////////////////////////////////////////////// - -{ - { - const sandbox = { - animal: 'cat', - count: 2 - }; - - const context = vm.createContext(sandbox); - console.log(vm.isContext(context)); - const script = new vm.Script('count += 1; name = "kitty"'); - - for (let i = 0; i < 10; ++i) { - script.runInContext(context); - } - - console.log(util.inspect(sandbox)); - - vm.runInNewContext('count += 1; name = "kitty"', sandbox); - console.log(util.inspect(sandbox)); - } - - { - const sandboxes = [{}, {}, {}]; - - const script = new vm.Script('globalVar = "set"'); - - sandboxes.forEach((sandbox) => { - script.runInNewContext(sandbox); - script.runInThisContext(); - }); - - console.log(util.inspect(sandboxes)); - - const localVar = 'initial value'; - vm.runInThisContext('localVar = "vm";'); - - console.log(localVar); - } - - { - vm.runInThisContext('console.log("hello world"', './my-file.js'); - } - - { - const fn: Function = vm.compileFunction('console.log("test")', [], { - parsingContext: vm.createContext(), - contextExtensions: [{ - a: 1, - }], - produceCachedData: false, - cachedData: Buffer.from('nope'), - }); - } -} - -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - -{ - { - const immediate = timers - .setImmediate(() => { - console.log('immediate'); - }) - .unref() - .ref(); - timers.clearImmediate(immediate); - } - { - const timeout = timers - .setInterval(() => { - console.log('interval'); - }, 20) - .unref() - .ref() - .refresh(); - timers.clearInterval(timeout); - } - { - const timeout = timers - .setTimeout(() => { - console.log('timeout'); - }, 20) - .unref() - .ref() - .refresh(); - timers.clearTimeout(timeout); - } - async function testPromisify() { - const setTimeout = util.promisify(timers.setTimeout); - let v: void = await setTimeout(100); // tslint:disable-line no-void-expression void-return - let s: string = await setTimeout(100, ""); - - const setImmediate = util.promisify(timers.setImmediate); - v = await setImmediate(); // tslint:disable-line no-void-expression - s = await setImmediate(""); - } -} - -///////////////////////////////////////////////////////// -/// Errors Tests : https://nodejs.org/api/errors.html /// -///////////////////////////////////////////////////////// - -{ - { - Error.stackTraceLimit = Infinity; - } - { - const myObject = {}; - Error.captureStackTrace(myObject); - } - { - const frames: NodeJS.CallSite[] = []; - Error.prepareStackTrace(new Error(), frames); - } - { - const frame: NodeJS.CallSite = null; - const frameThis: any = frame.getThis(); - const typeName: string = frame.getTypeName(); - const func: Function = frame.getFunction(); - const funcName: string = frame.getFunctionName(); - const meth: string = frame.getMethodName(); - const fname: string = frame.getFileName(); - const lineno: number = frame.getLineNumber(); - const colno: number = frame.getColumnNumber(); - const evalOrigin: string = frame.getEvalOrigin(); - const isTop: boolean = frame.isToplevel(); - const isEval: boolean = frame.isEval(); - const isNative: boolean = frame.isNative(); - const isConstr: boolean = frame.isConstructor(); - } -} - -/////////////////////////////////////////////////////////// -/// Process Tests : https://nodejs.org/api/process.html /// -/////////////////////////////////////////////////////////// - -import * as p from "process"; -{ - { - let eventEmitter: events.EventEmitter; - eventEmitter = process; // Test that process implements EventEmitter... - - let _p: NodeJS.Process = process; - _p = p; - } - { - assert(process.argv[0] === process.argv0); - } - { - let module: NodeModule | undefined; - module = process.mainModule; - } - { - process.on("message", (req: any) => { }); - process.addListener("beforeExit", (code: number) => { }); - process.once("disconnect", () => { }); - process.prependListener("exit", (code: number) => { }); - process.prependOnceListener("rejectionHandled", (promise: Promise) => { }); - process.on("uncaughtException", (error: Error) => { }); - process.addListener("unhandledRejection", (reason: any, promise: Promise) => { }); - process.once("warning", (warning: Error) => { }); - process.prependListener("message", (message: any, sendHandle: any) => { }); - process.prependOnceListener("SIGBREAK", () => { }); - process.on("newListener", (event: string | symbol, listener: Function) => { }); - process.once("removeListener", (event: string | symbol, listener: Function) => { }); - process.on("multipleResolves", (type: NodeJS.MultipleResolveType, prom: Promise, value: any) => {}); - process.on("customEvent", () => { }); - - const listeners = process.listeners('uncaughtException'); - const oldHandler = listeners[listeners.length - 1]; - process.addListener('uncaughtException', oldHandler); - } - { - function myCb(err: Error): void { - } - process.setUncaughtExceptionCaptureCallback(myCb); - process.setUncaughtExceptionCaptureCallback(null); - const b: boolean = process.hasUncaughtExceptionCaptureCallback(); - } - { - // process.allowedNodeEnvironmentFlags.has('asdf'); - } -} - -/////////////////////////////////////////////////////////// -/// Console Tests : https://nodejs.org/api/console.html /// -/////////////////////////////////////////////////////////// - -{ - { - let _c: Console = console; - _c = console2; - } - { - const writeStream = fs.createWriteStream('./index.d.ts'); - let consoleInstance: Console = new console.Console(writeStream); - - consoleInstance = new console.Console(writeStream, writeStream); - consoleInstance = new console.Console(writeStream, writeStream, true); - consoleInstance = new console.Console({ - stdout: writeStream, - stderr: writeStream, - colorMode: 'auto', - ignoreErrors: true - }); - consoleInstance = new console.Console({ - stdout: writeStream, - colorMode: false - }); - consoleInstance = new console.Console({ - stdout: writeStream - }); - } - { - console.assert('value'); - console.assert('value', 'message'); - console.assert('value', 'message', 'foo', 'bar'); - console.clear(); - console.count(); - console.count('label'); - console.countReset(); - console.countReset('label'); - console.debug(); - console.debug('message'); - console.debug('message', 'foo', 'bar'); - console.dir('obj'); - console.dir('obj', { depth: 1 }); - console.error(); - console.error('message'); - console.error('message', 'foo', 'bar'); - console.group(); - console.group('label'); - console.group('label1', 'label2'); - console.groupCollapsed(); - console.groupEnd(); - console.info(); - console.info('message'); - console.info('message', 'foo', 'bar'); - console.log(); - console.log('message'); - console.log('message', 'foo', 'bar'); - console.table({ foo: 'bar' }); - console.table([{ foo: 'bar' }]); - console.table([{ foo: 'bar' }], ['foo']); - console.time(); - console.time('label'); - console.timeEnd(); - console.timeEnd('label'); - console.timeLog(); - console.timeLog('label'); - console.timeLog('label', 'foo', 'bar'); - console.trace(); - console.trace('message'); - console.trace('message', 'foo', 'bar'); - console.warn(); - console.warn('message'); - console.warn('message', 'foo', 'bar'); - - // --- Inspector mode only --- - console.markTimeline(); - console.markTimeline('label'); - console.profile(); - console.profile('label'); - console.profileEnd(); - console.profileEnd('label'); - console.timeStamp(); - console.timeStamp('label'); - console.timeline(); - console.timeline('label'); - console.timelineEnd(); - console.timelineEnd('label'); - } -} - -/////////////////////////////////////////////////// -/// Net Tests : https://nodejs.org/api/net.html /// -/////////////////////////////////////////////////// - -{ - { - const connectOpts: net.NetConnectOpts = { - allowHalfOpen: true, - family: 4, - host: "localhost", - port: 443, - timeout: 10E3 - }; - const socket: net.Socket = net.createConnection(connectOpts, (): void => { - // nothing - }); - } - - { - let server = net.createServer(); - // Check methods which return server instances by chaining calls - server = server.listen(0) - .close() - .ref() - .unref(); - - // close callback parameter can be either nothing (undefined) or an error - server = server.close(() => { }); - server = server.close((err) => { - if (typeof err !== 'undefined') { const _err: Error = err; } - }); - - // test the types of the address object fields - const address: net.AddressInfo | string = server.address(); - } - - { - const constructorOpts: net.SocketConstructorOpts = { - fd: 1, - allowHalfOpen: false, - readable: false, - writable: false - }; - - /** - * net.Socket - events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout - */ - let _socket: net.Socket = new net.Socket(constructorOpts); - - let bool: boolean; - let buffer: Buffer; - let error: Error; - let str: string; - let num: number; - - const ipcConnectOpts: net.IpcSocketConnectOpts = { - path: "/" - }; - const tcpConnectOpts: net.TcpSocketConnectOpts = { - family: 4, - hints: 0, - host: "localhost", - localAddress: "10.0.0.1", - localPort: 1234, - lookup: (_hostname: string, _options: dns.LookupOneOptions, _callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void => { - // nothing - }, - port: 80 - }; - _socket = _socket.connect(ipcConnectOpts); - _socket = _socket.connect(ipcConnectOpts, (): void => {}); - _socket = _socket.connect(tcpConnectOpts); - _socket = _socket.connect(tcpConnectOpts, (): void => {}); - _socket = _socket.connect(80, "localhost"); - _socket = _socket.connect(80, "localhost", (): void => {}); - _socket = _socket.connect(80); - _socket = _socket.connect(80, (): void => {}); - - /// addListener - - _socket = _socket.addListener("close", had_error => { - bool = had_error; - }); - _socket = _socket.addListener("connect", () => { }); - _socket = _socket.addListener("data", data => { - buffer = data; - }); - _socket = _socket.addListener("drain", () => { }); - _socket = _socket.addListener("end", () => { }); - _socket = _socket.addListener("error", err => { - error = err; - }); - _socket = _socket.addListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.addListener("timeout", () => { }); - - /// emit - bool = _socket.emit("close", bool); - bool = _socket.emit("connect"); - bool = _socket.emit("data", buffer); - bool = _socket.emit("drain"); - bool = _socket.emit("end"); - bool = _socket.emit("error", error); - bool = _socket.emit("lookup", error, str, str, str); - bool = _socket.emit("lookup", error, str, num, str); - bool = _socket.emit("timeout"); - - /// on - _socket = _socket.on("close", had_error => { - bool = had_error; - }); - _socket = _socket.on("connect", () => { }); - _socket = _socket.on("data", data => { - buffer = data; - }); - _socket = _socket.on("drain", () => { }); - _socket = _socket.on("end", () => { }); - _socket = _socket.on("error", err => { - error = err; - }); - _socket = _socket.on("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.on("timeout", () => { }); - - /// once - _socket = _socket.once("close", had_error => { - bool = had_error; - }); - _socket = _socket.once("connect", () => { }); - _socket = _socket.once("data", data => { - buffer = data; - }); - _socket = _socket.once("drain", () => { }); - _socket = _socket.once("end", () => { }); - _socket = _socket.once("error", err => { - error = err; - }); - _socket = _socket.once("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.once("timeout", () => { }); - - /// prependListener - _socket = _socket.prependListener("close", had_error => { - bool = had_error; - }); - _socket = _socket.prependListener("connect", () => { }); - _socket = _socket.prependListener("data", data => { - buffer = data; - }); - _socket = _socket.prependListener("drain", () => { }); - _socket = _socket.prependListener("end", () => { }); - _socket = _socket.prependListener("error", err => { - error = err; - }); - _socket = _socket.prependListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.prependListener("timeout", () => { }); - - /// prependOnceListener - _socket = _socket.prependOnceListener("close", had_error => { - bool = had_error; - }); - _socket = _socket.prependOnceListener("connect", () => { }); - _socket = _socket.prependOnceListener("data", data => { - buffer = data; - }); - _socket = _socket.prependOnceListener("drain", () => { }); - _socket = _socket.prependOnceListener("end", () => { }); - _socket = _socket.prependOnceListener("error", err => { - error = err; - }); - _socket = _socket.prependOnceListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.prependOnceListener("timeout", () => { }); - - bool = _socket.connecting; - bool = _socket.destroyed; - _socket.destroy(); - } - - { - /** - * net.Server - events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - */ - let _server: net.Server; - - let _socket: net.Socket; - let bool: boolean; - let error: Error; - - /// addListener - _server = _server.addListener("close", () => { }); - _server = _server.addListener("connection", socket => { - _socket = socket; - }); - _server = _server.addListener("error", err => { - error = err; - }); - _server = _server.addListener("listening", () => { }); - - /// emit - bool = _server.emit("close"); - bool = _server.emit("connection", _socket); - bool = _server.emit("error", error); - bool = _server.emit("listening"); - - /// once - _server = _server.once("close", () => { }); - _server = _server.once("connection", socket => { - _socket = socket; - }); - _server = _server.once("error", err => { - error = err; - }); - _server = _server.once("listening", () => { }); - - /// prependListener - _server = _server.prependListener("close", () => { }); - _server = _server.prependListener("connection", socket => { - _socket = socket; - }); - _server = _server.prependListener("error", err => { - error = err; - }); - _server = _server.prependListener("listening", () => { }); - - /// prependOnceListener - _server = _server.prependOnceListener("close", () => { }); - _server = _server.prependOnceListener("connection", socket => { - _socket = socket; - }); - _server = _server.prependOnceListener("error", err => { - error = err; - }); - _server = _server.prependOnceListener("listening", () => { }); - } -} - -///////////////////////////////////////////////////// -/// repl Tests : https://nodejs.org/api/repl.html /// -///////////////////////////////////////////////////// - -{ - { - let _server: repl.REPLServer; - let _boolean: boolean; - const _ctx: vm.Context = {}; - - _server = _server.addListener("exit", () => { }); - _server = _server.addListener("reset", () => { }); - - _boolean = _server.emit("exit", () => { }); - _boolean = _server.emit("reset", _ctx); - - _server = _server.on("exit", () => { }); - _server = _server.on("reset", () => { }); - - _server = _server.once("exit", () => { }); - _server = _server.once("reset", () => { }); - - _server = _server.prependListener("exit", () => { }); - _server = _server.prependListener("reset", () => { }); - - _server = _server.prependOnceListener("exit", () => { }); - _server = _server.prependOnceListener("reset", () => { }); - - _server.outputStream.write("test"); - const line = _server.inputStream.read(); - - _server.clearBufferedCommand(); - _server.displayPrompt(); - _server.displayPrompt(true); - _server.defineCommand("cmd", function(text) { - // $ExpectType string - text; - // $ExpectType REPLServer - this; - }); - _server.defineCommand("cmd", { - help: "", - action(text) { - // $ExpectType string - text; - // $ExpectType REPLServer - this; - } - }); - - repl.start({ - eval() { - // $ExpectType REPLServer - this; - }, - writer() { - // $ExpectType REPLServer - this; - return ""; - } - }); - - function test() { - throw new repl.Recoverable(new Error("test")); - } - - _server.context['key0'] = 1; - _server.context['key1'] = ""; - _server.context['key2'] = true; - _server.context['key3'] = []; - _server.context['key4'] = {}; - } -} - -/////////////////////////////////////////////////// -/// DNS Tests : https://nodejs.org/api/dns.html /// -/////////////////////////////////////////////////// - -{ - dns.lookup("nodejs.org", (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 4, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 6, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", {}, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup( - "nodejs.org", - { - family: 4, - hints: dns.ADDRCONFIG | dns.V4MAPPED, - all: false - }, - (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - } - ); - dns.lookup("nodejs.org", { all: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException = err; - const _address: dns.LookupAddress[] = addresses; - }); - dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException = err; - const _address: dns.LookupAddress[] = addresses; - }); - - function trueOrFalse(): boolean { - return Math.random() > 0.5 ? true : false; - } - dns.lookup("nodejs.org", { all: trueOrFalse() }, (err, addresses, family) => { - const _err: NodeJS.ErrnoException = err; - const _addresses: string | dns.LookupAddress[] = addresses; - const _family: number | undefined = family; - }); - - dns.lookupService("127.0.0.1", 0, (err, hostname, service) => { - const _err: NodeJS.ErrnoException = err; - const _hostname: string = hostname; - const _service: string = service; - }); - - dns.resolve("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "A", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "AAAA", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "ANY", (err, addresses) => { - const _addresses: dns.AnyRecord[] = addresses; - }); - dns.resolve("nodejs.org", "MX", (err, addresses) => { - const _addresses: dns.MxRecord[] = addresses; - }); - - dns.resolve4("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve4("nodejs.org", { ttl: true }, (err, addresses) => { - const _addresses: dns.RecordWithTtl[] = addresses; - }); - { - const ttl = false; - dns.resolve4("nodejs.org", { ttl }, (err, addresses) => { - const _addresses: string[] | dns.RecordWithTtl[] = addresses; - }); - } - - dns.resolve6("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve6("nodejs.org", { ttl: true }, (err, addresses) => { - const _addresses: dns.RecordWithTtl[] = addresses; - }); - { - const ttl = false; - dns.resolve6("nodejs.org", { ttl }, (err, addresses) => { - const _addresses: string[] | dns.RecordWithTtl[] = addresses; - }); - } - { - const resolver = new dns.Resolver(); - resolver.setServers(["4.4.4.4"]); - resolver.resolve("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - resolver.cancel(); - } -} - -/***************************************************************************** - * * - * The following tests are the modules not mentioned in document but existed * - * * - *****************************************************************************/ - -/////////////////////////////////////////////////////////// -/// Constants Tests /// -/////////////////////////////////////////////////////////// - -import * as constants from 'constants'; -{ - let str: string; - let num: number; - num = constants.SIGHUP; - num = constants.SIGINT; - num = constants.SIGQUIT; - num = constants.SIGILL; - num = constants.SIGTRAP; - num = constants.SIGABRT; - num = constants.SIGIOT; - num = constants.SIGBUS; - num = constants.SIGFPE; - num = constants.SIGKILL; - num = constants.SIGUSR1; - num = constants.SIGSEGV; - num = constants.SIGUSR2; - num = constants.SIGPIPE; - num = constants.SIGALRM; - num = constants.SIGTERM; - num = constants.SIGCHLD; - num = constants.SIGSTKFLT; - num = constants.SIGCONT; - num = constants.SIGSTOP; - num = constants.SIGTSTP; - num = constants.SIGTTIN; - num = constants.SIGTTOU; - num = constants.SIGURG; - num = constants.SIGXCPU; - num = constants.SIGXFSZ; - num = constants.SIGVTALRM; - num = constants.SIGPROF; - num = constants.SIGWINCH; - num = constants.SIGIO; - num = constants.SIGPOLL; - num = constants.SIGPWR; - num = constants.SIGSYS; - num = constants.SIGUNUSED; - num = constants.O_RDONLY; - num = constants.O_WRONLY; - num = constants.O_RDWR; - num = constants.S_IFMT; - num = constants.S_IFREG; - num = constants.S_IFDIR; - num = constants.S_IFCHR; - num = constants.S_IFBLK; - num = constants.S_IFIFO; - num = constants.S_IFLNK; - num = constants.S_IFSOCK; - num = constants.O_CREAT; - num = constants.O_EXCL; - num = constants.O_NOCTTY; - num = constants.O_TRUNC; - num = constants.O_APPEND; - num = constants.O_DIRECTORY; - num = constants.O_NOATIME; - num = constants.O_NOFOLLOW; - num = constants.O_SYNC; - num = constants.O_DSYNC; - num = constants.O_DIRECT; - num = constants.O_NONBLOCK; - num = constants.S_IRWXU; - num = constants.S_IRUSR; - num = constants.S_IWUSR; - num = constants.S_IXUSR; - num = constants.S_IRWXG; - num = constants.S_IRGRP; - num = constants.S_IWGRP; - num = constants.S_IXGRP; - num = constants.S_IRWXO; - num = constants.S_IROTH; - num = constants.S_IWOTH; - num = constants.S_IXOTH; - num = constants.F_OK; - num = constants.R_OK; - num = constants.W_OK; - num = constants.X_OK; - num = constants.SSL_OP_ALL; - num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION; - num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE; - num = constants.SSL_OP_CISCO_ANYCONNECT; - num = constants.SSL_OP_COOKIE_EXCHANGE; - num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG; - num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; - num = constants.SSL_OP_EPHEMERAL_RSA; - num = constants.SSL_OP_LEGACY_SERVER_CONNECT; - num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER; - num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG; - num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING; - num = constants.SSL_OP_NETSCAPE_CA_DN_BUG; - num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG; - num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG; - num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; - num = constants.SSL_OP_NO_COMPRESSION; - num = constants.SSL_OP_NO_QUERY_MTU; - num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION; - num = constants.SSL_OP_NO_SSLv2; - num = constants.SSL_OP_NO_SSLv3; - num = constants.SSL_OP_NO_TICKET; - num = constants.SSL_OP_NO_TLSv1; - num = constants.SSL_OP_NO_TLSv1_1; - num = constants.SSL_OP_NO_TLSv1_2; - num = constants.SSL_OP_PKCS1_CHECK_1; - num = constants.SSL_OP_PKCS1_CHECK_2; - num = constants.SSL_OP_SINGLE_DH_USE; - num = constants.SSL_OP_SINGLE_ECDH_USE; - num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG; - num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG; - num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG; - num = constants.SSL_OP_TLS_D5_BUG; - num = constants.SSL_OP_TLS_ROLLBACK_BUG; - num = constants.ENGINE_METHOD_RSA; - num = constants.ENGINE_METHOD_DSA; - num = constants.ENGINE_METHOD_DH; - num = constants.ENGINE_METHOD_RAND; - num = constants.ENGINE_METHOD_ECDH; - num = constants.ENGINE_METHOD_ECDSA; - num = constants.ENGINE_METHOD_CIPHERS; - num = constants.ENGINE_METHOD_DIGESTS; - num = constants.ENGINE_METHOD_STORE; - num = constants.ENGINE_METHOD_PKEY_METHS; - num = constants.ENGINE_METHOD_PKEY_ASN1_METHS; - num = constants.ENGINE_METHOD_ALL; - num = constants.ENGINE_METHOD_NONE; - num = constants.DH_CHECK_P_NOT_SAFE_PRIME; - num = constants.DH_CHECK_P_NOT_PRIME; - num = constants.DH_UNABLE_TO_CHECK_GENERATOR; - num = constants.DH_NOT_SUITABLE_GENERATOR; - num = constants.NPN_ENABLED; - num = constants.ALPN_ENABLED; - num = constants.RSA_PKCS1_PADDING; - num = constants.RSA_SSLV23_PADDING; - num = constants.RSA_NO_PADDING; - num = constants.RSA_PKCS1_OAEP_PADDING; - num = constants.RSA_X931_PADDING; - num = constants.RSA_PKCS1_PSS_PADDING; - num = constants.POINT_CONVERSION_COMPRESSED; - num = constants.POINT_CONVERSION_UNCOMPRESSED; - num = constants.POINT_CONVERSION_HYBRID; - str = constants.defaultCoreCipherList; - str = constants.defaultCipherList; -} - -//////////////////////////////////////////////////// -/// v8 tests : https://nodejs.org/api/v8.html -//////////////////////////////////////////////////// - -{ - const heapStats = v8.getHeapStatistics(); - const heapSpaceStats = v8.getHeapSpaceStatistics(); - - const zapsGarbage: number = heapStats.does_zap_garbage; - - v8.setFlagsFromString('--collect_maps'); -} - -//////////////////////////////////////////////////// -/// PerfHooks tests : https://nodejs.org/api/perf_hooks.html -//////////////////////////////////////////////////// -{ - perf_hooks.performance.mark('start'); - ( - () => {} - )(); - perf_hooks.performance.mark('end'); - - const timeOrigin = perf_hooks.performance.timeOrigin; - - const performanceObserverCallback: perf_hooks.PerformanceObserverCallback = (list, obs) => { - const { - duration, - entryType, - name, - startTime, - } = list.getEntries()[0]; - obs.disconnect(); - }; - const obs = new perf_hooks.PerformanceObserver(performanceObserverCallback); - obs.observe({ - entryTypes: ['function'], - buffered: true, - }); -} - -//////////////////////////////////////////////////// -/// AsyncHooks tests : https://nodejs.org/api/async_hooks.html -//////////////////////////////////////////////////// -{ - const hooks: async_hooks.HookCallbacks = { - init() {}, - before() {}, - after() {}, - destroy() {}, - promiseResolve() {}, - }; - - const asyncHook = async_hooks.createHook(hooks); - - asyncHook.enable().disable().enable(); - - const tId: number = async_hooks.triggerAsyncId(); - const eId: number = async_hooks.executionAsyncId(); - - class TestResource extends async_hooks.AsyncResource { - constructor() { - super('TEST_RESOURCE'); - } - } - - class AnotherTestResource extends async_hooks.AsyncResource { - constructor() { - super('TEST_RESOURCE', 42); - const aId: number = this.asyncId(); - const tId: number = this.triggerAsyncId(); - } - run() { - this.runInAsyncScope(() => {}); - this.runInAsyncScope(Array.prototype.find, [], () => true); - } - destroy() { - this.emitDestroy(); - } - } - - // check AsyncResource constructor options. - new async_hooks.AsyncResource(''); - new async_hooks.AsyncResource('', 0); - new async_hooks.AsyncResource('', {}); - new async_hooks.AsyncResource('', { triggerAsyncId: 0 }); - new async_hooks.AsyncResource('', { - triggerAsyncId: 0, - requireManualDestroy: true - }); -} - -//////////////////////////////////////////////////// -/// zlib tests : http://nodejs.org/api/zlib.html /// -//////////////////////////////////////////////////// - -{ - { - const gzipped = zlib.gzipSync('test'); - const unzipped = zlib.gunzipSync(gzipped.toString()); - } - - { - const deflate = zlib.deflateSync('test'); - const inflate = zlib.inflateSync(deflate.toString()); - } - - { - const gzip = zlib.createGzip(); - const written: number = gzip.bytesWritten; - } -} - -/////////////////////////////////////////////////////////// -/// HTTP/2 Tests /// -/////////////////////////////////////////////////////////// - -{ - // Headers & Settings - { - const headers: http2.OutgoingHttpHeaders = { - ':status': 200, - 'content-type': 'text-plain', - ABC: ['has', 'more', 'than', 'one', 'value'], - undef: undefined - }; - - const settings: http2.Settings = { - headerTableSize: 0, - enablePush: true, - initialWindowSize: 0, - maxFrameSize: 0, - maxConcurrentStreams: 0, - maxHeaderListSize: 0 - }; - } - - // Http2Session - { - const http2Session: http2.Http2Session = {} as any; - const ee: events.EventEmitter = http2Session; - - http2Session.on('close', () => {}); - http2Session.on('connect', (session: http2.Http2Session, socket: net.Socket) => {}); - http2Session.on('error', (err: Error) => {}); - http2Session.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); - http2Session.on('goaway', (errorCode: number, lastStreamID: number, opaqueData: Buffer) => {}); - http2Session.on('localSettings', (settings: http2.Settings) => {}); - http2Session.on('remoteSettings', (settings: http2.Settings) => {}); - http2Session.on('stream', (stream: http2.Http2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - http2Session.on('timeout', () => {}); - http2Session.on('ping', () => {}); - - http2Session.destroy(); - - const alpnProtocol: string = http2Session.alpnProtocol; - const destroyed: boolean = http2Session.destroyed; - const encrypted: boolean = http2Session.encrypted; - const originSet: string[] = http2Session.originSet; - const pendingSettingsAck: boolean = http2Session.pendingSettingsAck; - let settings: http2.Settings = http2Session.localSettings; - const closed: boolean = http2Session.closed; - const connecting: boolean = http2Session.connecting; - settings = http2Session.remoteSettings; - - http2Session.ref(); - http2Session.unref(); - - const headers: http2.OutgoingHttpHeaders = {}; - const options: http2.ClientSessionRequestOptions = { - endStream: true, - exclusive: true, - parent: 0, - weight: 0, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {} - }; - (http2Session as http2.ClientHttp2Session).request(); - (http2Session as http2.ClientHttp2Session).request(headers); - (http2Session as http2.ClientHttp2Session).request(headers, options); - - const stream: http2.Http2Stream = {} as any; - http2Session.rstStream(stream); - http2Session.rstStream(stream, 0); - - http2Session.setTimeout(100, () => {}); - http2Session.close(() => {}); - - const socket: net.Socket | tls.TLSSocket = http2Session.socket; - let state: http2.SessionState = http2Session.state; - state = { - effectiveLocalWindowSize: 0, - effectiveRecvDataLength: 0, - nextStreamID: 0, - localWindowSize: 0, - lastProcStreamID: 0, - remoteWindowSize: 0, - outboundQueueSize: 0, - deflateDynamicTableSize: 0, - inflateDynamicTableSize: 0 - }; - - http2Session.priority(stream, { - exclusive: true, - parent: 0, - weight: 0, - silent: true - }); - - http2Session.settings(settings); - - http2Session.ping((err: Error | null, duration: number, payload: Buffer) => {}); - http2Session.ping(Buffer.from(''), (err: Error | null, duration: number, payload: Buffer) => {}); - http2Session.ping(new DataView(new Int8Array(1).buffer), (err: Error | null, duration: number, payload: Buffer) => {}); - } - - // Http2Stream - { - const http2Stream: http2.Http2Stream = {} as any; - const duplex: stream.Duplex = http2Stream; - - http2Stream.on('aborted', () => {}); - http2Stream.on('error', (err: Error) => {}); - http2Stream.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); - http2Stream.on('streamClosed', (code: number) => {}); - http2Stream.on('timeout', () => {}); - http2Stream.on('trailers', (trailers: http2.IncomingHttpHeaders, flags: number) => {}); - http2Stream.on('wantTrailers', () => {}); - - const aborted: boolean = http2Stream.aborted; - const closed: boolean = http2Stream.closed; - const destroyed: boolean = http2Stream.destroyed; - const pending: boolean = http2Stream.pending; - - http2Stream.priority({ - exclusive: true, - parent: 0, - weight: 0, - silent: true - }); - - const sesh: http2.Http2Session = http2Stream.session; - - http2Stream.setTimeout(100, () => {}); - - let state: http2.StreamState = http2Stream.state; - state = { - localWindowSize: 0, - state: 0, - streamLocalClose: 0, - streamRemoteClose: 0, - sumDependencyWeight: 0, - weight: 0 - }; - - http2Stream.close(); - http2Stream.close(0); - http2Stream.close(0, () => {}); - http2Stream.close(undefined, () => {}); - - // ClientHttp2Stream - const clientHttp2Stream: http2.ClientHttp2Stream = {} as any; - clientHttp2Stream.on('headers', (headers: http2.IncomingHttpHeaders, flags: number) => {}); - clientHttp2Stream.on('push', (headers: http2.IncomingHttpHeaders, flags: number) => {}); - clientHttp2Stream.on('response', (headers: http2.IncomingHttpHeaders & http2.IncomingHttpStatusHeader, flags: number) => { - const s: number = headers[':status']; - }); - - // ServerHttp2Stream - const serverHttp2Stream: http2.ServerHttp2Stream = {} as any; - const headers: http2.OutgoingHttpHeaders = {}; - - serverHttp2Stream.additionalHeaders(headers); - const headerSent: boolean = serverHttp2Stream.headersSent; - const pushAllowed: boolean = serverHttp2Stream.pushAllowed; - serverHttp2Stream.pushStream(headers, (err: Error | null, pushStream: http2.ServerHttp2Stream, headers: http2.OutgoingHttpHeaders) => {}); - - const options: http2.ServerStreamResponseOptions = { - endStream: true, - waitForTrailers: true, - }; - serverHttp2Stream.respond(); - serverHttp2Stream.respond(headers); - serverHttp2Stream.respond(headers, options); - - const options2: http2.ServerStreamFileResponseOptions = { - statCheck: (stats: fs.Stats, headers: http2.OutgoingHttpHeaders, statOptions: http2.StatOptions) => {}, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {}, - offset: 0, - length: 0 - }; - serverHttp2Stream.respondWithFD(0); - serverHttp2Stream.respondWithFD(0, headers); - serverHttp2Stream.respondWithFD(0, headers, options2); - serverHttp2Stream.respondWithFD(0, headers, {statCheck: () => false}); - const options3: http2.ServerStreamFileResponseOptionsWithError = { - onError: (err: NodeJS.ErrnoException) => {}, - statCheck: (stats: fs.Stats, headers: http2.OutgoingHttpHeaders, statOptions: http2.StatOptions) => {}, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {}, - offset: 0, - length: 0 - }; - serverHttp2Stream.respondWithFile(''); - serverHttp2Stream.respondWithFile('', headers); - serverHttp2Stream.respondWithFile('', headers, options3); - serverHttp2Stream.respondWithFile('', headers, {statCheck: () => false}); - } - - // Http2Server / Http2SecureServer - { - const http2Server: http2.Http2Server = http2.createServer(); - const http2SecureServer: http2.Http2SecureServer = http2.createSecureServer(); - const s1: net.Server = http2Server; - const s2: tls.Server = http2SecureServer; - [http2Server, http2SecureServer].forEach((server) => { - server.on('sessionError', (err: Error) => {}); - server.on('checkContinue', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - server.on('stream', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - server.on('request', (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => {}); - server.on('timeout', () => {}); - }); - - http2SecureServer.on('unknownProtocol', (socket: tls.TLSSocket) => {}); - } - - // Public API (except constants) - { - let settings: http2.Settings; - const serverOptions: http2.ServerOptions = { - maxDeflateDynamicTableSize: 0, - maxReservedRemoteStreams: 0, - maxSendHeaderBlockLength: 0, - paddingStrategy: 0, - peerMaxConcurrentStreams: 0, - selectPadding: (frameLen: number, maxFrameLen: number) => 0, - settings - }; - // tslint:disable-next-line prefer-object-spread (ts2.1 feature) - const secureServerOptions: http2.SecureServerOptions = Object.assign({}, serverOptions); - secureServerOptions.ca = ''; - const onRequestHandler = (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => { - // Http2ServerRequest - - const readable: stream.Readable = request; - let incomingHeaders: http2.IncomingHttpHeaders = request.headers; - incomingHeaders = request.trailers; - const httpVersion: string = request.httpVersion; - let method: string = request.method; - let rawHeaders: string[] = request.rawHeaders; - rawHeaders = request.rawTrailers; - let socket: net.Socket | tls.TLSSocket = request.socket; - let stream: http2.ServerHttp2Stream = request.stream; - const url: string = request.url; - - request.setTimeout(0, () => {}); - request.on('aborted', (hadError: boolean, code: number) => {}); - - // Http2ServerResponse - - let outgoingHeaders: http2.OutgoingHttpHeaders; - response.addTrailers(outgoingHeaders); - socket = response.connection; - const finished: boolean = response.finished; - response.sendDate = true; - response.statusCode = 200; - response.statusMessage = ''; - socket = response.socket; - stream = response.stream; - - method = response.getHeader(':method'); - const headers: string[] = response.getHeaderNames(); - outgoingHeaders = response.getHeaders(); - const hasMethod = response.hasHeader(':method'); - response.removeHeader(':method'); - response.setHeader(':method', 'GET'); - response.setHeader(':status', 200); - response.setHeader('some-list', ['', '']); - const headersSent: boolean = response.headersSent; - - response.setTimeout(0, () => {}); - response.createPushResponse(outgoingHeaders, (err: Error | null, res: http2.Http2ServerResponse) => {}); - - response.writeContinue(); - response.writeHead(200); - response.writeHead(200, outgoingHeaders); - response.writeHead(200, 'OK', outgoingHeaders); - response.writeHead(200, 'OK'); - response.write(''); - response.write('', (err: Error) => {}); - response.write('', 'utf8'); - response.write('', 'utf8', (err: Error) => {}); - response.write(Buffer.from([])); - response.write(Buffer.from([]), (err: Error) => {}); - response.write(Buffer.from([]), 'utf8'); - response.write(Buffer.from([]), 'utf8', (err: Error) => {}); - response.end(); - response.end(() => {}); - response.end(''); - response.end('', () => {}); - response.end('', 'utf8'); - response.end('', 'utf8', () => {}); - response.end(Buffer.from([])); - response.end(Buffer.from([]), () => {}); - response.end(Buffer.from([]), 'utf8'); - response.end(Buffer.from([]), 'utf8', () => {}); - - request.on('aborted', (hadError: boolean, code: number) => {}); - request.on('close', () => {}); - request.on('drain', () => {}); - request.on('error', (error: Error) => {}); - request.on('finish', () => {}); - }; - - let http2Server: http2.Http2Server; - let http2SecureServer: http2.Http2SecureServer; - - http2Server = http2.createServer(); - http2Server = http2.createServer(serverOptions); - http2Server = http2.createServer(onRequestHandler); - http2Server = http2.createServer(serverOptions, onRequestHandler); - - http2SecureServer = http2.createSecureServer(); - http2SecureServer = http2.createSecureServer(secureServerOptions); - http2SecureServer = http2.createSecureServer(onRequestHandler); - http2SecureServer = http2.createSecureServer(secureServerOptions, onRequestHandler); - - const clientSessionOptions: http2.ClientSessionOptions = { - maxDeflateDynamicTableSize: 0, - maxReservedRemoteStreams: 0, - maxSendHeaderBlockLength: 0, - paddingStrategy: 0, - peerMaxConcurrentStreams: 0, - selectPadding: (frameLen: number, maxFrameLen: number) => 0, - settings - }; - // tslint:disable-next-line prefer-object-spread (ts2.1 feature) - const secureClientSessionOptions: http2.SecureClientSessionOptions = Object.assign({}, clientSessionOptions); - secureClientSessionOptions.ca = ''; - const onConnectHandler = (session: http2.Http2Session, socket: net.Socket) => {}; - - const serverHttp2Session: http2.ServerHttp2Session = {} as any; - - serverHttp2Session.altsvc('', ''); - serverHttp2Session.altsvc('', 0); - serverHttp2Session.altsvc('', new url.URL('')); - serverHttp2Session.altsvc('', { origin: '' }); - serverHttp2Session.altsvc('', { origin: 0 }); - serverHttp2Session.altsvc('', { origin: new url.URL('') }); - - let clientHttp2Session: http2.ClientHttp2Session; - - clientHttp2Session = http2.connect(''); - clientHttp2Session = http2.connect('', onConnectHandler); - clientHttp2Session = http2.connect('', clientSessionOptions); - clientHttp2Session = http2.connect('', clientSessionOptions, onConnectHandler); - clientHttp2Session = http2.connect('', secureClientSessionOptions); - clientHttp2Session = http2.connect('', secureClientSessionOptions, onConnectHandler); - clientHttp2Session.on('altsvc', (alt: string, origin: string, number: number) => {}); - - settings = http2.getDefaultSettings(); - settings = http2.getPackedSettings(settings); - settings = http2.getUnpackedSettings(Buffer.from([])); - settings = http2.getUnpackedSettings(Uint8Array.from([])); - } - - // constants - { - const constants = http2.constants; - let num: number; - let str: string; - num = constants.NGHTTP2_SESSION_SERVER; - num = constants.NGHTTP2_SESSION_CLIENT; - num = constants.NGHTTP2_STREAM_STATE_IDLE; - num = constants.NGHTTP2_STREAM_STATE_OPEN; - num = constants.NGHTTP2_STREAM_STATE_RESERVED_LOCAL; - num = constants.NGHTTP2_STREAM_STATE_RESERVED_REMOTE; - num = constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL; - num = constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE; - num = constants.NGHTTP2_STREAM_STATE_CLOSED; - num = constants.NGHTTP2_NO_ERROR; - num = constants.NGHTTP2_PROTOCOL_ERROR; - num = constants.NGHTTP2_INTERNAL_ERROR; - num = constants.NGHTTP2_FLOW_CONTROL_ERROR; - num = constants.NGHTTP2_SETTINGS_TIMEOUT; - num = constants.NGHTTP2_STREAM_CLOSED; - num = constants.NGHTTP2_FRAME_SIZE_ERROR; - num = constants.NGHTTP2_REFUSED_STREAM; - num = constants.NGHTTP2_CANCEL; - num = constants.NGHTTP2_COMPRESSION_ERROR; - num = constants.NGHTTP2_CONNECT_ERROR; - num = constants.NGHTTP2_ENHANCE_YOUR_CALM; - num = constants.NGHTTP2_INADEQUATE_SECURITY; - num = constants.NGHTTP2_HTTP_1_1_REQUIRED; - num = constants.NGHTTP2_ERR_FRAME_SIZE_ERROR; - num = constants.NGHTTP2_FLAG_NONE; - num = constants.NGHTTP2_FLAG_END_STREAM; - num = constants.NGHTTP2_FLAG_END_HEADERS; - num = constants.NGHTTP2_FLAG_ACK; - num = constants.NGHTTP2_FLAG_PADDED; - num = constants.NGHTTP2_FLAG_PRIORITY; - num = constants.DEFAULT_SETTINGS_HEADER_TABLE_SIZE; - num = constants.DEFAULT_SETTINGS_ENABLE_PUSH; - num = constants.DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE; - num = constants.DEFAULT_SETTINGS_MAX_FRAME_SIZE; - num = constants.MAX_MAX_FRAME_SIZE; - num = constants.MIN_MAX_FRAME_SIZE; - num = constants.MAX_INITIAL_WINDOW_SIZE; - num = constants.NGHTTP2_DEFAULT_WEIGHT; - num = constants.NGHTTP2_SETTINGS_HEADER_TABLE_SIZE; - num = constants.NGHTTP2_SETTINGS_ENABLE_PUSH; - num = constants.NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; - num = constants.NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; - num = constants.NGHTTP2_SETTINGS_MAX_FRAME_SIZE; - num = constants.NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE; - num = constants.PADDING_STRATEGY_NONE; - num = constants.PADDING_STRATEGY_MAX; - num = constants.PADDING_STRATEGY_CALLBACK; - num = constants.HTTP_STATUS_CONTINUE; - num = constants.HTTP_STATUS_SWITCHING_PROTOCOLS; - num = constants.HTTP_STATUS_PROCESSING; - num = constants.HTTP_STATUS_OK; - num = constants.HTTP_STATUS_CREATED; - num = constants.HTTP_STATUS_ACCEPTED; - num = constants.HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION; - num = constants.HTTP_STATUS_NO_CONTENT; - num = constants.HTTP_STATUS_RESET_CONTENT; - num = constants.HTTP_STATUS_PARTIAL_CONTENT; - num = constants.HTTP_STATUS_MULTI_STATUS; - num = constants.HTTP_STATUS_ALREADY_REPORTED; - num = constants.HTTP_STATUS_IM_USED; - num = constants.HTTP_STATUS_MULTIPLE_CHOICES; - num = constants.HTTP_STATUS_MOVED_PERMANENTLY; - num = constants.HTTP_STATUS_FOUND; - num = constants.HTTP_STATUS_SEE_OTHER; - num = constants.HTTP_STATUS_NOT_MODIFIED; - num = constants.HTTP_STATUS_USE_PROXY; - num = constants.HTTP_STATUS_TEMPORARY_REDIRECT; - num = constants.HTTP_STATUS_PERMANENT_REDIRECT; - num = constants.HTTP_STATUS_BAD_REQUEST; - num = constants.HTTP_STATUS_UNAUTHORIZED; - num = constants.HTTP_STATUS_PAYMENT_REQUIRED; - num = constants.HTTP_STATUS_FORBIDDEN; - num = constants.HTTP_STATUS_NOT_FOUND; - num = constants.HTTP_STATUS_METHOD_NOT_ALLOWED; - num = constants.HTTP_STATUS_NOT_ACCEPTABLE; - num = constants.HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED; - num = constants.HTTP_STATUS_REQUEST_TIMEOUT; - num = constants.HTTP_STATUS_CONFLICT; - num = constants.HTTP_STATUS_GONE; - num = constants.HTTP_STATUS_LENGTH_REQUIRED; - num = constants.HTTP_STATUS_PRECONDITION_FAILED; - num = constants.HTTP_STATUS_PAYLOAD_TOO_LARGE; - num = constants.HTTP_STATUS_URI_TOO_LONG; - num = constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE; - num = constants.HTTP_STATUS_RANGE_NOT_SATISFIABLE; - num = constants.HTTP_STATUS_EXPECTATION_FAILED; - num = constants.HTTP_STATUS_TEAPOT; - num = constants.HTTP_STATUS_MISDIRECTED_REQUEST; - num = constants.HTTP_STATUS_UNPROCESSABLE_ENTITY; - num = constants.HTTP_STATUS_LOCKED; - num = constants.HTTP_STATUS_FAILED_DEPENDENCY; - num = constants.HTTP_STATUS_UNORDERED_COLLECTION; - num = constants.HTTP_STATUS_UPGRADE_REQUIRED; - num = constants.HTTP_STATUS_PRECONDITION_REQUIRED; - num = constants.HTTP_STATUS_TOO_MANY_REQUESTS; - num = constants.HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE; - num = constants.HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS; - num = constants.HTTP_STATUS_INTERNAL_SERVER_ERROR; - num = constants.HTTP_STATUS_NOT_IMPLEMENTED; - num = constants.HTTP_STATUS_BAD_GATEWAY; - num = constants.HTTP_STATUS_SERVICE_UNAVAILABLE; - num = constants.HTTP_STATUS_GATEWAY_TIMEOUT; - num = constants.HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED; - num = constants.HTTP_STATUS_VARIANT_ALSO_NEGOTIATES; - num = constants.HTTP_STATUS_INSUFFICIENT_STORAGE; - num = constants.HTTP_STATUS_LOOP_DETECTED; - num = constants.HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED; - num = constants.HTTP_STATUS_NOT_EXTENDED; - num = constants.HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED; - str = constants.HTTP2_HEADER_STATUS; - str = constants.HTTP2_HEADER_METHOD; - str = constants.HTTP2_HEADER_AUTHORITY; - str = constants.HTTP2_HEADER_SCHEME; - str = constants.HTTP2_HEADER_PATH; - str = constants.HTTP2_HEADER_ACCEPT_CHARSET; - str = constants.HTTP2_HEADER_ACCEPT_ENCODING; - str = constants.HTTP2_HEADER_ACCEPT_LANGUAGE; - str = constants.HTTP2_HEADER_ACCEPT_RANGES; - str = constants.HTTP2_HEADER_ACCEPT; - str = constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN; - str = constants.HTTP2_HEADER_AGE; - str = constants.HTTP2_HEADER_ALLOW; - str = constants.HTTP2_HEADER_AUTHORIZATION; - str = constants.HTTP2_HEADER_CACHE_CONTROL; - str = constants.HTTP2_HEADER_CONNECTION; - str = constants.HTTP2_HEADER_CONTENT_DISPOSITION; - str = constants.HTTP2_HEADER_CONTENT_ENCODING; - str = constants.HTTP2_HEADER_CONTENT_LANGUAGE; - str = constants.HTTP2_HEADER_CONTENT_LENGTH; - str = constants.HTTP2_HEADER_CONTENT_LOCATION; - str = constants.HTTP2_HEADER_CONTENT_MD5; - str = constants.HTTP2_HEADER_CONTENT_RANGE; - str = constants.HTTP2_HEADER_CONTENT_TYPE; - str = constants.HTTP2_HEADER_COOKIE; - str = constants.HTTP2_HEADER_DATE; - str = constants.HTTP2_HEADER_ETAG; - str = constants.HTTP2_HEADER_EXPECT; - str = constants.HTTP2_HEADER_EXPIRES; - str = constants.HTTP2_HEADER_FROM; - str = constants.HTTP2_HEADER_HOST; - str = constants.HTTP2_HEADER_IF_MATCH; - str = constants.HTTP2_HEADER_IF_MODIFIED_SINCE; - str = constants.HTTP2_HEADER_IF_NONE_MATCH; - str = constants.HTTP2_HEADER_IF_RANGE; - str = constants.HTTP2_HEADER_IF_UNMODIFIED_SINCE; - str = constants.HTTP2_HEADER_LAST_MODIFIED; - str = constants.HTTP2_HEADER_LINK; - str = constants.HTTP2_HEADER_LOCATION; - str = constants.HTTP2_HEADER_MAX_FORWARDS; - str = constants.HTTP2_HEADER_PREFER; - str = constants.HTTP2_HEADER_PROXY_AUTHENTICATE; - str = constants.HTTP2_HEADER_PROXY_AUTHORIZATION; - str = constants.HTTP2_HEADER_RANGE; - str = constants.HTTP2_HEADER_REFERER; - str = constants.HTTP2_HEADER_REFRESH; - str = constants.HTTP2_HEADER_RETRY_AFTER; - str = constants.HTTP2_HEADER_SERVER; - str = constants.HTTP2_HEADER_SET_COOKIE; - str = constants.HTTP2_HEADER_STRICT_TRANSPORT_SECURITY; - str = constants.HTTP2_HEADER_TRANSFER_ENCODING; - str = constants.HTTP2_HEADER_TE; - str = constants.HTTP2_HEADER_UPGRADE; - str = constants.HTTP2_HEADER_USER_AGENT; - str = constants.HTTP2_HEADER_VARY; - str = constants.HTTP2_HEADER_VIA; - str = constants.HTTP2_HEADER_WWW_AUTHENTICATE; - str = constants.HTTP2_HEADER_HTTP2_SETTINGS; - str = constants.HTTP2_HEADER_KEEP_ALIVE; - str = constants.HTTP2_HEADER_PROXY_CONNECTION; - str = constants.HTTP2_METHOD_ACL; - str = constants.HTTP2_METHOD_BASELINE_CONTROL; - str = constants.HTTP2_METHOD_BIND; - str = constants.HTTP2_METHOD_CHECKIN; - str = constants.HTTP2_METHOD_CHECKOUT; - str = constants.HTTP2_METHOD_CONNECT; - str = constants.HTTP2_METHOD_COPY; - str = constants.HTTP2_METHOD_DELETE; - str = constants.HTTP2_METHOD_GET; - str = constants.HTTP2_METHOD_HEAD; - str = constants.HTTP2_METHOD_LABEL; - str = constants.HTTP2_METHOD_LINK; - str = constants.HTTP2_METHOD_LOCK; - str = constants.HTTP2_METHOD_MERGE; - str = constants.HTTP2_METHOD_MKACTIVITY; - str = constants.HTTP2_METHOD_MKCALENDAR; - str = constants.HTTP2_METHOD_MKCOL; - str = constants.HTTP2_METHOD_MKREDIRECTREF; - str = constants.HTTP2_METHOD_MKWORKSPACE; - str = constants.HTTP2_METHOD_MOVE; - str = constants.HTTP2_METHOD_OPTIONS; - str = constants.HTTP2_METHOD_ORDERPATCH; - str = constants.HTTP2_METHOD_PATCH; - str = constants.HTTP2_METHOD_POST; - str = constants.HTTP2_METHOD_PRI; - str = constants.HTTP2_METHOD_PROPFIND; - str = constants.HTTP2_METHOD_PROPPATCH; - str = constants.HTTP2_METHOD_PUT; - str = constants.HTTP2_METHOD_REBIND; - str = constants.HTTP2_METHOD_REPORT; - str = constants.HTTP2_METHOD_SEARCH; - str = constants.HTTP2_METHOD_TRACE; - str = constants.HTTP2_METHOD_UNBIND; - str = constants.HTTP2_METHOD_UNCHECKOUT; - str = constants.HTTP2_METHOD_UNLINK; - str = constants.HTTP2_METHOD_UNLOCK; - str = constants.HTTP2_METHOD_UPDATE; - str = constants.HTTP2_METHOD_UPDATEREDIRECTREF; - str = constants.HTTP2_METHOD_VERSION_CONTROL; - } -} - -/////////////////////////////////////////////////////////// -/// Inspector Tests /// -/////////////////////////////////////////////////////////// - -{ - { - const b: inspector.Console.ConsoleMessage = {source: 'test', text: 'test', level: 'error' }; - inspector.open(); - inspector.open(0); - inspector.open(0, 'localhost'); - inspector.open(0, 'localhost', true); - inspector.close(); - const inspectorUrl: string | undefined = inspector.url(); - - const session = new inspector.Session(); - session.connect(); - session.disconnect(); - - // Unknown post method - session.post('A.b', { key: 'value' }, (err, params) => {}); - // TODO: parameters are implicitly 'any' and need type annotation - session.post('A.b', (err: Error | null, params?: {}) => {}); - session.post('A.b'); - // Known post method - const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; - session.post('Runtime.evaluate', parameter, - (err: Error, params: inspector.Runtime.EvaluateReturnType) => {}); - session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { - const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails; - const resultClassName: string = params.result.className; - }); - session.post('Runtime.evaluate'); - - // General event - session.on('inspectorNotification', message => { - message; // $ExpectType InspectorNotification<{}> - }); - // Known events - session.on('Debugger.paused', (message: inspector.InspectorNotification) => { - const method: string = message.method; - const pauseReason: string = message.params.reason; - }); - session.on('Debugger.resumed', () => {}); - // Node Inspector events - session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification) => { - const value: Array<{}> = message.params.value; - }); - } -} - -/////////////////////////////////////////////////////////// -/// Trace Events Tests /// -/////////////////////////////////////////////////////////// - -{ - const enabledCategories: string = trace_events.getEnabledCategories(); - const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] }); - const categories: string = tracing.categories; - const enabled: boolean = tracing.enabled; - tracing.enable(); - tracing.disable(); -} - -//////////////////////////////////////////////////// -/// module tests : http://nodejs.org/api/modules.html -//////////////////////////////////////////////////// -import moduleModule = require('module'); - -{ - require.extensions[".ts"] = () => ""; - - Module.runMain(); - const s: string = Module.wrap("some code"); - - const m1: Module = new Module("moduleId"); - const m2: Module = new Module.Module("moduleId"); - const b: string[] = Module.builtinModules; - let paths: string[] = module.paths; - paths = m1.paths; - - moduleModule.createRequireFromPath('./test')('test'); -} - -//////////////////////////////////////////////////// -/// Node.js ESNEXT Support -//////////////////////////////////////////////////// - -{ - const s = 'foo'; - const s1: string = s.trimLeft(); - const s2: string = s.trimRight(); - const s3: string = s.trimStart(); - const s4: string = s.trimEnd(); -} diff --git a/types/node/v10/ts3.1/tsconfig.json b/types/node/v10/ts3.1/tsconfig.json deleted file mode 100644 index de75d02481..0000000000 --- a/types/node/v10/ts3.1/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "files": [ - "index.d.ts", - "node-tests.ts" - ], - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": true, - "baseUrl": "../../../", - "typeRoots": [ - "../../../" - ], - "paths": { - "node": [ - "node/v10" - ] - }, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - } -} diff --git a/types/node/v10/ts3.1/tslint.json b/types/node/v10/ts3.1/tslint.json deleted file mode 100644 index 65e8b18d2a..0000000000 --- a/types/node/v10/ts3.1/tslint.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "no-bad-reference": false, - "no-empty-interface": false, - "no-single-declare-module": false, - "unified-signatures": false - } -} diff --git a/types/node/v10/ts3.1/util.d.ts b/types/node/v10/ts3.1/util.d.ts deleted file mode 100644 index 2cfdeb844a..0000000000 --- a/types/node/v10/ts3.1/util.d.ts +++ /dev/null @@ -1,171 +0,0 @@ -declare module "util" { - interface InspectOptions extends NodeJS.InspectOptions { } - function format(format: any, ...param: any[]): string; - function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; - /** @deprecated since v0.11.3 - use `console.error()` instead. */ - function debug(string: string): void; - /** @deprecated since v0.11.3 - use `console.error()` instead. */ - function error(...param: any[]): void; - /** @deprecated since v0.11.3 - use `console.log()` instead. */ - function puts(...param: any[]): void; - /** @deprecated since v0.11.3 - use `console.log()` instead. */ - function print(...param: any[]): void; - /** @deprecated since v0.11.3 - use a third party module instead. */ - function log(string: string): void; - function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - function inspect(object: any, options: InspectOptions): string; - namespace inspect { - let colors: { - [color: string]: [number, number] | undefined - }; - let styles: { - [style: string]: string | undefined - }; - let defaultOptions: InspectOptions; - } - /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ - function isArray(object: any): object is any[]; - /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ - function isRegExp(object: any): object is RegExp; - /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ - function isDate(object: any): object is Date; - /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ - function isError(object: any): object is Error; - function inherits(constructor: any, superConstructor: any): void; - function debuglog(key: string): (msg: string, ...param: any[]) => void; - /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ - function isBoolean(object: any): object is boolean; - /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ - function isBuffer(object: any): object is Buffer; - /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ - function isFunction(object: any): boolean; - /** @deprecated since v4.0.0 - use `value === null` instead. */ - function isNull(object: any): object is null; - /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ - function isNullOrUndefined(object: any): object is null | undefined; - /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ - function isNumber(object: any): object is number; - /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ - function isObject(object: any): boolean; - /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ - function isPrimitive(object: any): boolean; - /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ - function isString(object: any): object is string; - /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ - function isSymbol(object: any): object is symbol; - /** @deprecated since v4.0.0 - use `value === undefined` instead. */ - function isUndefined(object: any): object is undefined; - function deprecate(fn: T, message: string, code?: string): T; - function isDeepStrictEqual(val1: any, val2: any): boolean; - - interface CustomPromisify extends Function { - __promisify__: TCustom; - } - - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - - function promisify(fn: CustomPromisify): TCustom; - function promisify(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise; - function promisify(fn: (callback: (err?: Error | null) => void) => void): () => Promise; - function promisify(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, callback: (err?: Error | null) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error | null, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error | null, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error | null) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify(fn: Function): Function; - - namespace types { - function isAnyArrayBuffer(object: any): boolean; - function isArgumentsObject(object: any): object is IArguments; - function isArrayBuffer(object: any): object is ArrayBuffer; - function isArrayBufferView(object: any): object is ArrayBufferView; - function isAsyncFunction(object: any): boolean; - function isBooleanObject(object: any): object is Boolean; - function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); - function isDataView(object: any): object is DataView; - function isDate(object: any): object is Date; - function isExternal(object: any): boolean; - function isFloat32Array(object: any): object is Float32Array; - function isFloat64Array(object: any): object is Float64Array; - function isGeneratorFunction(object: any): boolean; - function isGeneratorObject(object: any): boolean; - function isInt8Array(object: any): object is Int8Array; - function isInt16Array(object: any): object is Int16Array; - function isInt32Array(object: any): object is Int32Array; - function isMap(object: any): boolean; - function isMapIterator(object: any): boolean; - function isModuleNamespaceObject(value: any): boolean; - function isNativeError(object: any): object is Error; - function isNumberObject(object: any): object is Number; - function isPromise(object: any): boolean; - function isProxy(object: any): boolean; - function isRegExp(object: any): object is RegExp; - function isSet(object: any): boolean; - function isSetIterator(object: any): boolean; - function isSharedArrayBuffer(object: any): boolean; - function isStringObject(object: any): boolean; - function isSymbolObject(object: any): boolean; - function isTypedArray(object: any): object is NodeJS.TypedArray; - function isUint8Array(object: any): object is Uint8Array; - function isUint8ClampedArray(object: any): object is Uint8ClampedArray; - function isUint16Array(object: any): object is Uint16Array; - function isUint32Array(object: any): object is Uint32Array; - function isWeakMap(object: any): boolean; - function isWeakSet(object: any): boolean; - function isWebAssemblyCompiledModule(object: any): boolean; - } - - class TextDecoder { - readonly encoding: string; - readonly fatal: boolean; - readonly ignoreBOM: boolean; - constructor( - encoding?: string, - options?: { fatal?: boolean; ignoreBOM?: boolean } - ); - decode( - input?: NodeJS.TypedArray | DataView | ArrayBuffer | null, - options?: { stream?: boolean } - ): string; - } - - class TextEncoder { - readonly encoding: string; - constructor(); - encode(input?: string): Uint8Array; - } -} diff --git a/types/node/v10/ts3.1/assert.d.ts b/types/node/v10/ts3.6/assert.d.ts similarity index 100% rename from types/node/v10/ts3.1/assert.d.ts rename to types/node/v10/ts3.6/assert.d.ts diff --git a/types/node/v10/ts3.6/base.d.ts b/types/node/v10/ts3.6/base.d.ts index 184fab0df6..78119001e3 100644 --- a/types/node/v10/ts3.6/base.d.ts +++ b/types/node/v10/ts3.6/base.d.ts @@ -12,10 +12,43 @@ /// /// -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -// tslint:disable-next-line:no-bad-reference -/// - -// TypeScript 3.2-specific augmentations: -/// +// base definitions for all NodeJS modules that are not specific to any version of TypeScript /// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/node/v10/ts3.6/index.d.ts b/types/node/v10/ts3.6/index.d.ts index f06f092555..bc0357f5a4 100644 --- a/types/node/v10/ts3.6/index.d.ts +++ b/types/node/v10/ts3.6/index.d.ts @@ -3,6 +3,4 @@ // Typically type modifications should be made in base.d.ts instead of here /// - -// tslint:disable-next-line:no-bad-reference -/// +/// diff --git a/types/node/v10/ts3.6/tslint.json b/types/node/v10/ts3.6/tslint.json index 56086bb86a..65e8b18d2a 100644 --- a/types/node/v10/ts3.6/tslint.json +++ b/types/node/v10/ts3.6/tslint.json @@ -1,6 +1,10 @@ { "extends": "dtslint/dt.json", "rules": { - "no-bad-reference": false + "ban-types": false, + "no-bad-reference": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "unified-signatures": false } } diff --git a/types/node/v10/util.d.ts b/types/node/v10/util.d.ts index 56a879e854..981c4d3950 100644 --- a/types/node/v10/util.d.ts +++ b/types/node/v10/util.d.ts @@ -1,15 +1,175 @@ -// tslint:disable-next-line:no-bad-reference -/// - declare module "util" { + interface InspectOptions extends NodeJS.InspectOptions { } + function format(format: any, ...param: any[]): string; + function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function debug(string: string): void; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function error(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function puts(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function print(...param: any[]): void; + /** @deprecated since v0.11.3 - use a third party module instead. */ + function log(string: string): void; + function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + function inspect(object: any, options: InspectOptions): string; namespace inspect { + let colors: { + [color: string]: [number, number] | undefined + }; const custom: unique symbol; + let styles: { + [style: string]: string | undefined + }; + let defaultOptions: InspectOptions; } - namespace promisify { - const custom: unique symbol; + /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ + function isArray(object: any): object is any[]; + /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ + function isRegExp(object: any): object is RegExp; + /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ + function isDate(object: any): object is Date; + /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ + function isError(object: any): object is Error; + function inherits(constructor: any, superConstructor: any): void; + function debuglog(key: string): (msg: string, ...param: any[]) => void; + /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ + function isBoolean(object: any): object is boolean; + /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ + function isBuffer(object: any): object is Buffer; + /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ + function isFunction(object: any): boolean; + /** @deprecated since v4.0.0 - use `value === null` instead. */ + function isNull(object: any): object is null; + /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ + function isNullOrUndefined(object: any): object is null | undefined; + /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ + function isNumber(object: any): object is number; + /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ + function isObject(object: any): boolean; + /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ + function isPrimitive(object: any): boolean; + /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ + function isString(object: any): object is string; + /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ + function isSymbol(object: any): object is symbol; + /** @deprecated since v4.0.0 - use `value === undefined` instead. */ + function isUndefined(object: any): object is undefined; + function deprecate(fn: T, message: string, code?: string): T; + function isDeepStrictEqual(val1: any, val2: any): boolean; + + interface CustomPromisify extends Function { + __promisify__: TCustom; } + + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + + function promisify(fn: CustomPromisify): TCustom; + function promisify(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise; + function promisify(fn: (callback: (err?: Error | null) => void) => void): () => Promise; + function promisify(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, callback: (err?: Error | null) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error | null) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify(fn: Function): Function; + namespace types { + const custom: unique symbol; + function isAnyArrayBuffer(object: any): boolean; + function isArgumentsObject(object: any): object is IArguments; + function isArrayBuffer(object: any): object is ArrayBuffer; + function isArrayBufferView(object: any): object is ArrayBufferView; + function isAsyncFunction(object: any): boolean; function isBigInt64Array(value: any): value is BigInt64Array; function isBigUint64Array(value: any): value is BigUint64Array; + function isBooleanObject(object: any): object is Boolean; + function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); + function isDataView(object: any): object is DataView; + function isDate(object: any): object is Date; + function isExternal(object: any): boolean; + function isFloat32Array(object: any): object is Float32Array; + function isFloat64Array(object: any): object is Float64Array; + function isGeneratorFunction(object: any): boolean; + function isGeneratorObject(object: any): boolean; + function isInt8Array(object: any): object is Int8Array; + function isInt16Array(object: any): object is Int16Array; + function isInt32Array(object: any): object is Int32Array; + function isMap(object: any): boolean; + function isMapIterator(object: any): boolean; + function isModuleNamespaceObject(value: any): boolean; + function isNativeError(object: any): object is Error; + function isNumberObject(object: any): object is Number; + function isPromise(object: any): boolean; + function isProxy(object: any): boolean; + function isRegExp(object: any): object is RegExp; + function isSet(object: any): boolean; + function isSetIterator(object: any): boolean; + function isSharedArrayBuffer(object: any): boolean; + function isStringObject(object: any): boolean; + function isSymbolObject(object: any): boolean; + function isTypedArray(object: any): object is NodeJS.TypedArray; + function isUint8Array(object: any): object is Uint8Array; + function isUint8ClampedArray(object: any): object is Uint8ClampedArray; + function isUint16Array(object: any): object is Uint16Array; + function isUint32Array(object: any): object is Uint32Array; + function isWeakMap(object: any): boolean; + function isWeakSet(object: any): boolean; + function isWebAssemblyCompiledModule(object: any): boolean; + } + + class TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { fatal?: boolean; ignoreBOM?: boolean } + ); + decode( + input?: NodeJS.TypedArray | DataView | ArrayBuffer | null, + options?: { stream?: boolean } + ): string; + } + + class TextEncoder { + readonly encoding: string; + constructor(); + encode(input?: string): Uint8Array; } } diff --git a/types/node/v11/globals.d.ts b/types/node/v11/globals.d.ts index 81078e31d1..8e6694a815 100644 --- a/types/node/v11/globals.d.ts +++ b/types/node/v11/globals.d.ts @@ -1,8 +1,1152 @@ -// tslint:disable-next-line:no-bad-reference -/// +// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build +interface Console { + Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * The console.markTimeline() method is the deprecated form of console.timeStamp(). + * + * @deprecated Use console.timeStamp() instead. + */ + markTimeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timeline() method is the deprecated form of console.time(). + * + * @deprecated Use console.time() instead. + */ + timeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timelineEnd() method is the deprecated form of console.timeEnd(). + * + * @deprecated Use console.timeEnd() instead. + */ + timelineEnd(label?: string): void; +} + +interface Error { + stack?: string; +} + +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + + stackTraceLimit: number; +} + +interface SymbolConstructor { + readonly observable: symbol; +} + +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; + + /** Returns a copy with leading whitespace removed. */ + trimStart(): string; + /** Returns a copy with trailing whitespace removed. */ + trimEnd(): string; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T): Promise; +} +declare function clearTimeout(timeoutId: NodeJS.Timeout): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare function clearInterval(intervalId: NodeJS.Timeout): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; +declare namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T): Promise; +} +declare function clearImmediate(immediateId: NodeJS.Immediate): void; + +/** + * @experimental + */ +declare function queueMicrotask(callback: () => void): void; + +// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. +interface NodeRequireFunction { + /* tslint:disable-next-line:callable-types */ + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve: RequireResolve; + cache: any; + /** + * @deprecated + */ + extensions: NodeExtensions; + main: NodeModule | undefined; +} + +interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; +} + +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[]; + /** + * @since 11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"; +interface Buffer extends Uint8Array { + constructor: typeof Buffer; + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: number[] }; + equals(otherBuffer: Uint8Array): boolean; + compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + subarray(begin: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number): number; + writeUIntBE(value: number, offset: number, byteLength: number): number; + writeIntLE(value: number, offset: number, byteLength: number): number; + writeIntBE(value: number, offset: number, byteLength: number): number; + readUIntLE(offset: number, byteLength: number): number; + readUIntBE(offset: number, byteLength: number): number; + readIntLE(offset: number, byteLength: number): number; + readIntBE(offset: number, byteLength: number): number; + readUInt8(offset: number): number; + readUInt16LE(offset: number): number; + readUInt16BE(offset: number): number; + readUInt32LE(offset: number): number; + readUInt32BE(offset: number): number; + readInt8(offset: number): number; + readInt16LE(offset: number): number; + readInt16BE(offset: number): number; + readInt32LE(offset: number): number; + readInt32BE(offset: number): number; + readFloatLE(offset: number): number; + readFloatBE(offset: number): number; + readDoubleLE(offset: number): number; + readDoubleBE(offset: number): number; + reverse(): this; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number): number; + writeUInt16LE(value: number, offset: number): number; + writeUInt16BE(value: number, offset: number): number; + writeUInt32LE(value: number, offset: number): number; + writeUInt32BE(value: number, offset: number): number; + writeInt8(value: number, offset: number): number; + writeInt16LE(value: number, offset: number): number; + writeInt16BE(value: number, offset: number): number; + writeInt32LE(value: number, offset: number): number; + writeInt32BE(value: number, offset: number): number; + writeFloatLE(value: number, offset: number): number; + writeFloatBE(value: number, offset: number): number; + writeDoubleLE(value: number, offset: number): number; + writeDoubleBE(value: number, offset: number): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + 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 const 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' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): Buffer; + prototype: 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 any TypedArray or a new ArrayBuffer() + */ + from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: number[]): Buffer; + from(data: Uint8Array): Buffer; + /** + * Creates a new buffer containing the coerced value of an object + * A `TypeError` will be thrown if {obj} has not mentioned methods or is not of other type appropriate for `Buffer.from()` variants. + * @param obj An object supporting `Symbol.toPrimitive` or `valueOf()`. + */ + from(obj: { valueOf(): string | object } | { [Symbol.toPrimitive](hint: 'string'): string }, byteOffset?: number, length?: number): 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'. + */ + from(str: string, encoding?: BufferEncoding): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): 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): encoding is BufferEncoding + /** + * 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 | NodeJS.TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): 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: Uint8Array[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Uint8Array, buf2: Uint8Array): 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?: BufferEncoding): 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; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + poolSize: number; +}; + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ declare namespace NodeJS { + interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean; + showHidden?: boolean; + /** + * @default 2 + */ + depth?: number | null; + colors?: boolean; + customInspect?: boolean; + showProxy?: boolean; + maxArrayLength?: number | null; + breakLength?: number; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default `true` + */ + compact?: boolean | number; + sorted?: boolean | ((a: string, b: string) => number); + } + + interface ConsoleConstructorOptions { + stdout: WritableStream; + stderr?: WritableStream; + ignoreErrors?: boolean; + colorMode?: boolean | 'auto'; + inspectOptions?: InspectOptions; + } + + interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + + interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + class EventEmitter { + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(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: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + eventNames(): Array; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Buffer | Uint8Array): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer | Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: string, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): void; + end(data: string | Uint8Array | Buffer, cb?: () => void): void; + end(str: string, encoding?: string, cb?: () => void): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface Events extends EventEmitter { } + + interface Domain extends Events { + run(fn: (...args: any[]) => T, ...args: any[]): T; + add(emitter: EventEmitter | Timer): void; + remove(emitter: EventEmitter | Timer): void; + bind(cb: T): T; + intercept(cb: T): T; + + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + } + + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + } + + interface CpuUsage { + user: number; + system: number; + } + + interface ProcessRelease { + name: string; + sourceUrl?: string; + headersUrl?: string; + libUrl?: string; + lts?: string; + } + + interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | 'cygwin'; + + type Signals = + "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | + "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | + "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type MultipleResolveType = 'resolve' | 'reject'; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = (signal: Signals) => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; + + interface Socket extends ReadWriteStream { + isTTY?: true; + } + + interface ProcessEnv { + [key: string]: string | undefined; + } + + interface WriteStream extends Socket { + readonly writableHighWaterMark: number; + readonly writableLength: number; + columns?: number; + rows?: number; + _write(chunk: any, encoding: string, callback: (err?: null | Error) => void): void; + _destroy(err: Error | null, callback: (err?: null | Error) => void): void; + _final(callback: (err?: null | Error) => void): void; + setDefaultEncoding(encoding: string): this; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + } + interface ReadStream extends Socket { + readonly readableFlowing: boolean | null; + readonly readableHighWaterMark: number; + readonly readableLength: number; + isRaw?: boolean; + setRawMode?(mode: boolean): void; + _read(size: number): void; + _destroy(err: Error | null, callback: (err?: null | Error) => void): void; + push(chunk: any, encoding?: string): boolean; + destroy(error?: Error): void; + } + interface HRTime { + (time?: [number, number]): [number, number]; bigint(): bigint; } + + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @defaul false + */ + reportOnSignal: boolean; + + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + + interface Process extends EventEmitter { + /** + * Can also be a tty.WriteStream, not typed due to limitation.s + */ + stdout: WriteStream; + /** + * Can also be a tty.WriteStream, not typed due to limitation.s + */ + stderr: WriteStream; + stdin: ReadStream; + openStdin(): Socket; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + debugPort: number; + emitWarning(warning: string | Error, name?: string, ctor?: Function): void; + env: ProcessEnv; + exit(code?: number): never; + exitCode?: number; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: Array): void; + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + hasUncaughtExceptionCaptureCallback(): boolean; + 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; + ppid: number; + title: string; + arch: string; + platform: Platform; + mainModule?: NodeModule; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * Can only be set if not in worker thread. + */ + umask(mask?: number): number; + uptime(): number; + hrtime: HRTime; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; + disconnect(): void; + connected: boolean; + + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] + * environment variable. + */ + allowedNodeEnvironmentFlags: ReadonlySet; + + /** + * Only available with `--experimental-report` + */ + report?: ProcessReport; + + /** + * EventEmitter + * 1. beforeExit + * 2. disconnect + * 3. exit + * 4. message + * 5. rejectionHandled + * 6. uncaughtException + * 7. unhandledRejection + * 8. warning + * 9. message + * 10. + * 11. newListener/removeListener inherited from EventEmitter + */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; + + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + } + + 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: Immediate) => void; + clearInterval: (intervalId: Timeout) => void; + clearTimeout: (timeoutId: Timeout) => 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[]) => Immediate; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + queueMicrotask: typeof queueMicrotask; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + interface Timer { + hasRef(): boolean; + ref(): this; + refresh(): this; + unref(): this; + } + + class Immediate { + hasRef(): boolean; + ref(): this; + refresh(): this; + unref(): this; + _onImmediate: Function; // to distinguish it from the Timeout class + } + + class Timeout implements Timer { + hasRef(): boolean; + ref(): this; + refresh(): this; + unref(): this; + } + + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequireFromPath(path: string): (path: string) => any; + static builtinModules: string[]; + + static Module: typeof Module; + + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: Module | null; + children: Module[]; + paths: string[]; + + constructor(id: string, parent?: Module); + } + + type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; + + // TODO: The value type here is a version of `unknown` with an acceptably lossy amount of accuracy. + // Now that TypeScript's DT support is 3.0+, we can look into replacing this with `unknown`. + type UnknownFacade = {} | null | undefined; + + /** @deprecated - Use `UnknownFacade` instead. It is a better classifier for the type */ + type PoorMansUnknown = UnknownFacade; } diff --git a/types/node/v11/package.json b/types/node/v11/package.json index d70cf2b291..b0c8bbe606 100644 --- a/types/node/v11/package.json +++ b/types/node/v11/package.json @@ -2,11 +2,6 @@ "private": true, "types": "index", "typesVersions": { - "<=3.1": { - "*": [ - "ts3.1/*" - ] - }, "<=3.6": { "*": [ "ts3.6/*" diff --git a/types/node/v11/ts3.1/base.d.ts b/types/node/v11/ts3.1/base.d.ts deleted file mode 100644 index cf77532198..0000000000 --- a/types/node/v11/ts3.1/base.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -// base definitions for all NodeJS modules that are not specific to any version of TypeScript -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// diff --git a/types/node/v11/ts3.1/globals.d.ts b/types/node/v11/ts3.1/globals.d.ts deleted file mode 100644 index 8241104c47..0000000000 --- a/types/node/v11/ts3.1/globals.d.ts +++ /dev/null @@ -1,1151 +0,0 @@ -// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build -interface Console { - Console: NodeJS.ConsoleConstructor; - /** - * A simple assertion test that verifies whether `value` is truthy. - * If it is not, an `AssertionError` is thrown. - * If provided, the error `message` is formatted using `util.format()` and used as the error message. - */ - assert(value: any, message?: string, ...optionalParams: any[]): void; - /** - * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. - * When `stdout` is not a TTY, this method does nothing. - */ - clear(): void; - /** - * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. - */ - count(label?: string): void; - /** - * Resets the internal counter specific to `label`. - */ - countReset(label?: string): void; - /** - * The `console.debug()` function is an alias for {@link console.log()}. - */ - debug(message?: any, ...optionalParams: any[]): void; - /** - * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. - * This function bypasses any custom `inspect()` function defined on `obj`. - */ - dir(obj: any, options?: NodeJS.InspectOptions): void; - /** - * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting - */ - dirxml(...data: any[]): void; - /** - * Prints to `stderr` with newline. - */ - error(message?: any, ...optionalParams: any[]): void; - /** - * Increases indentation of subsequent lines by two spaces. - * If one or more `label`s are provided, those are printed first without the additional indentation. - */ - group(...label: any[]): void; - /** - * The `console.groupCollapsed()` function is an alias for {@link console.group()}. - */ - groupCollapsed(...label: any[]): void; - /** - * Decreases indentation of subsequent lines by two spaces. - */ - groupEnd(): void; - /** - * The {@link console.info()} function is an alias for {@link console.log()}. - */ - info(message?: any, ...optionalParams: any[]): void; - /** - * Prints to `stdout` with newline. - */ - log(message?: any, ...optionalParams: any[]): void; - /** - * This method does not display anything unless used in the inspector. - * Prints to `stdout` the array `array` formatted as a table. - */ - table(tabularData: any, properties?: string[]): void; - /** - * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. - */ - time(label?: string): void; - /** - * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. - */ - timeEnd(label?: string): void; - /** - * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. - */ - timeLog(label?: string, ...data: any[]): void; - /** - * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. - */ - trace(message?: any, ...optionalParams: any[]): void; - /** - * The {@link console.warn()} function is an alias for {@link console.error()}. - */ - warn(message?: any, ...optionalParams: any[]): void; - - // --- Inspector mode only --- - /** - * This method does not display anything unless used in the inspector. - * The console.markTimeline() method is the deprecated form of console.timeStamp(). - * - * @deprecated Use console.timeStamp() instead. - */ - markTimeline(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Starts a JavaScript CPU profile with an optional label. - */ - profile(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. - */ - profileEnd(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Adds an event with the label `label` to the Timeline panel of the inspector. - */ - timeStamp(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * The console.timeline() method is the deprecated form of console.time(). - * - * @deprecated Use console.time() instead. - */ - timeline(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * The console.timelineEnd() method is the deprecated form of console.timeEnd(). - * - * @deprecated Use console.timeEnd() instead. - */ - timelineEnd(label?: string): void; -} - -interface Error { - stack?: string; -} - -// Declare "static" methods in Error -interface ErrorConstructor { - /** Create .stack property on a target object */ - captureStackTrace(targetObject: Object, constructorOpt?: Function): void; - - /** - * Optional override for formatting stack traces - * - * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces - */ - prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; - - stackTraceLimit: number; -} - -interface SymbolConstructor { - readonly observable: symbol; -} - -// Node.js ESNEXT support -interface String { - /** Removes whitespace from the left end of a string. */ - trimLeft(): string; - /** Removes whitespace from the right end of a string. */ - trimRight(): string; - - /** Returns a copy with leading whitespace removed. */ - trimStart(): string; - /** Returns a copy with trailing whitespace removed. */ - trimEnd(): string; -} - -/*-----------------------------------------------* - * * - * GLOBAL * - * * - ------------------------------------------------*/ -declare var process: NodeJS.Process; -declare var global: NodeJS.Global; -declare var console: Console; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare namespace setTimeout { - function __promisify__(ms: number): Promise; - function __promisify__(ms: number, value: T): Promise; -} -declare function clearTimeout(timeoutId: NodeJS.Timeout): void; -declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare function clearInterval(intervalId: NodeJS.Timeout): void; -declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; -declare namespace setImmediate { - function __promisify__(): Promise; - function __promisify__(value: T): Promise; -} -declare function clearImmediate(immediateId: NodeJS.Immediate): void; - -/** - * @experimental - */ -declare function queueMicrotask(callback: () => void): void; - -// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. -interface NodeRequireFunction { - /* tslint:disable-next-line:callable-types */ - (id: string): any; -} - -interface NodeRequire extends NodeRequireFunction { - resolve: RequireResolve; - cache: any; - /** - * @deprecated - */ - extensions: NodeExtensions; - main: NodeModule | undefined; -} - -interface RequireResolve { - (id: string, options?: { paths?: string[]; }): string; - paths(request: string): string[] | null; -} - -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[]; - /** - * @since 11.14.0 - * - * The directory name of the module. This is usually the same as the path.dirname() of the module.id. - */ - path: string; - paths: string[]; -} - -declare var module: NodeModule; - -// Same as module.exports -declare var exports: any; - -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"; -interface Buffer extends Uint8Array { - constructor: typeof Buffer; - write(string: string, encoding?: BufferEncoding): number; - write(string: string, offset: number, encoding?: BufferEncoding): number; - write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: number[] }; - equals(otherBuffer: Uint8Array): boolean; - compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - subarray(begin: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number): number; - writeUIntBE(value: number, offset: number, byteLength: number): number; - writeIntLE(value: number, offset: number, byteLength: number): number; - writeIntBE(value: number, offset: number, byteLength: number): number; - readUIntLE(offset: number, byteLength: number): number; - readUIntBE(offset: number, byteLength: number): number; - readIntLE(offset: number, byteLength: number): number; - readIntBE(offset: number, byteLength: number): number; - readUInt8(offset: number): number; - readUInt16LE(offset: number): number; - readUInt16BE(offset: number): number; - readUInt32LE(offset: number): number; - readUInt32BE(offset: number): number; - readInt8(offset: number): number; - readInt16LE(offset: number): number; - readInt16BE(offset: number): number; - readInt32LE(offset: number): number; - readInt32BE(offset: number): number; - readFloatLE(offset: number): number; - readFloatBE(offset: number): number; - readDoubleLE(offset: number): number; - readDoubleBE(offset: number): number; - reverse(): this; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number): number; - writeUInt16LE(value: number, offset: number): number; - writeUInt16BE(value: number, offset: number): number; - writeUInt32LE(value: number, offset: number): number; - writeUInt32BE(value: number, offset: number): number; - writeInt8(value: number, offset: number): number; - writeInt16LE(value: number, offset: number): number; - writeInt16BE(value: number, offset: number): number; - writeInt32LE(value: number, offset: number): number; - writeInt32BE(value: number, offset: number): number; - writeFloatLE(value: number, offset: number): number; - writeFloatBE(value: number, offset: number): number; - writeDoubleLE(value: number, offset: number): number; - writeDoubleBE(value: number, offset: number): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; - lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; - 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 const 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' - * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. - */ - new(str: string, encoding?: BufferEncoding): Buffer; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). - */ - new(size: number): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - new(array: Uint8Array): Buffer; - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}/{SharedArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. - */ - new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - new(array: any[]): Buffer; - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. - */ - new(buffer: Buffer): Buffer; - prototype: 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 any TypedArray or a new ArrayBuffer() - */ - from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param data data to create a new Buffer - */ - from(data: number[]): Buffer; - from(data: Uint8Array): Buffer; - /** - * Creates a new buffer containing the coerced value of an object - * A `TypeError` will be thrown if {obj} has not mentioned methods or is not of other type appropriate for `Buffer.from()` variants. - * @param obj An object supporting `Symbol.toPrimitive` or `valueOf()`. - */ - from(obj: { valueOf(): string | object } | { [Symbol.toPrimitive](hint: 'string'): string }, byteOffset?: number, length?: number): 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'. - */ - from(str: string, encoding?: BufferEncoding): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param values to create a new Buffer - */ - of(...items: number[]): 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): encoding is BufferEncoding - /** - * 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 | NodeJS.TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): 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: Uint8Array[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - compare(buf1: Uint8Array, buf2: Uint8Array): 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?: BufferEncoding): 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; - /** - * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. - */ - poolSize: number; -}; - -/*----------------------------------------------* -* * -* GLOBAL INTERFACES * -* * -*-----------------------------------------------*/ -declare namespace NodeJS { - interface InspectOptions { - /** - * If set to `true`, getters are going to be - * inspected as well. If set to `'get'` only getters without setter are going - * to be inspected. If set to `'set'` only getters having a corresponding - * setter are going to be inspected. This might cause side effects depending on - * the getter function. - * @default `false` - */ - getters?: 'get' | 'set' | boolean; - showHidden?: boolean; - /** - * @default 2 - */ - depth?: number | null; - colors?: boolean; - customInspect?: boolean; - showProxy?: boolean; - maxArrayLength?: number | null; - breakLength?: number; - /** - * Setting this to `false` causes each object key - * to be displayed on a new line. It will also add new lines to text that is - * longer than `breakLength`. If set to a number, the most `n` inner elements - * are united on a single line as long as all properties fit into - * `breakLength`. Short array elements are also grouped together. Note that no - * text will be reduced below 16 characters, no matter the `breakLength` size. - * For more information, see the example below. - * @default `true` - */ - compact?: boolean | number; - sorted?: boolean | ((a: string, b: string) => number); - } - - interface ConsoleConstructorOptions { - stdout: WritableStream; - stderr?: WritableStream; - ignoreErrors?: boolean; - colorMode?: boolean | 'auto'; - inspectOptions?: InspectOptions; - } - - interface ConsoleConstructor { - prototype: Console; - new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; - new(options: ConsoleConstructorOptions): Console; - } - - interface CallSite { - /** - * Value of "this" - */ - getThis(): any; - - /** - * Type of "this" as a string. - * This is the name of the function stored in the constructor field of - * "this", if available. Otherwise the object's [[Class]] internal - * property. - */ - getTypeName(): string | null; - - /** - * Current function - */ - getFunction(): Function | undefined; - - /** - * Name of the current function, typically its name property. - * If a name property is not available an attempt will be made to try - * to infer a name from the function's context. - */ - getFunctionName(): string | null; - - /** - * Name of the property [of "this" or one of its prototypes] that holds - * the current function - */ - getMethodName(): string | null; - - /** - * Name of the script [if this function was defined in a script] - */ - getFileName(): string | null; - - /** - * Current line number [if this function was defined in a script] - */ - getLineNumber(): number | null; - - /** - * Current column number [if this function was defined in a script] - */ - getColumnNumber(): number | null; - - /** - * A call site object representing the location where eval was called - * [if this function was created using a call to eval] - */ - getEvalOrigin(): string | undefined; - - /** - * Is this a toplevel invocation, that is, is "this" the global object? - */ - isToplevel(): boolean; - - /** - * Does this call take place in code defined by a call to eval? - */ - isEval(): boolean; - - /** - * Is this call in native V8 code? - */ - isNative(): boolean; - - /** - * Is this a constructor call? - */ - isConstructor(): boolean; - } - - interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } - - class EventEmitter { - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - rawListeners(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: (...args: any[]) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - eventNames(): Array; - } - - interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: WritableStream): this; - unshift(chunk: string | Buffer | Uint8Array): void; - wrap(oldStream: ReadableStream): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - interface WritableStream extends EventEmitter { - writable: boolean; - write(buffer: Buffer | Uint8Array | string, cb?: (err?: Error | null) => void): boolean; - write(str: string, encoding?: string, cb?: (err?: Error | null) => void): boolean; - end(cb?: () => void): void; - end(data: string | Uint8Array | Buffer, cb?: () => void): void; - end(str: string, encoding?: string, cb?: () => void): void; - } - - interface ReadWriteStream extends ReadableStream, WritableStream { } - - interface Events extends EventEmitter { } - - interface Domain extends Events { - run(fn: (...args: any[]) => T, ...args: any[]): T; - add(emitter: EventEmitter | Timer): void; - remove(emitter: EventEmitter | Timer): void; - bind(cb: T): T; - intercept(cb: T): T; - - addListener(event: string, listener: (...args: any[]) => void): this; - on(event: string, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - removeListener(event: string, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string): this; - } - - interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - external: number; - } - - interface CpuUsage { - user: number; - system: number; - } - - interface ProcessRelease { - name: string; - sourceUrl?: string; - headersUrl?: string; - libUrl?: string; - lts?: string; - } - - interface ProcessVersions { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } - - type Platform = 'aix' - | 'android' - | 'darwin' - | 'freebsd' - | 'linux' - | 'openbsd' - | 'sunos' - | 'win32' - | 'cygwin'; - - type Signals = - "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | - "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | - "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | - "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; - - type MultipleResolveType = 'resolve' | 'reject'; - - type BeforeExitListener = (code: number) => void; - type DisconnectListener = () => void; - type ExitListener = (code: number) => void; - type RejectionHandledListener = (promise: Promise) => void; - type UncaughtExceptionListener = (error: Error) => void; - type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; - type WarningListener = (warning: Error) => void; - type MessageListener = (message: any, sendHandle: any) => void; - type SignalsListener = (signal: Signals) => void; - type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; - - interface Socket extends ReadWriteStream { - isTTY?: true; - } - - interface ProcessEnv { - [key: string]: string | undefined; - } - - interface WriteStream extends Socket { - readonly writableHighWaterMark: number; - readonly writableLength: number; - columns?: number; - rows?: number; - _write(chunk: any, encoding: string, callback: (err?: null | Error) => void): void; - _destroy(err: Error | null, callback: (err?: null | Error) => void): void; - _final(callback: (err?: null | Error) => void): void; - setDefaultEncoding(encoding: string): this; - cork(): void; - uncork(): void; - destroy(error?: Error): void; - } - interface ReadStream extends Socket { - readonly readableFlowing: boolean | null; - readonly readableHighWaterMark: number; - readonly readableLength: number; - isRaw?: boolean; - setRawMode?(mode: boolean): void; - _read(size: number): void; - _destroy(err: Error | null, callback: (err?: null | Error) => void): void; - push(chunk: any, encoding?: string): boolean; - destroy(error?: Error): void; - } - - interface HRTime { - (time?: [number, number]): [number, number]; - } - - interface ProcessReport { - /** - * Directory where the report is written. - * working directory of the Node.js process. - * @default '' indicating that reports are written to the current - */ - directory: string; - - /** - * Filename where the report is written. - * The default value is the empty string. - * @default '' the output filename will be comprised of a timestamp, - * PID, and sequence number. - */ - filename: string; - - /** - * Returns a JSON-formatted diagnostic report for the running process. - * The report's JavaScript stack trace is taken from err, if present. - */ - getReport(err?: Error): string; - - /** - * If true, a diagnostic report is generated on fatal errors, - * such as out of memory errors or failed C++ assertions. - * @default false - */ - reportOnFatalError: boolean; - - /** - * If true, a diagnostic report is generated when the process - * receives the signal specified by process.report.signal. - * @defaul false - */ - reportOnSignal: boolean; - - /** - * If true, a diagnostic report is generated on uncaught exception. - * @default false - */ - reportOnUncaughtException: boolean; - - /** - * The signal used to trigger the creation of a diagnostic report. - * @default 'SIGUSR2' - */ - signal: Signals; - - /** - * Writes a diagnostic report to a file. If filename is not provided, the default filename - * includes the date, time, PID, and a sequence number. - * The report's JavaScript stack trace is taken from err, if present. - * - * @param fileName Name of the file where the report is written. - * This should be a relative path, that will be appended to the directory specified in - * `process.report.directory`, or the current working directory of the Node.js process, - * if unspecified. - * @param error A custom error used for reporting the JavaScript stack. - * @return Filename of the generated report. - */ - writeReport(fileName?: string): string; - writeReport(error?: Error): string; - writeReport(fileName?: string, err?: Error): string; - } - - interface Process extends EventEmitter { - /** - * Can also be a tty.WriteStream, not typed due to limitation.s - */ - stdout: WriteStream; - /** - * Can also be a tty.WriteStream, not typed due to limitation.s - */ - stderr: WriteStream; - stdin: ReadStream; - openStdin(): Socket; - argv: string[]; - argv0: string; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - debugPort: number; - emitWarning(warning: string | Error, name?: string, ctor?: Function): void; - env: ProcessEnv; - exit(code?: number): never; - exitCode?: number; - getgid(): number; - setgid(id: number | string): void; - getuid(): number; - setuid(id: number | string): void; - geteuid(): number; - seteuid(id: number | string): void; - getegid(): number; - setegid(id: number | string): void; - getgroups(): number[]; - setgroups(groups: Array): void; - setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; - hasUncaughtExceptionCaptureCallback(): boolean; - 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; - ppid: number; - title: string; - arch: string; - platform: Platform; - mainModule?: NodeModule; - memoryUsage(): MemoryUsage; - cpuUsage(previousValue?: CpuUsage): CpuUsage; - nextTick(callback: Function, ...args: any[]): void; - release: ProcessRelease; - features: { - inspector: boolean; - debug: boolean; - uv: boolean; - ipv6: boolean; - tls_alpn: boolean; - tls_sni: boolean; - tls_ocsp: boolean; - tls: boolean; - }; - /** - * Can only be set if not in worker thread. - */ - umask(mask?: number): number; - uptime(): number; - hrtime: HRTime; - domain: Domain; - - // Worker - send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; - disconnect(): void; - connected: boolean; - - /** - * The `process.allowedNodeEnvironmentFlags` property is a special, - * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] - * environment variable. - */ - allowedNodeEnvironmentFlags: ReadonlySet; - - /** - * Only available with `--experimental-report` - */ - report?: ProcessReport; - - /** - * EventEmitter - * 1. beforeExit - * 2. disconnect - * 3. exit - * 4. message - * 5. rejectionHandled - * 6. uncaughtException - * 7. unhandledRejection - * 8. warning - * 9. message - * 10. - * 11. newListener/removeListener inherited from EventEmitter - */ - addListener(event: "beforeExit", listener: BeforeExitListener): this; - addListener(event: "disconnect", listener: DisconnectListener): this; - addListener(event: "exit", listener: ExitListener): this; - addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - addListener(event: "warning", listener: WarningListener): this; - addListener(event: "message", listener: MessageListener): this; - addListener(event: Signals, listener: SignalsListener): this; - addListener(event: "newListener", listener: NewListenerListener): this; - addListener(event: "removeListener", listener: RemoveListenerListener): this; - addListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - emit(event: "beforeExit", code: number): boolean; - emit(event: "disconnect"): boolean; - emit(event: "exit", code: number): boolean; - emit(event: "rejectionHandled", promise: Promise): boolean; - emit(event: "uncaughtException", error: Error): boolean; - emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; - emit(event: "warning", warning: Error): boolean; - emit(event: "message", message: any, sendHandle: any): this; - emit(event: Signals, signal: Signals): boolean; - emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; - emit(event: "multipleResolves", listener: MultipleResolveListener): this; - - on(event: "beforeExit", listener: BeforeExitListener): this; - on(event: "disconnect", listener: DisconnectListener): this; - on(event: "exit", listener: ExitListener): this; - on(event: "rejectionHandled", listener: RejectionHandledListener): this; - on(event: "uncaughtException", listener: UncaughtExceptionListener): this; - on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - on(event: "warning", listener: WarningListener): this; - on(event: "message", listener: MessageListener): this; - on(event: Signals, listener: SignalsListener): this; - on(event: "newListener", listener: NewListenerListener): this; - on(event: "removeListener", listener: RemoveListenerListener): this; - on(event: "multipleResolves", listener: MultipleResolveListener): this; - - once(event: "beforeExit", listener: BeforeExitListener): this; - once(event: "disconnect", listener: DisconnectListener): this; - once(event: "exit", listener: ExitListener): this; - once(event: "rejectionHandled", listener: RejectionHandledListener): this; - once(event: "uncaughtException", listener: UncaughtExceptionListener): this; - once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - once(event: "warning", listener: WarningListener): this; - once(event: "message", listener: MessageListener): this; - once(event: Signals, listener: SignalsListener): this; - once(event: "newListener", listener: NewListenerListener): this; - once(event: "removeListener", listener: RemoveListenerListener): this; - once(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependListener(event: "beforeExit", listener: BeforeExitListener): this; - prependListener(event: "disconnect", listener: DisconnectListener): this; - prependListener(event: "exit", listener: ExitListener): this; - prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependListener(event: "warning", listener: WarningListener): this; - prependListener(event: "message", listener: MessageListener): this; - prependListener(event: Signals, listener: SignalsListener): this; - prependListener(event: "newListener", listener: NewListenerListener): this; - prependListener(event: "removeListener", listener: RemoveListenerListener): this; - prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; - prependOnceListener(event: "disconnect", listener: DisconnectListener): this; - prependOnceListener(event: "exit", listener: ExitListener): this; - prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependOnceListener(event: "warning", listener: WarningListener): this; - prependOnceListener(event: "message", listener: MessageListener): this; - prependOnceListener(event: Signals, listener: SignalsListener): this; - prependOnceListener(event: "newListener", listener: NewListenerListener): this; - prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; - prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - listeners(event: "beforeExit"): BeforeExitListener[]; - listeners(event: "disconnect"): DisconnectListener[]; - listeners(event: "exit"): ExitListener[]; - listeners(event: "rejectionHandled"): RejectionHandledListener[]; - listeners(event: "uncaughtException"): UncaughtExceptionListener[]; - listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; - listeners(event: "warning"): WarningListener[]; - listeners(event: "message"): MessageListener[]; - listeners(event: Signals): SignalsListener[]; - listeners(event: "newListener"): NewListenerListener[]; - listeners(event: "removeListener"): RemoveListenerListener[]; - listeners(event: "multipleResolves"): MultipleResolveListener[]; - } - - 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: Immediate) => void; - clearInterval: (intervalId: Timeout) => void; - clearTimeout: (timeoutId: Timeout) => 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[]) => Immediate; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - queueMicrotask: typeof queueMicrotask; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } - - interface Timer { - hasRef(): boolean; - ref(): this; - refresh(): this; - unref(): this; - } - - class Immediate { - hasRef(): boolean; - ref(): this; - refresh(): this; - unref(): this; - _onImmediate: Function; // to distinguish it from the Timeout class - } - - class Timeout implements Timer { - hasRef(): boolean; - ref(): this; - refresh(): this; - unref(): this; - } - - class Module { - static runMain(): void; - static wrap(code: string): string; - static createRequireFromPath(path: string): (path: string) => any; - static builtinModules: string[]; - - static Module: typeof Module; - - exports: any; - require: NodeRequireFunction; - id: string; - filename: string; - loaded: boolean; - parent: Module | null; - children: Module[]; - paths: string[]; - - constructor(id: string, parent?: Module); - } - - type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; - - // TODO: The value type here is a version of `unknown` with an acceptably lossy amount of accuracy. - // Now that TypeScript's DT support is 3.0+, we can look into replacing this with `unknown`. - type UnknownFacade = {} | null | undefined; - - /** @deprecated - Use `UnknownFacade` instead. It is a better classifier for the type */ - type PoorMansUnknown = UnknownFacade; -} diff --git a/types/node/v11/ts3.1/index.d.ts b/types/node/v11/ts3.1/index.d.ts deleted file mode 100644 index 6aed5176a1..0000000000 --- a/types/node/v11/ts3.1/index.d.ts +++ /dev/null @@ -1,61 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.2. - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 - -// NOTE: Augmentations for TypeScript 3.2 and later should use individual files for overrides -// within the respective ~/ts3.2 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.2, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -/// - -// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in +ts3.7 -/// - -// TypeScript 2.1-specific augmentations: - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files -// just to ensure the names are known and node typings can be used without importing these libs. -// if someone really needs these types the libs need to be added via --lib or in tsconfig.json -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } -interface Set {} -interface Map {} -interface ReadonlySet {} -interface IteratorResult { } -interface Iterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IterableIterator { } -interface AsyncIterableIterator {} -interface SymbolConstructor { - readonly iterator: symbol; - readonly asyncIterator: symbol; -} -declare var Symbol: SymbolConstructor; -// even this is just a forward declaration some properties are added otherwise -// it would be allowed to pass anything to e.g. Buffer.from() -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; -} - -declare module "util" { - namespace inspect { - const custom: symbol; - } - namespace promisify { - const custom: symbol; - } - namespace types { - function isBigInt64Array(value: any): boolean; - function isBigUint64Array(value: any): boolean; - } -} diff --git a/types/node/v11/ts3.1/node-tests.ts b/types/node/v11/ts3.1/node-tests.ts deleted file mode 100644 index 50d8320e89..0000000000 --- a/types/node/v11/ts3.1/node-tests.ts +++ /dev/null @@ -1,1206 +0,0 @@ -import assert = require("assert"); -import * as fs from "fs"; -import * as url from "url"; -import * as util from "util"; -import * as http from "http"; -import * as https from "https"; -import * as vm from "vm"; -import * as console2 from "console"; -import * as string_decoder from "string_decoder"; -import * as timers from "timers"; -import * as dns from "dns"; -import * as async_hooks from "async_hooks"; -import * as inspector from "inspector"; -import * as trace_events from "trace_events"; -import Module = require("module"); - -//////////////////////////////////////////////////// -/// File system tests : http://nodejs.org/api/fs.html -//////////////////////////////////////////////////// - -{ - { - fs.writeFile("thebible.txt", - "Do unto others as you would have them do unto you.", - assert.ifError); - - fs.write(1234, "test", () => { }); - - fs.writeFile("Harry Potter", - "\"You be wizzing, Harry,\" jived Dumbledore.", - { - encoding: "ascii" - }, - assert.ifError); - - fs.writeFile("testfile", "content", "utf8", assert.ifError); - - fs.writeFileSync("testfile", "content", "utf8"); - fs.writeFileSync("testfile", "content", { encoding: "utf8" }); - fs.writeFileSync("testfile", new DataView(new ArrayBuffer(1)), { encoding: "utf8" }); - } - - { - fs.appendFile("testfile", "foobar", "utf8", assert.ifError); - fs.appendFile("testfile", "foobar", { encoding: "utf8" }, assert.ifError); - fs.appendFileSync("testfile", "foobar", "utf8"); - fs.appendFileSync("testfile", "foobar", { encoding: "utf8" }); - } - - { - let content: string; - let buffer: Buffer; - let stringOrBuffer: string | Buffer; - const nullEncoding: string | null = null; - const stringEncoding: string | null = 'utf8'; - - content = fs.readFileSync('testfile', 'utf8'); - content = fs.readFileSync('testfile', { encoding: 'utf8' }); - stringOrBuffer = fs.readFileSync('testfile', stringEncoding); - stringOrBuffer = fs.readFileSync('testfile', { encoding: stringEncoding }); - - buffer = fs.readFileSync('testfile'); - buffer = fs.readFileSync('testfile', null); - buffer = fs.readFileSync('testfile', { encoding: null }); - stringOrBuffer = fs.readFileSync('testfile', nullEncoding); - stringOrBuffer = fs.readFileSync('testfile', { encoding: nullEncoding }); - - buffer = fs.readFileSync('testfile', { flag: 'r' }); - - fs.readFile('testfile', 'utf8', (err, data) => content = data); - fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); - fs.readFile('testfile', stringEncoding, (err, data) => stringOrBuffer = data); - fs.readFile('testfile', { encoding: stringEncoding }, (err, data) => stringOrBuffer = data); - - fs.readFile('testfile', (err, data) => buffer = data); - fs.readFile('testfile', null, (err, data) => buffer = data); - fs.readFile('testfile', { encoding: null }, (err, data) => buffer = data); - fs.readFile('testfile', nullEncoding, (err, data) => stringOrBuffer = data); - fs.readFile('testfile', { encoding: nullEncoding }, (err, data) => stringOrBuffer = data); - - fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); - } - - { - fs.read(1, new DataView(new ArrayBuffer(1)), 0, 1, 0, (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: DataView) => {}); - } - - { - fs.readSync(1, new DataView(new ArrayBuffer(1)), 0, 1, 0); - } - - { - let errno: number; - fs.readFile('testfile', (err, data) => { - if (err && err.errno) { - errno = err.errno; - } - }); - } - - { - let listS: string[]; - listS = fs.readdirSync('path'); - listS = fs.readdirSync('path', { encoding: 'utf8' }); - listS = fs.readdirSync('path', { encoding: null }); - listS = fs.readdirSync('path', { encoding: undefined }) as string[]; - listS = fs.readdirSync('path', 'utf8'); - listS = fs.readdirSync('path', null); - listS = fs.readdirSync('path', undefined); - const listDir: fs.Dirent[] = fs.readdirSync('path', { withFileTypes: true }); - const listDir2: Buffer[] = fs.readdirSync('path', { withFileTypes: false, encoding: 'buffer' }); - const listDir3: fs.Dirent[] = fs.readdirSync('path', { encoding: 'utf8', withFileTypes: true }); - - let listB: Buffer[]; - listB = fs.readdirSync('path', { encoding: 'buffer' }); - listB = fs.readdirSync("path", 'buffer'); - - const enc = 'buffer'; - fs.readdirSync('path', { encoding: enc }); - fs.readdirSync('path', { }); - - fs.readdir('path', { withFileTypes: true }, (err: NodeJS.ErrnoException | null, files: fs.Dirent[]) => {}); - } - - async function testPromisify() { - const rd = util.promisify(fs.readdir); - let listS: string[]; - listS = await rd('path'); - listS = await rd('path', 'utf8'); - listS = await rd('path', null); - listS = await rd('path', undefined); - listS = await rd('path', { encoding: 'utf8' }); - listS = await rd('path', { encoding: null }); - listS = await rd('path', { encoding: null, withFileTypes: false }); - listS = await rd('path', { encoding: 'utf8', withFileTypes: false }); - const listDir: fs.Dirent[] = await rd('path', { withFileTypes: true }); - const listDir2: Buffer[] = await rd('path', { withFileTypes: false, encoding: 'buffer' }); - const listDir3: fs.Dirent[] = await rd('path', { encoding: 'utf8', withFileTypes: true }); - } - - { - fs.mkdtemp('/tmp/foo-', (err, folder) => { - console.log(folder); - // Prints: /tmp/foo-itXde2 - }); - } - - { - let tempDir: string; - tempDir = fs.mkdtempSync('/tmp/foo-'); - } - - { - fs.watch('/tmp/foo-', (event, filename) => { - console.log(event, filename); - }); - - fs.watch('/tmp/foo-', 'utf8', (event, filename) => { - console.log(event, filename); - }); - - fs.watch('/tmp/foo-', { - recursive: true, - persistent: true, - encoding: 'utf8' - }, (event, filename) => { - console.log(event, filename); - }); - } - - { - fs.access('/path/to/folder', (err) => { }); - - fs.access(Buffer.from(''), (err) => { }); - - fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - - fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - - fs.accessSync('/path/to/folder'); - - fs.accessSync(Buffer.from('')); - - fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); - - fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); - } - - { - let s = '123'; - let b: Buffer; - fs.readlink('/path/to/folder', (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', undefined, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', 'utf8', (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', 'buffer', (err, linkString) => b = linkString); - fs.readlink('/path/to/folder', s, (err, linkString) => typeof linkString === 'string' ? s = linkString : b = linkString); - fs.readlink('/path/to/folder', {}, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', { encoding: undefined }, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', { encoding: 'utf8' }, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', { encoding: 'buffer' }, (err, linkString) => b = linkString); - fs.readlink('/path/to/folder', { encoding: s }, (err, linkString) => typeof linkString === "string" ? s = linkString : b = linkString); - - s = fs.readlinkSync('/path/to/folder'); - s = fs.readlinkSync('/path/to/folder', undefined); - s = fs.readlinkSync('/path/to/folder', 'utf8'); - b = fs.readlinkSync('/path/to/folder', 'buffer'); - const v1 = fs.readlinkSync('/path/to/folder', s); - typeof v1 === "string" ? s = v1 : b = v1; - - s = fs.readlinkSync('/path/to/folder', {}); - s = fs.readlinkSync('/path/to/folder', { encoding: undefined }); - s = fs.readlinkSync('/path/to/folder', { encoding: 'utf8' }); - b = fs.readlinkSync('/path/to/folder', { encoding: 'buffer' }); - const v2 = fs.readlinkSync('/path/to/folder', { encoding: s }); - typeof v2 === "string" ? s = v2 : b = v2; - } - - { - let s = '123'; - let b: Buffer; - fs.realpath('/path/to/folder', (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath); - fs.realpath('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath); - fs.realpath('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath); - fs.realpath('/path/to/folder', { encoding: s }, (err, resolvedPath) => typeof resolvedPath === "string" ? s = resolvedPath : b = resolvedPath); - - s = fs.realpathSync('/path/to/folder'); - s = fs.realpathSync('/path/to/folder', undefined); - s = fs.realpathSync('/path/to/folder', 'utf8'); - b = fs.realpathSync('/path/to/folder', 'buffer'); - const v1 = fs.realpathSync('/path/to/folder', s); - typeof v1 === "string" ? s = v1 : b = v1; - - s = fs.realpathSync('/path/to/folder', {}); - s = fs.realpathSync('/path/to/folder', { encoding: undefined }); - s = fs.realpathSync('/path/to/folder', { encoding: 'utf8' }); - b = fs.realpathSync('/path/to/folder', { encoding: 'buffer' }); - const v2 = fs.realpathSync('/path/to/folder', { encoding: s }); - typeof v2 === "string" ? s = v2 : b = v2; - - // native - fs.realpath.native('/path/to/folder', (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath); - fs.realpath.native('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath); - fs.realpath.native('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath); - fs.realpath.native('/path/to/folder', { encoding: s }, (err, resolvedPath) => typeof resolvedPath === "string" ? s = resolvedPath : b = resolvedPath); - - s = fs.realpathSync.native('/path/to/folder'); - s = fs.realpathSync.native('/path/to/folder', undefined); - s = fs.realpathSync.native('/path/to/folder', 'utf8'); - b = fs.realpathSync.native('/path/to/folder', 'buffer'); - const v3 = fs.realpathSync.native('/path/to/folder', s); - typeof v3 === "string" ? s = v3 : b = v3; - - s = fs.realpathSync.native('/path/to/folder', {}); - s = fs.realpathSync.native('/path/to/folder', { encoding: undefined }); - s = fs.realpathSync.native('/path/to/folder', { encoding: 'utf8' }); - b = fs.realpathSync.native('/path/to/folder', { encoding: 'buffer' }); - const v4 = fs.realpathSync.native('/path/to/folder', { encoding: s }); - typeof v4 === "string" ? s = v4 : b = v4; - } - - { - fs.copyFile('/path/to/src', '/path/to/dest', (err) => console.error(err)); - fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL, (err) => console.error(err)); - fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE, (err) => console.error(err)); - fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE_FORCE, (err) => console.error(err)); - - fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL); - fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE); - fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE_FORCE); - - const cf = util.promisify(fs.copyFile); - cf('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL).then(console.log); - } - - { - fs.mkdir('some/test/path', { - recursive: true, - mode: 0o777, - }, () => { - }); - - fs.mkdirSync('some/test/path', { - recursive: true, - mode: 0o777, - }); - } - - { - let names: Promise; - let buffers: Promise; - let namesOrBuffers: Promise; - let entries: Promise; - - names = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: false }); - buffers = fs.promises.readdir('/path/to/dir', { encoding: 'buffer', withFileTypes: false }); - namesOrBuffers = fs.promises.readdir('/path/to/dir', { encoding: 'SOME OTHER', withFileTypes: false }); - entries = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: true }); - } -} - -//////////////////////////////////////////////////// -/// Url tests : http://nodejs.org/api/url.html -//////////////////////////////////////////////////// - -{ - { - url.format(url.parse('http://www.example.com/xyz')); - - url.format('http://www.example.com/xyz'); - - // https://google.com/search?q=you're%20a%20lizard%2C%20gary - url.format({ - protocol: 'https', - host: "google.com", - pathname: 'search', - query: { q: "you're a lizard, gary" } - }); - - const myURL = new url.URL('https://a:b@你好你好?abc#foo'); - url.format(myURL, { fragment: false, unicode: true, auth: false }); - } - - { - const helloUrl = url.parse('http://example.com/?hello=world', true); - let helloQuery = helloUrl.query['hello']; - assert.equal(helloUrl.query['hello'], 'world'); - - let strUrl = url.parse('http://example.com/?hello=world'); - let queryStr: string = strUrl.query!; - - strUrl = url.parse('http://example.com/?hello=world', false); - queryStr = strUrl.query!; - - function getBoolean(): boolean { return false; } - const urlUrl = url.parse('http://example.com/?hello=world', getBoolean()); - if (typeof(urlUrl.query) === 'string') { - queryStr = urlUrl.query; - } else if (urlUrl.query) { - helloQuery = urlUrl.query['hello']; - } - } - - { - const ascii: string = url.domainToASCII('español.com'); - const unicode: string = url.domainToUnicode('xn--espaol-zwa.com'); - } - - { - let myURL = new url.URL('https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.hash, '#bar'); - assert.equal(myURL.host, 'example.org:81'); - assert.equal(myURL.hostname, 'example.org'); - assert.equal(myURL.href, 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.origin, 'https://example.org:81'); - assert.equal(myURL.password, 'thepwd'); - assert.equal(myURL.username, 'theuser'); - assert.equal(myURL.pathname, '/foo/path'); - assert.equal(myURL.port, "81"); - assert.equal(myURL.protocol, "https:"); - assert.equal(myURL.search, "?query=string"); - assert.equal(myURL.toString(), 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert(myURL.searchParams instanceof url.URLSearchParams); - - myURL.host = 'example.org:82'; - myURL.hostname = 'example.com'; - myURL.href = 'http://other.com'; - myURL.hash = 'baz'; - myURL.password = "otherpwd"; - myURL.username = "otheruser"; - myURL.pathname = "/otherPath"; - myURL.port = "82"; - myURL.protocol = "http"; - myURL.search = "a=b"; - assert.equal(myURL.href, 'http://otheruser:otherpwd@other.com:82/otherPath?a=b#baz'); - - myURL = new url.URL('/foo', 'https://example.org/'); - assert.equal(myURL.href, 'https://example.org/foo'); - assert.equal(myURL.toJSON(), myURL.href); - } - - { - const searchParams = new url.URLSearchParams('abc=123'); - - assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { - assert.equal(name, 'abc'); - assert.equal(value, '123'); - assert.equal(me, searchParams); - }); - - assert.equal(searchParams.get('abc'), '123'); - - searchParams.append('abc', 'xyz'); - - assert.deepEqual(searchParams.getAll('abc'), ['123', 'xyz']); - - const entries = searchParams.entries(); - assert.deepEqual(entries.next(), { value: ["abc", "123"], done: false }); - assert.deepEqual(entries.next(), { value: ["abc", "xyz"], done: false }); - assert.deepEqual(entries.next(), { value: undefined, done: true }); - - const keys = searchParams.keys(); - assert.deepEqual(keys.next(), { value: "abc", done: false }); - assert.deepEqual(keys.next(), { value: "abc", done: false }); - assert.deepEqual(keys.next(), { value: undefined, done: true }); - - const values = searchParams.values(); - assert.deepEqual(values.next(), { value: "123", done: false }); - assert.deepEqual(values.next(), { value: "xyz", done: false }); - assert.deepEqual(values.next(), { value: undefined, done: true }); - - searchParams.set('abc', 'b'); - assert.deepEqual(searchParams.getAll('abc'), ['b']); - - searchParams.delete('a'); - assert(!searchParams.has('a')); - assert.equal(searchParams.get('a'), null); - - searchParams.sort(); - } - - { - const searchParams = new url.URLSearchParams({ - user: 'abc', - query: ['first', 'second'] - }); - - assert.equal(searchParams.toString(), 'user=abc&query=first%2Csecond'); - assert.deepEqual(searchParams.getAll('query'), ['first,second']); - } - - { - // Using an array - const params = new url.URLSearchParams([ - ['user', 'abc'], - ['query', 'first'], - ['query', 'second'], - // ts 2.1/2.* compatibility - // tslint:disable-next-line no-unnecessary-type-assertion - ] as Array<[string, string]>); - assert.equal(params.toString(), 'user=abc&query=first&query=second'); - } - - { - let path: string = url.fileURLToPath('file://test'); - path = url.fileURLToPath(new url.URL('file://test')); - } - - { - const path: url.URL = url.pathToFileURL('file://test'); - } -} - -////////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html /// -////////////////////////////////////////////////////// - -{ - let agent: https.Agent = new https.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256, - maxCachedSessions: 100, - timeout: 15000 - }); - - agent = https.globalAgent; - - https.request({ - agent: false - }); - https.request({ - agent - }); - https.request({ - agent: undefined - }); - - https.get('http://www.example.com/xyz'); - https.request('http://www.example.com/xyz'); - - https.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - https.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - - https.get(new url.URL('http://www.example.com/xyz')); - https.request(new url.URL('http://www.example.com/xyz')); - - https.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - https.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - - const opts: https.RequestOptions = { - path: '/some/path' - }; - https.get(new url.URL('http://www.example.com'), opts); - https.request(new url.URL('http://www.example.com'), opts); - https.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - https.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - - https.globalAgent.options.ca = []; - - { - function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} - - class MyIncomingMessage extends http.IncomingMessage { - foo: number; - } - - class MyServerResponse extends http.ServerResponse { - foo: string; - } - - let server: https.Server; - - server = new https.Server(); - server = new https.Server(reqListener); - server = new https.Server({ IncomingMessage: MyIncomingMessage}); - - server = new https.Server({ - IncomingMessage: MyIncomingMessage, - ServerResponse: MyServerResponse - }, reqListener); - - server = https.createServer(); - server = https.createServer(reqListener); - server = https.createServer({ IncomingMessage: MyIncomingMessage }); - server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); - - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - const maxHeadersCount: number | null = server.maxHeadersCount; - const headersTimeout: number = server.headersTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } -} - -//////////////////////////////////////////////////// -/// string_decoder tests : https://nodejs.org/api/string_decoder.html -//////////////////////////////////////////////////// - -{ - const StringDecoder = string_decoder.StringDecoder; - const buffer = new Buffer('test'); - const decoder1 = new StringDecoder(); - const decoder2 = new StringDecoder('utf8'); - const part1: string = decoder1.write(new Buffer('test')); - const end1: string = decoder1.end(); - const part2: string = decoder2.write(new Buffer('test')); - const end2: string = decoder1.end(new Buffer('test')); -} - -//////////////////////////////////////////////////// -/// vm tests : https://nodejs.org/api/vm.html -//////////////////////////////////////////////////// - -{ - { - const sandbox = { - animal: 'cat', - count: 2 - }; - - const context = vm.createContext(sandbox); - console.log(vm.isContext(context)); - const script = new vm.Script('count += 1; name = "kitty"'); - - for (let i = 0; i < 10; ++i) { - script.runInContext(context); - } - - console.log(util.inspect(sandbox)); - - vm.runInNewContext('count += 1; name = "kitty"', sandbox); - console.log(util.inspect(sandbox)); - } - - { - const sandboxes = [{}, {}, {}]; - - const script = new vm.Script('globalVar = "set"'); - - sandboxes.forEach((sandbox) => { - script.runInNewContext(sandbox); - script.runInThisContext(); - }); - - console.log(util.inspect(sandboxes)); - - const localVar = 'initial value'; - vm.runInThisContext('localVar = "vm";'); - - console.log(localVar); - } - - { - vm.runInThisContext('console.log("hello world"', './my-file.js'); - } - - { - const fn: Function = vm.compileFunction('console.log("test")', [], { - parsingContext: vm.createContext(), - contextExtensions: [{ - a: 1, - }], - produceCachedData: false, - cachedData: Buffer.from('nope'), - }); - } -} - -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - -{ - { - const immediate = timers - .setImmediate(() => { - console.log('immediate'); - }) - .unref() - .ref(); - const b: boolean = immediate.hasRef(); - timers.clearImmediate(immediate); - } - { - const timeout = timers - .setInterval(() => { - console.log('interval'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearInterval(timeout); - } - { - const timeout = timers - .setTimeout(() => { - console.log('timeout'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearTimeout(timeout); - } - async function testPromisify() { - const setTimeout = util.promisify(timers.setTimeout); - let v: void = await setTimeout(100); // tslint:disable-line no-void-expression void-return - let s: string = await setTimeout(100, ""); - - const setImmediate = util.promisify(timers.setImmediate); - v = await setImmediate(); // tslint:disable-line no-void-expression - s = await setImmediate(""); - } -} - -///////////////////////////////////////////////////////// -/// Errors Tests : https://nodejs.org/api/errors.html /// -///////////////////////////////////////////////////////// - -{ - { - Error.stackTraceLimit = Infinity; - } - { - const myObject = {}; - Error.captureStackTrace(myObject); - } - { - const frames: NodeJS.CallSite[] = []; - Error.prepareStackTrace!(new Error(), frames); - } - { - const frame: NodeJS.CallSite = null!; - const frameThis: any = frame.getThis(); - const typeName: string | null = frame.getTypeName(); - const func: Function | undefined = frame.getFunction(); - const funcName: string | null = frame.getFunctionName(); - const meth: string | null = frame.getMethodName(); - const fname: string | null = frame.getFileName(); - const lineno: number | null = frame.getLineNumber(); - const colno: number | null = frame.getColumnNumber(); - const evalOrigin: string | undefined = frame.getEvalOrigin(); - const isTop: boolean = frame.isToplevel(); - const isEval: boolean = frame.isEval(); - const isNative: boolean = frame.isNative(); - const isConstr: boolean = frame.isConstructor(); - } -} - -/////////////////////////////////////////////////////////// -/// Console Tests : https://nodejs.org/api/console.html /// -/////////////////////////////////////////////////////////// - -{ - { - let _c: Console = console; - _c = console2; - } - { - const writeStream = fs.createWriteStream('./index.d.ts'); - let consoleInstance: Console = new console.Console(writeStream); - - consoleInstance = new console.Console(writeStream, writeStream); - consoleInstance = new console.Console(writeStream, writeStream, true); - consoleInstance = new console.Console({ - stdout: writeStream, - stderr: writeStream, - colorMode: 'auto', - ignoreErrors: true - }); - consoleInstance = new console.Console({ - stdout: writeStream, - colorMode: false - }); - consoleInstance = new console.Console({ - stdout: writeStream - }); - } - { - console.assert('value'); - console.assert('value', 'message'); - console.assert('value', 'message', 'foo', 'bar'); - console.clear(); - console.count(); - console.count('label'); - console.countReset(); - console.countReset('label'); - console.debug(); - console.debug('message'); - console.debug('message', 'foo', 'bar'); - console.dir('obj'); - console.dir('obj', { depth: 1 }); - console.error(); - console.error('message'); - console.error('message', 'foo', 'bar'); - console.group(); - console.group('label'); - console.group('label1', 'label2'); - console.groupCollapsed(); - console.groupEnd(); - console.info(); - console.info('message'); - console.info('message', 'foo', 'bar'); - console.log(); - console.log('message'); - console.log('message', 'foo', 'bar'); - console.table({ foo: 'bar' }); - console.table([{ foo: 'bar' }]); - console.table([{ foo: 'bar' }], ['foo']); - console.time(); - console.time('label'); - console.timeEnd(); - console.timeEnd('label'); - console.timeLog(); - console.timeLog('label'); - console.timeLog('label', 'foo', 'bar'); - console.trace(); - console.trace('message'); - console.trace('message', 'foo', 'bar'); - console.warn(); - console.warn('message'); - console.warn('message', 'foo', 'bar'); - - // --- Inspector mode only --- - console.markTimeline(); - console.markTimeline('label'); - console.profile(); - console.profile('label'); - console.profileEnd(); - console.profileEnd('label'); - console.timeStamp(); - console.timeStamp('label'); - console.timeline(); - console.timeline('label'); - console.timelineEnd(); - console.timelineEnd('label'); - } -} - -/////////////////////////////////////////////////// -/// DNS Tests : https://nodejs.org/api/dns.html /// -/////////////////////////////////////////////////// - -{ - dns.lookup("nodejs.org", (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 4, (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 6, (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", {}, (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup( - "nodejs.org", - { - family: 4, - hints: dns.ADDRCONFIG | dns.V4MAPPED, - all: false - }, - (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - } - ); - dns.lookup("nodejs.org", { all: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: dns.LookupAddress[] = addresses; - }); - dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: dns.LookupAddress[] = addresses; - }); - - function trueOrFalse(): boolean { - return Math.random() > 0.5 ? true : false; - } - dns.lookup("nodejs.org", { all: trueOrFalse() }, (err, addresses, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _addresses: string | dns.LookupAddress[] = addresses; - const _family: number | undefined = family; - }); - - dns.lookupService("127.0.0.1", 0, (err, hostname, service) => { - const _err: NodeJS.ErrnoException | null = err; - const _hostname: string = hostname; - const _service: string = service; - }); - - dns.resolve("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "A", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "AAAA", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "ANY", (err, addresses) => { - const _addresses: dns.AnyRecord[] = addresses; - }); - dns.resolve("nodejs.org", "MX", (err, addresses) => { - const _addresses: dns.MxRecord[] = addresses; - }); - - dns.resolve4("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve4("nodejs.org", { ttl: true }, (err, addresses) => { - const _addresses: dns.RecordWithTtl[] = addresses; - }); - { - const ttl = false; - dns.resolve4("nodejs.org", { ttl }, (err, addresses) => { - const _addresses: string[] | dns.RecordWithTtl[] = addresses; - }); - } - - dns.resolve6("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve6("nodejs.org", { ttl: true }, (err, addresses) => { - const _addresses: dns.RecordWithTtl[] = addresses; - }); - { - const ttl = false; - dns.resolve6("nodejs.org", { ttl }, (err, addresses) => { - const _addresses: string[] | dns.RecordWithTtl[] = addresses; - }); - } - { - const resolver = new dns.Resolver(); - resolver.setServers(["4.4.4.4"]); - resolver.resolve("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - resolver.cancel(); - } -} - -/***************************************************************************** - * * - * The following tests are the modules not mentioned in document but existed * - * * - *****************************************************************************/ - -/////////////////////////////////////////////////////////// -/// Constants Tests /// -/////////////////////////////////////////////////////////// - -import * as constants from 'constants'; -{ - let str: string; - let num: number; - num = constants.SIGHUP; - num = constants.SIGINT; - num = constants.SIGQUIT; - num = constants.SIGILL; - num = constants.SIGTRAP; - num = constants.SIGABRT; - num = constants.SIGIOT; - num = constants.SIGBUS; - num = constants.SIGFPE; - num = constants.SIGKILL; - num = constants.SIGUSR1; - num = constants.SIGSEGV; - num = constants.SIGUSR2; - num = constants.SIGPIPE; - num = constants.SIGALRM; - num = constants.SIGTERM; - num = constants.SIGCHLD; - num = constants.SIGSTKFLT; - num = constants.SIGCONT; - num = constants.SIGSTOP; - num = constants.SIGTSTP; - num = constants.SIGTTIN; - num = constants.SIGTTOU; - num = constants.SIGURG; - num = constants.SIGXCPU; - num = constants.SIGXFSZ; - num = constants.SIGVTALRM; - num = constants.SIGPROF; - num = constants.SIGWINCH; - num = constants.SIGIO; - num = constants.SIGPOLL; - num = constants.SIGPWR; - num = constants.SIGSYS; - num = constants.SIGUNUSED; - num = constants.O_RDONLY; - num = constants.O_WRONLY; - num = constants.O_RDWR; - num = constants.S_IFMT; - num = constants.S_IFREG; - num = constants.S_IFDIR; - num = constants.S_IFCHR; - num = constants.S_IFBLK; - num = constants.S_IFIFO; - num = constants.S_IFLNK; - num = constants.S_IFSOCK; - num = constants.O_CREAT; - num = constants.O_EXCL; - num = constants.O_NOCTTY; - num = constants.O_TRUNC; - num = constants.O_APPEND; - num = constants.O_DIRECTORY; - num = constants.O_NOATIME; - num = constants.O_NOFOLLOW; - num = constants.O_SYNC; - num = constants.O_DSYNC; - num = constants.O_DIRECT; - num = constants.O_NONBLOCK; - num = constants.S_IRWXU; - num = constants.S_IRUSR; - num = constants.S_IWUSR; - num = constants.S_IXUSR; - num = constants.S_IRWXG; - num = constants.S_IRGRP; - num = constants.S_IWGRP; - num = constants.S_IXGRP; - num = constants.S_IRWXO; - num = constants.S_IROTH; - num = constants.S_IWOTH; - num = constants.S_IXOTH; - num = constants.F_OK; - num = constants.R_OK; - num = constants.W_OK; - num = constants.X_OK; - num = constants.SSL_OP_ALL; - num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION; - num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE; - num = constants.SSL_OP_CISCO_ANYCONNECT; - num = constants.SSL_OP_COOKIE_EXCHANGE; - num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG; - num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; - num = constants.SSL_OP_EPHEMERAL_RSA; - num = constants.SSL_OP_LEGACY_SERVER_CONNECT; - num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER; - num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG; - num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING; - num = constants.SSL_OP_NETSCAPE_CA_DN_BUG; - num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG; - num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG; - num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; - num = constants.SSL_OP_NO_COMPRESSION; - num = constants.SSL_OP_NO_QUERY_MTU; - num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION; - num = constants.SSL_OP_NO_SSLv2; - num = constants.SSL_OP_NO_SSLv3; - num = constants.SSL_OP_NO_TICKET; - num = constants.SSL_OP_NO_TLSv1; - num = constants.SSL_OP_NO_TLSv1_1; - num = constants.SSL_OP_NO_TLSv1_2; - num = constants.SSL_OP_PKCS1_CHECK_1; - num = constants.SSL_OP_PKCS1_CHECK_2; - num = constants.SSL_OP_SINGLE_DH_USE; - num = constants.SSL_OP_SINGLE_ECDH_USE; - num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG; - num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG; - num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG; - num = constants.SSL_OP_TLS_D5_BUG; - num = constants.SSL_OP_TLS_ROLLBACK_BUG; - num = constants.ENGINE_METHOD_RSA; - num = constants.ENGINE_METHOD_DSA; - num = constants.ENGINE_METHOD_DH; - num = constants.ENGINE_METHOD_RAND; - num = constants.ENGINE_METHOD_ECDH; - num = constants.ENGINE_METHOD_ECDSA; - num = constants.ENGINE_METHOD_CIPHERS; - num = constants.ENGINE_METHOD_DIGESTS; - num = constants.ENGINE_METHOD_STORE; - num = constants.ENGINE_METHOD_PKEY_METHS; - num = constants.ENGINE_METHOD_PKEY_ASN1_METHS; - num = constants.ENGINE_METHOD_ALL; - num = constants.ENGINE_METHOD_NONE; - num = constants.DH_CHECK_P_NOT_SAFE_PRIME; - num = constants.DH_CHECK_P_NOT_PRIME; - num = constants.DH_UNABLE_TO_CHECK_GENERATOR; - num = constants.DH_NOT_SUITABLE_GENERATOR; - num = constants.NPN_ENABLED; - num = constants.ALPN_ENABLED; - num = constants.RSA_PKCS1_PADDING; - num = constants.RSA_SSLV23_PADDING; - num = constants.RSA_NO_PADDING; - num = constants.RSA_PKCS1_OAEP_PADDING; - num = constants.RSA_X931_PADDING; - num = constants.RSA_PKCS1_PSS_PADDING; - num = constants.POINT_CONVERSION_COMPRESSED; - num = constants.POINT_CONVERSION_UNCOMPRESSED; - num = constants.POINT_CONVERSION_HYBRID; - str = constants.defaultCoreCipherList; - str = constants.defaultCipherList; -} - -//////////////////////////////////////////////////// -/// AsyncHooks tests : https://nodejs.org/api/async_hooks.html -//////////////////////////////////////////////////// -{ - const hooks: async_hooks.HookCallbacks = { - init() {}, - before() {}, - after() {}, - destroy() {}, - promiseResolve() {}, - }; - - const asyncHook = async_hooks.createHook(hooks); - - asyncHook.enable().disable().enable(); - - const tId: number = async_hooks.triggerAsyncId(); - const eId: number = async_hooks.executionAsyncId(); - - class TestResource extends async_hooks.AsyncResource { - constructor() { - super('TEST_RESOURCE'); - } - } - - class AnotherTestResource extends async_hooks.AsyncResource { - constructor() { - super('TEST_RESOURCE', 42); - const aId: number = this.asyncId(); - const tId: number = this.triggerAsyncId(); - } - run() { - this.runInAsyncScope(() => {}); - this.runInAsyncScope(Array.prototype.find, [], () => true); - } - destroy() { - this.emitDestroy(); - } - } - - // check AsyncResource constructor options. - new async_hooks.AsyncResource(''); - new async_hooks.AsyncResource('', 0); - new async_hooks.AsyncResource('', {}); - new async_hooks.AsyncResource('', { triggerAsyncId: 0 }); - new async_hooks.AsyncResource('', { - triggerAsyncId: 0, - requireManualDestroy: true - }); -} - -/////////////////////////////////////////////////////////// -/// Inspector Tests /// -/////////////////////////////////////////////////////////// - -{ - { - const b: inspector.Console.ConsoleMessage = {source: 'test', text: 'test', level: 'error' }; - inspector.open(); - inspector.open(0); - inspector.open(0, 'localhost'); - inspector.open(0, 'localhost', true); - inspector.close(); - const inspectorUrl: string | undefined = inspector.url(); - - const session = new inspector.Session(); - session.connect(); - session.disconnect(); - - // Unknown post method - session.post('A.b', { key: 'value' }, (err, params) => {}); - // TODO: parameters are implicitly 'any' and need type annotation - session.post('A.b', (err: Error | null, params?: {}) => {}); - session.post('A.b'); - // Known post method - const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; - session.post('Runtime.evaluate', parameter, - (err: Error | null, params: inspector.Runtime.EvaluateReturnType) => {}); - session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { - const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails!; - const resultClassName: string = params.result.className!; - }); - session.post('Runtime.evaluate'); - - // General event - session.on('inspectorNotification', message => { - message; // $ExpectType InspectorNotification<{}> - }); - // Known events - session.on('Debugger.paused', (message: inspector.InspectorNotification) => { - const method: string = message.method; - const pauseReason: string = message.params.reason; - }); - session.on('Debugger.resumed', () => {}); - // Node Inspector events - session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification) => { - const value: Array<{}> = message.params.value; - }); - } -} - -/////////////////////////////////////////////////////////// -/// Trace Events Tests /// -/////////////////////////////////////////////////////////// - -{ - const enabledCategories: string = trace_events.getEnabledCategories(); - const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] }); - const categories: string = tracing.categories; - const enabled: boolean = tracing.enabled; - tracing.enable(); - tracing.disable(); -} - -//////////////////////////////////////////////////// -/// module tests : http://nodejs.org/api/modules.html -//////////////////////////////////////////////////// -import moduleModule = require('module'); - -{ - require.extensions[".ts"] = () => ""; - - Module.runMain(); - const s: string = Module.wrap("some code"); - - const m1: Module = new Module("moduleId"); - const m2: Module = new Module.Module("moduleId"); - const b: string[] = Module.builtinModules; - let paths: string[] = module.paths; - paths = m1.paths; - - moduleModule.createRequireFromPath('./test')('test'); -} - -//////////////////////////////////////////////////// -/// Node.js ESNEXT Support -//////////////////////////////////////////////////// - -{ - const s = 'foo'; - const s1: string = s.trimLeft(); - const s2: string = s.trimRight(); - const s3: string = s.trimStart(); - const s4: string = s.trimEnd(); -} diff --git a/types/node/v11/ts3.1/tsconfig.json b/types/node/v11/ts3.1/tsconfig.json deleted file mode 100644 index 8c8169c04a..0000000000 --- a/types/node/v11/ts3.1/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "files": [ - "index.d.ts", - "node-tests.ts" - ], - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../../../", - "typeRoots": [ - "../../../" - ], - "paths": { - "node": [ - "node/v11" - ] - }, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - } -} diff --git a/types/node/v11/ts3.1/tslint.json b/types/node/v11/ts3.1/tslint.json deleted file mode 100644 index 65e8b18d2a..0000000000 --- a/types/node/v11/ts3.1/tslint.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "no-bad-reference": false, - "no-empty-interface": false, - "no-single-declare-module": false, - "unified-signatures": false - } -} diff --git a/types/node/v11/ts3.1/util.d.ts b/types/node/v11/ts3.1/util.d.ts deleted file mode 100644 index b4a99ff52a..0000000000 --- a/types/node/v11/ts3.1/util.d.ts +++ /dev/null @@ -1,174 +0,0 @@ -declare module "util" { - interface InspectOptions extends NodeJS.InspectOptions { } - function format(format: any, ...param: any[]): string; - function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; - /** @deprecated since v0.11.3 - use `console.error()` instead. */ - function debug(string: string): void; - /** @deprecated since v0.11.3 - use `console.error()` instead. */ - function error(...param: any[]): void; - /** @deprecated since v0.11.3 - use `console.log()` instead. */ - function puts(...param: any[]): void; - /** @deprecated since v0.11.3 - use `console.log()` instead. */ - function print(...param: any[]): void; - /** @deprecated since v0.11.3 - use a third party module instead. */ - function log(string: string): void; - function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - function inspect(object: any, options: InspectOptions): string; - namespace inspect { - let colors: { - [color: string]: [number, number] | undefined - }; - let styles: { - [style: string]: string | undefined - }; - let defaultOptions: InspectOptions; - /** - * Allows changing inspect settings from the repl. - */ - let replDefaults: InspectOptions; - } - /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ - function isArray(object: any): object is any[]; - /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ - function isRegExp(object: any): object is RegExp; - /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ - function isDate(object: any): object is Date; - /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ - function isError(object: any): object is Error; - function inherits(constructor: any, superConstructor: any): void; - function debuglog(key: string): (msg: string, ...param: any[]) => void; - /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ - function isBoolean(object: any): object is boolean; - /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ - function isBuffer(object: any): object is Buffer; - /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ - function isFunction(object: any): boolean; - /** @deprecated since v4.0.0 - use `value === null` instead. */ - function isNull(object: any): object is null; - /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ - function isNullOrUndefined(object: any): object is null | undefined; - /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ - function isNumber(object: any): object is number; - /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ - function isObject(object: any): boolean; - /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ - function isPrimitive(object: any): boolean; - /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ - function isString(object: any): object is string; - /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ - function isSymbol(object: any): object is symbol; - /** @deprecated since v4.0.0 - use `value === undefined` instead. */ - function isUndefined(object: any): object is undefined; - function deprecate(fn: T, message: string): T; - function isDeepStrictEqual(val1: any, val2: any): boolean; - - interface CustomPromisify extends Function { - __promisify__: TCustom; - } - - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - - function promisify(fn: CustomPromisify): TCustom; - function promisify(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise; - function promisify(fn: (callback: (err?: Error) => void) => void): () => Promise; - function promisify(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, callback: (err?: Error) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: Error) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error | null, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error | null, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify(fn: Function): Function; - - namespace types { - function isAnyArrayBuffer(object: any): boolean; - function isArgumentsObject(object: any): object is IArguments; - function isArrayBuffer(object: any): object is ArrayBuffer; - function isArrayBufferView(object: any): object is ArrayBufferView; - function isAsyncFunction(object: any): boolean; - function isBooleanObject(object: any): object is Boolean; - function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); - function isDataView(object: any): object is DataView; - function isDate(object: any): object is Date; - function isExternal(object: any): boolean; - function isFloat32Array(object: any): object is Float32Array; - function isFloat64Array(object: any): object is Float64Array; - function isGeneratorFunction(object: any): boolean; - function isGeneratorObject(object: any): boolean; - function isInt8Array(object: any): object is Int8Array; - function isInt16Array(object: any): object is Int16Array; - function isInt32Array(object: any): object is Int32Array; - function isMap(object: any): boolean; - function isMapIterator(object: any): boolean; - function isModuleNamespaceObject(value: any): boolean; - function isNativeError(object: any): object is Error; - function isNumberObject(object: any): object is Number; - function isPromise(object: any): boolean; - function isProxy(object: any): boolean; - function isRegExp(object: any): object is RegExp; - function isSet(object: any): boolean; - function isSetIterator(object: any): boolean; - function isSharedArrayBuffer(object: any): boolean; - function isStringObject(object: any): boolean; - function isSymbolObject(object: any): boolean; - function isTypedArray(object: any): object is NodeJS.TypedArray; - function isUint8Array(object: any): object is Uint8Array; - function isUint8ClampedArray(object: any): object is Uint8ClampedArray; - function isUint16Array(object: any): object is Uint16Array; - function isUint32Array(object: any): object is Uint32Array; - function isWeakMap(object: any): boolean; - function isWeakSet(object: any): boolean; - function isWebAssemblyCompiledModule(object: any): boolean; - } - - class TextDecoder { - readonly encoding: string; - readonly fatal: boolean; - readonly ignoreBOM: boolean; - constructor( - encoding?: string, - options?: { fatal?: boolean; ignoreBOM?: boolean } - ); - decode( - input?: NodeJS.TypedArray | DataView | ArrayBuffer | null, - options?: { stream?: boolean } - ): string; - } - - class TextEncoder { - readonly encoding: string; - encode(input?: string): Uint8Array; - } -} diff --git a/types/node/v11/ts3.1/assert.d.ts b/types/node/v11/ts3.6/assert.d.ts similarity index 100% rename from types/node/v11/ts3.1/assert.d.ts rename to types/node/v11/ts3.6/assert.d.ts diff --git a/types/node/v11/ts3.6/base.d.ts b/types/node/v11/ts3.6/base.d.ts index 184fab0df6..9080234f98 100644 --- a/types/node/v11/ts3.6/base.d.ts +++ b/types/node/v11/ts3.6/base.d.ts @@ -13,9 +13,42 @@ /// // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -// tslint:disable-next-line:no-bad-reference -/// - -// TypeScript 3.2-specific augmentations: -/// /// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/node/v11/ts3.6/index.d.ts b/types/node/v11/ts3.6/index.d.ts index 07c70ef140..ed49ea697e 100644 --- a/types/node/v11/ts3.6/index.d.ts +++ b/types/node/v11/ts3.6/index.d.ts @@ -3,6 +3,4 @@ // Typically type modifiations should be made in base.d.ts instead of here /// - -// tslint:disable-next-line:no-bad-reference -/// +/// diff --git a/types/node/v11/ts3.6/node-tests.ts b/types/node/v11/ts3.6/node-tests.ts index 50477ece4d..c445abaaba 100644 --- a/types/node/v11/ts3.6/node-tests.ts +++ b/types/node/v11/ts3.6/node-tests.ts @@ -1,31 +1,1209 @@ -// tslint:disable-next-line:no-bad-reference -import '../ts3.1/node-tests'; -import '../ts3.1/assert'; -import '../ts3.1/buffer'; -import '../ts3.1/child_process'; -import '../ts3.1/cluster'; -import '../ts3.1/crypto'; -import '../ts3.1/dgram'; -import '../ts3.1/global'; -import '../ts3.1/http'; -import '../ts3.1/http2'; -import '../ts3.1/net'; -import '../ts3.1/os'; -import '../ts3.1/path'; -import '../ts3.1/perf_hooks'; -import '../ts3.1/process'; -import '../ts3.1/querystring'; -import '../ts3.1/readline'; -import '../ts3.1/repl'; -import '../ts3.1/stream'; -import '../ts3.1/tls'; -import '../ts3.1/tty'; -import '../ts3.1/util'; -import '../ts3.1/worker_threads'; -import '../ts3.1/zlib'; +import assert = require("assert"); +import * as fs from "fs"; +import * as url from "url"; +import * as util from "util"; +import * as http from "http"; +import * as https from "https"; +import * as vm from "vm"; +import * as console2 from "console"; +import * as string_decoder from "string_decoder"; +import * as timers from "timers"; +import * as dns from "dns"; +import * as async_hooks from "async_hooks"; +import * as inspector from "inspector"; +import * as trace_events from "trace_events"; +import Module = require("module"); -import { types } from 'util'; +//////////////////////////////////////////////////// +/// File system tests : http://nodejs.org/api/fs.html +//////////////////////////////////////////////////// +{ + { + fs.writeFile("thebible.txt", + "Do unto others as you would have them do unto you.", + assert.ifError); + + fs.write(1234, "test", () => { }); + + fs.writeFile("Harry Potter", + "\"You be wizzing, Harry,\" jived Dumbledore.", + { + encoding: "ascii" + }, + assert.ifError); + + fs.writeFile("testfile", "content", "utf8", assert.ifError); + + fs.writeFileSync("testfile", "content", "utf8"); + fs.writeFileSync("testfile", "content", { encoding: "utf8" }); + fs.writeFileSync("testfile", new DataView(new ArrayBuffer(1)), { encoding: "utf8" }); + } + + { + fs.appendFile("testfile", "foobar", "utf8", assert.ifError); + fs.appendFile("testfile", "foobar", { encoding: "utf8" }, assert.ifError); + fs.appendFileSync("testfile", "foobar", "utf8"); + fs.appendFileSync("testfile", "foobar", { encoding: "utf8" }); + } + + { + let content: string; + let buffer: Buffer; + let stringOrBuffer: string | Buffer; + const nullEncoding: string | null = null; + const stringEncoding: string | null = 'utf8'; + + content = fs.readFileSync('testfile', 'utf8'); + content = fs.readFileSync('testfile', { encoding: 'utf8' }); + stringOrBuffer = fs.readFileSync('testfile', stringEncoding); + stringOrBuffer = fs.readFileSync('testfile', { encoding: stringEncoding }); + + buffer = fs.readFileSync('testfile'); + buffer = fs.readFileSync('testfile', null); + buffer = fs.readFileSync('testfile', { encoding: null }); + stringOrBuffer = fs.readFileSync('testfile', nullEncoding); + stringOrBuffer = fs.readFileSync('testfile', { encoding: nullEncoding }); + + buffer = fs.readFileSync('testfile', { flag: 'r' }); + + fs.readFile('testfile', 'utf8', (err, data) => content = data); + fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); + fs.readFile('testfile', stringEncoding, (err, data) => stringOrBuffer = data); + fs.readFile('testfile', { encoding: stringEncoding }, (err, data) => stringOrBuffer = data); + + fs.readFile('testfile', (err, data) => buffer = data); + fs.readFile('testfile', null, (err, data) => buffer = data); + fs.readFile('testfile', { encoding: null }, (err, data) => buffer = data); + fs.readFile('testfile', nullEncoding, (err, data) => stringOrBuffer = data); + fs.readFile('testfile', { encoding: nullEncoding }, (err, data) => stringOrBuffer = data); + + fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); + } + + { + fs.read(1, new DataView(new ArrayBuffer(1)), 0, 1, 0, (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: DataView) => {}); + } + + { + fs.readSync(1, new DataView(new ArrayBuffer(1)), 0, 1, 0); + } + + { + let errno: number; + fs.readFile('testfile', (err, data) => { + if (err && err.errno) { + errno = err.errno; + } + }); + } + + { + let listS: string[]; + listS = fs.readdirSync('path'); + listS = fs.readdirSync('path', { encoding: 'utf8' }); + listS = fs.readdirSync('path', { encoding: null }); + listS = fs.readdirSync('path', { encoding: undefined }) as string[]; + listS = fs.readdirSync('path', 'utf8'); + listS = fs.readdirSync('path', null); + listS = fs.readdirSync('path', undefined); + const listDir: fs.Dirent[] = fs.readdirSync('path', { withFileTypes: true }); + const listDir2: Buffer[] = fs.readdirSync('path', { withFileTypes: false, encoding: 'buffer' }); + const listDir3: fs.Dirent[] = fs.readdirSync('path', { encoding: 'utf8', withFileTypes: true }); + + let listB: Buffer[]; + listB = fs.readdirSync('path', { encoding: 'buffer' }); + listB = fs.readdirSync("path", 'buffer'); + + const enc = 'buffer'; + fs.readdirSync('path', { encoding: enc }); + fs.readdirSync('path', { }); + + fs.readdir('path', { withFileTypes: true }, (err: NodeJS.ErrnoException | null, files: fs.Dirent[]) => {}); + } + + async function testPromisify() { + const rd = util.promisify(fs.readdir); + let listS: string[]; + listS = await rd('path'); + listS = await rd('path', 'utf8'); + listS = await rd('path', null); + listS = await rd('path', undefined); + listS = await rd('path', { encoding: 'utf8' }); + listS = await rd('path', { encoding: null }); + listS = await rd('path', { encoding: null, withFileTypes: false }); + listS = await rd('path', { encoding: 'utf8', withFileTypes: false }); + const listDir: fs.Dirent[] = await rd('path', { withFileTypes: true }); + const listDir2: Buffer[] = await rd('path', { withFileTypes: false, encoding: 'buffer' }); + const listDir3: fs.Dirent[] = await rd('path', { encoding: 'utf8', withFileTypes: true }); + } + + { + fs.mkdtemp('/tmp/foo-', (err, folder) => { + console.log(folder); + // Prints: /tmp/foo-itXde2 + }); + } + + { + let tempDir: string; + tempDir = fs.mkdtempSync('/tmp/foo-'); + } + + { + fs.watch('/tmp/foo-', (event, filename) => { + console.log(event, filename); + }); + + fs.watch('/tmp/foo-', 'utf8', (event, filename) => { + console.log(event, filename); + }); + + fs.watch('/tmp/foo-', { + recursive: true, + persistent: true, + encoding: 'utf8' + }, (event, filename) => { + console.log(event, filename); + }); + } + + { + fs.access('/path/to/folder', (err) => { }); + + fs.access(Buffer.from(''), (err) => { }); + + fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { }); + + fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { }); + + fs.accessSync('/path/to/folder'); + + fs.accessSync(Buffer.from('')); + + fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); + + fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); + } + + { + let s = '123'; + let b: Buffer; + fs.readlink('/path/to/folder', (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', undefined, (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', 'utf8', (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', 'buffer', (err, linkString) => b = linkString); + fs.readlink('/path/to/folder', s, (err, linkString) => typeof linkString === 'string' ? s = linkString : b = linkString); + fs.readlink('/path/to/folder', {}, (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', { encoding: undefined }, (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', { encoding: 'utf8' }, (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', { encoding: 'buffer' }, (err, linkString) => b = linkString); + fs.readlink('/path/to/folder', { encoding: s }, (err, linkString) => typeof linkString === "string" ? s = linkString : b = linkString); + + s = fs.readlinkSync('/path/to/folder'); + s = fs.readlinkSync('/path/to/folder', undefined); + s = fs.readlinkSync('/path/to/folder', 'utf8'); + b = fs.readlinkSync('/path/to/folder', 'buffer'); + const v1 = fs.readlinkSync('/path/to/folder', s); + typeof v1 === "string" ? s = v1 : b = v1; + + s = fs.readlinkSync('/path/to/folder', {}); + s = fs.readlinkSync('/path/to/folder', { encoding: undefined }); + s = fs.readlinkSync('/path/to/folder', { encoding: 'utf8' }); + b = fs.readlinkSync('/path/to/folder', { encoding: 'buffer' }); + const v2 = fs.readlinkSync('/path/to/folder', { encoding: s }); + typeof v2 === "string" ? s = v2 : b = v2; + } + + { + let s = '123'; + let b: Buffer; + fs.realpath('/path/to/folder', (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath); + fs.realpath('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath); + fs.realpath('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath); + fs.realpath('/path/to/folder', { encoding: s }, (err, resolvedPath) => typeof resolvedPath === "string" ? s = resolvedPath : b = resolvedPath); + + s = fs.realpathSync('/path/to/folder'); + s = fs.realpathSync('/path/to/folder', undefined); + s = fs.realpathSync('/path/to/folder', 'utf8'); + b = fs.realpathSync('/path/to/folder', 'buffer'); + const v1 = fs.realpathSync('/path/to/folder', s); + typeof v1 === "string" ? s = v1 : b = v1; + + s = fs.realpathSync('/path/to/folder', {}); + s = fs.realpathSync('/path/to/folder', { encoding: undefined }); + s = fs.realpathSync('/path/to/folder', { encoding: 'utf8' }); + b = fs.realpathSync('/path/to/folder', { encoding: 'buffer' }); + const v2 = fs.realpathSync('/path/to/folder', { encoding: s }); + typeof v2 === "string" ? s = v2 : b = v2; + + // native + fs.realpath.native('/path/to/folder', (err, resolvedPath) => s = resolvedPath); + fs.realpath.native('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); + fs.realpath.native('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath); + fs.realpath.native('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath); + fs.realpath.native('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath); + fs.realpath.native('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath); + fs.realpath.native('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath); + fs.realpath.native('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath); + fs.realpath.native('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath); + fs.realpath.native('/path/to/folder', { encoding: s }, (err, resolvedPath) => typeof resolvedPath === "string" ? s = resolvedPath : b = resolvedPath); + + s = fs.realpathSync.native('/path/to/folder'); + s = fs.realpathSync.native('/path/to/folder', undefined); + s = fs.realpathSync.native('/path/to/folder', 'utf8'); + b = fs.realpathSync.native('/path/to/folder', 'buffer'); + const v3 = fs.realpathSync.native('/path/to/folder', s); + typeof v3 === "string" ? s = v3 : b = v3; + + s = fs.realpathSync.native('/path/to/folder', {}); + s = fs.realpathSync.native('/path/to/folder', { encoding: undefined }); + s = fs.realpathSync.native('/path/to/folder', { encoding: 'utf8' }); + b = fs.realpathSync.native('/path/to/folder', { encoding: 'buffer' }); + const v4 = fs.realpathSync.native('/path/to/folder', { encoding: s }); + typeof v4 === "string" ? s = v4 : b = v4; + } + + { + fs.copyFile('/path/to/src', '/path/to/dest', (err) => console.error(err)); + fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL, (err) => console.error(err)); + fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE, (err) => console.error(err)); + fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE_FORCE, (err) => console.error(err)); + + fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL); + fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE); + fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE_FORCE); + + const cf = util.promisify(fs.copyFile); + cf('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL).then(console.log); + } + + { + fs.mkdir('some/test/path', { + recursive: true, + mode: 0o777, + }, () => { + }); + + fs.mkdirSync('some/test/path', { + recursive: true, + mode: 0o777, + }); + } + + { + let names: Promise; + let buffers: Promise; + let namesOrBuffers: Promise; + let entries: Promise; + + names = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: false }); + buffers = fs.promises.readdir('/path/to/dir', { encoding: 'buffer', withFileTypes: false }); + namesOrBuffers = fs.promises.readdir('/path/to/dir', { encoding: 'SOME OTHER', withFileTypes: false }); + entries = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: true }); + } +} + +//////////////////////////////////////////////////// +/// Url tests : http://nodejs.org/api/url.html +//////////////////////////////////////////////////// + +{ + { + url.format(url.parse('http://www.example.com/xyz')); + + url.format('http://www.example.com/xyz'); + + // https://google.com/search?q=you're%20a%20lizard%2C%20gary + url.format({ + protocol: 'https', + host: "google.com", + pathname: 'search', + query: { q: "you're a lizard, gary" } + }); + + const myURL = new url.URL('https://a:b@你好你好?abc#foo'); + url.format(myURL, { fragment: false, unicode: true, auth: false }); + } + + { + const helloUrl = url.parse('http://example.com/?hello=world', true); + let helloQuery = helloUrl.query['hello']; + assert.equal(helloUrl.query['hello'], 'world'); + + let strUrl = url.parse('http://example.com/?hello=world'); + let queryStr: string = strUrl.query!; + + strUrl = url.parse('http://example.com/?hello=world', false); + queryStr = strUrl.query!; + + function getBoolean(): boolean { return false; } + const urlUrl = url.parse('http://example.com/?hello=world', getBoolean()); + if (typeof(urlUrl.query) === 'string') { + queryStr = urlUrl.query; + } else if (urlUrl.query) { + helloQuery = urlUrl.query['hello']; + } + } + + { + const ascii: string = url.domainToASCII('español.com'); + const unicode: string = url.domainToUnicode('xn--espaol-zwa.com'); + } + + { + let myURL = new url.URL('https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert.equal(myURL.hash, '#bar'); + assert.equal(myURL.host, 'example.org:81'); + assert.equal(myURL.hostname, 'example.org'); + assert.equal(myURL.href, 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert.equal(myURL.origin, 'https://example.org:81'); + assert.equal(myURL.password, 'thepwd'); + assert.equal(myURL.username, 'theuser'); + assert.equal(myURL.pathname, '/foo/path'); + assert.equal(myURL.port, "81"); + assert.equal(myURL.protocol, "https:"); + assert.equal(myURL.search, "?query=string"); + assert.equal(myURL.toString(), 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert(myURL.searchParams instanceof url.URLSearchParams); + + myURL.host = 'example.org:82'; + myURL.hostname = 'example.com'; + myURL.href = 'http://other.com'; + myURL.hash = 'baz'; + myURL.password = "otherpwd"; + myURL.username = "otheruser"; + myURL.pathname = "/otherPath"; + myURL.port = "82"; + myURL.protocol = "http"; + myURL.search = "a=b"; + assert.equal(myURL.href, 'http://otheruser:otherpwd@other.com:82/otherPath?a=b#baz'); + + myURL = new url.URL('/foo', 'https://example.org/'); + assert.equal(myURL.href, 'https://example.org/foo'); + assert.equal(myURL.toJSON(), myURL.href); + } + + { + const searchParams = new url.URLSearchParams('abc=123'); + + assert.equal(searchParams.toString(), 'abc=123'); + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { + assert.equal(name, 'abc'); + assert.equal(value, '123'); + assert.equal(me, searchParams); + }); + + assert.equal(searchParams.get('abc'), '123'); + + searchParams.append('abc', 'xyz'); + + assert.deepEqual(searchParams.getAll('abc'), ['123', 'xyz']); + + const entries = searchParams.entries(); + assert.deepEqual(entries.next(), { value: ["abc", "123"], done: false }); + assert.deepEqual(entries.next(), { value: ["abc", "xyz"], done: false }); + assert.deepEqual(entries.next(), { value: undefined, done: true }); + + const keys = searchParams.keys(); + assert.deepEqual(keys.next(), { value: "abc", done: false }); + assert.deepEqual(keys.next(), { value: "abc", done: false }); + assert.deepEqual(keys.next(), { value: undefined, done: true }); + + const values = searchParams.values(); + assert.deepEqual(values.next(), { value: "123", done: false }); + assert.deepEqual(values.next(), { value: "xyz", done: false }); + assert.deepEqual(values.next(), { value: undefined, done: true }); + + searchParams.set('abc', 'b'); + assert.deepEqual(searchParams.getAll('abc'), ['b']); + + searchParams.delete('a'); + assert(!searchParams.has('a')); + assert.equal(searchParams.get('a'), null); + + searchParams.sort(); + } + + { + const searchParams = new url.URLSearchParams({ + user: 'abc', + query: ['first', 'second'] + }); + + assert.equal(searchParams.toString(), 'user=abc&query=first%2Csecond'); + assert.deepEqual(searchParams.getAll('query'), ['first,second']); + } + + { + // Using an array + const params = new url.URLSearchParams([ + ['user', 'abc'], + ['query', 'first'], + ['query', 'second'], + // ts 2.1/2.* compatibility + // tslint:disable-next-line no-unnecessary-type-assertion + ] as Array<[string, string]>); + assert.equal(params.toString(), 'user=abc&query=first&query=second'); + } + + { + let path: string = url.fileURLToPath('file://test'); + path = url.fileURLToPath(new url.URL('file://test')); + } + + { + const path: url.URL = url.pathToFileURL('file://test'); + } +} + +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + +{ + let agent: https.Agent = new https.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256, + maxCachedSessions: 100, + timeout: 15000 + }); + + agent = https.globalAgent; + + https.request({ + agent: false + }); + https.request({ + agent + }); + https.request({ + agent: undefined + }); + + https.get('http://www.example.com/xyz'); + https.request('http://www.example.com/xyz'); + + https.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + https.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + + https.get(new url.URL('http://www.example.com/xyz')); + https.request(new url.URL('http://www.example.com/xyz')); + + https.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + https.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + + const opts: https.RequestOptions = { + path: '/some/path' + }; + https.get(new url.URL('http://www.example.com'), opts); + https.request(new url.URL('http://www.example.com'), opts); + https.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + https.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + + https.globalAgent.options.ca = []; + + { + function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} + + class MyIncomingMessage extends http.IncomingMessage { + foo: number; + } + + class MyServerResponse extends http.ServerResponse { + foo: string; + } + + let server: https.Server; + + server = new https.Server(); + server = new https.Server(reqListener); + server = new https.Server({ IncomingMessage: MyIncomingMessage}); + + server = new https.Server({ + IncomingMessage: MyIncomingMessage, + ServerResponse: MyServerResponse + }, reqListener); + + server = https.createServer(); + server = https.createServer(reqListener); + server = https.createServer({ IncomingMessage: MyIncomingMessage }); + server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); + + const timeout: number = server.timeout; + const listening: boolean = server.listening; + const keepAliveTimeout: number = server.keepAliveTimeout; + const maxHeadersCount: number | null = server.maxHeadersCount; + const headersTimeout: number = server.headersTimeout; + server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); + } +} + +//////////////////////////////////////////////////// +/// string_decoder tests : https://nodejs.org/api/string_decoder.html +//////////////////////////////////////////////////// + +{ + const StringDecoder = string_decoder.StringDecoder; + const buffer = new Buffer('test'); + const decoder1 = new StringDecoder(); + const decoder2 = new StringDecoder('utf8'); + const part1: string = decoder1.write(new Buffer('test')); + const end1: string = decoder1.end(); + const part2: string = decoder2.write(new Buffer('test')); + const end2: string = decoder1.end(new Buffer('test')); +} + +//////////////////////////////////////////////////// +/// vm tests : https://nodejs.org/api/vm.html +//////////////////////////////////////////////////// + +{ + { + const sandbox = { + animal: 'cat', + count: 2 + }; + + const context = vm.createContext(sandbox); + console.log(vm.isContext(context)); + const script = new vm.Script('count += 1; name = "kitty"'); + + for (let i = 0; i < 10; ++i) { + script.runInContext(context); + } + + console.log(util.inspect(sandbox)); + + vm.runInNewContext('count += 1; name = "kitty"', sandbox); + console.log(util.inspect(sandbox)); + } + + { + const sandboxes = [{}, {}, {}]; + + const script = new vm.Script('globalVar = "set"'); + + sandboxes.forEach((sandbox) => { + script.runInNewContext(sandbox); + script.runInThisContext(); + }); + + console.log(util.inspect(sandboxes)); + + const localVar = 'initial value'; + vm.runInThisContext('localVar = "vm";'); + + console.log(localVar); + } + + { + vm.runInThisContext('console.log("hello world"', './my-file.js'); + } + + { + const fn: Function = vm.compileFunction('console.log("test")', [], { + parsingContext: vm.createContext(), + contextExtensions: [{ + a: 1, + }], + produceCachedData: false, + cachedData: Buffer.from('nope'), + }); + } +} + +///////////////////////////////////////////////////// +/// Timers tests : https://nodejs.org/api/timers.html +///////////////////////////////////////////////////// + +{ + { + const immediate = timers + .setImmediate(() => { + console.log('immediate'); + }) + .unref() + .ref(); + const b: boolean = immediate.hasRef(); + timers.clearImmediate(immediate); + } + { + const timeout = timers + .setInterval(() => { + console.log('interval'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearInterval(timeout); + } + { + const timeout = timers + .setTimeout(() => { + console.log('timeout'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearTimeout(timeout); + } + async function testPromisify() { + const setTimeout = util.promisify(timers.setTimeout); + let v: void = await setTimeout(100); // tslint:disable-line no-void-expression void-return + let s: string = await setTimeout(100, ""); + + const setImmediate = util.promisify(timers.setImmediate); + v = await setImmediate(); // tslint:disable-line no-void-expression + s = await setImmediate(""); + } +} + +///////////////////////////////////////////////////////// +/// Errors Tests : https://nodejs.org/api/errors.html /// +///////////////////////////////////////////////////////// + +{ + { + Error.stackTraceLimit = Infinity; + } + { + const myObject = {}; + Error.captureStackTrace(myObject); + } + { + const frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace!(new Error(), frames); + } + { + const frame: NodeJS.CallSite = null!; + const frameThis: any = frame.getThis(); + const typeName: string | null = frame.getTypeName(); + const func: Function | undefined = frame.getFunction(); + const funcName: string | null = frame.getFunctionName(); + const meth: string | null = frame.getMethodName(); + const fname: string | null = frame.getFileName(); + const lineno: number | null = frame.getLineNumber(); + const colno: number | null = frame.getColumnNumber(); + const evalOrigin: string | undefined = frame.getEvalOrigin(); + const isTop: boolean = frame.isToplevel(); + const isEval: boolean = frame.isEval(); + const isNative: boolean = frame.isNative(); + const isConstr: boolean = frame.isConstructor(); + } +} + +/////////////////////////////////////////////////////////// +/// Console Tests : https://nodejs.org/api/console.html /// +/////////////////////////////////////////////////////////// + +{ + { + let _c: Console = console; + _c = console2; + } + { + const writeStream = fs.createWriteStream('./index.d.ts'); + let consoleInstance: Console = new console.Console(writeStream); + + consoleInstance = new console.Console(writeStream, writeStream); + consoleInstance = new console.Console(writeStream, writeStream, true); + consoleInstance = new console.Console({ + stdout: writeStream, + stderr: writeStream, + colorMode: 'auto', + ignoreErrors: true + }); + consoleInstance = new console.Console({ + stdout: writeStream, + colorMode: false + }); + consoleInstance = new console.Console({ + stdout: writeStream + }); + } + { + console.assert('value'); + console.assert('value', 'message'); + console.assert('value', 'message', 'foo', 'bar'); + console.clear(); + console.count(); + console.count('label'); + console.countReset(); + console.countReset('label'); + console.debug(); + console.debug('message'); + console.debug('message', 'foo', 'bar'); + console.dir('obj'); + console.dir('obj', { depth: 1 }); + console.error(); + console.error('message'); + console.error('message', 'foo', 'bar'); + console.group(); + console.group('label'); + console.group('label1', 'label2'); + console.groupCollapsed(); + console.groupEnd(); + console.info(); + console.info('message'); + console.info('message', 'foo', 'bar'); + console.log(); + console.log('message'); + console.log('message', 'foo', 'bar'); + console.table({ foo: 'bar' }); + console.table([{ foo: 'bar' }]); + console.table([{ foo: 'bar' }], ['foo']); + console.time(); + console.time('label'); + console.timeEnd(); + console.timeEnd('label'); + console.timeLog(); + console.timeLog('label'); + console.timeLog('label', 'foo', 'bar'); + console.trace(); + console.trace('message'); + console.trace('message', 'foo', 'bar'); + console.warn(); + console.warn('message'); + console.warn('message', 'foo', 'bar'); + + // --- Inspector mode only --- + console.markTimeline(); + console.markTimeline('label'); + console.profile(); + console.profile('label'); + console.profileEnd(); + console.profileEnd('label'); + console.timeStamp(); + console.timeStamp('label'); + console.timeline(); + console.timeline('label'); + console.timelineEnd(); + console.timelineEnd('label'); + } +} + +/////////////////////////////////////////////////// +/// DNS Tests : https://nodejs.org/api/dns.html /// +/////////////////////////////////////////////////// + +{ + dns.lookup("nodejs.org", (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 4, (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 6, (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", {}, (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup( + "nodejs.org", + { + family: 4, + hints: dns.ADDRCONFIG | dns.V4MAPPED, + all: false + }, + (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + } + ); + dns.lookup("nodejs.org", { all: true }, (err, addresses) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: dns.LookupAddress[] = addresses; + }); + dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: dns.LookupAddress[] = addresses; + }); + + function trueOrFalse(): boolean { + return Math.random() > 0.5 ? true : false; + } + dns.lookup("nodejs.org", { all: trueOrFalse() }, (err, addresses, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _addresses: string | dns.LookupAddress[] = addresses; + const _family: number | undefined = family; + }); + + dns.lookupService("127.0.0.1", 0, (err, hostname, service) => { + const _err: NodeJS.ErrnoException | null = err; + const _hostname: string = hostname; + const _service: string = service; + }); + + dns.resolve("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "A", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "AAAA", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "ANY", (err, addresses) => { + const _addresses: dns.AnyRecord[] = addresses; + }); + dns.resolve("nodejs.org", "MX", (err, addresses) => { + const _addresses: dns.MxRecord[] = addresses; + }); + + dns.resolve4("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve4("nodejs.org", { ttl: true }, (err, addresses) => { + const _addresses: dns.RecordWithTtl[] = addresses; + }); + { + const ttl = false; + dns.resolve4("nodejs.org", { ttl }, (err, addresses) => { + const _addresses: string[] | dns.RecordWithTtl[] = addresses; + }); + } + + dns.resolve6("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve6("nodejs.org", { ttl: true }, (err, addresses) => { + const _addresses: dns.RecordWithTtl[] = addresses; + }); + { + const ttl = false; + dns.resolve6("nodejs.org", { ttl }, (err, addresses) => { + const _addresses: string[] | dns.RecordWithTtl[] = addresses; + }); + } + { + const resolver = new dns.Resolver(); + resolver.setServers(["4.4.4.4"]); + resolver.resolve("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + resolver.cancel(); + } +} + +/***************************************************************************** + * * + * The following tests are the modules not mentioned in document but existed * + * * + *****************************************************************************/ + +/////////////////////////////////////////////////////////// +/// Constants Tests /// +/////////////////////////////////////////////////////////// + +import * as constants from 'constants'; +{ + let str: string; + let num: number; + num = constants.SIGHUP; + num = constants.SIGINT; + num = constants.SIGQUIT; + num = constants.SIGILL; + num = constants.SIGTRAP; + num = constants.SIGABRT; + num = constants.SIGIOT; + num = constants.SIGBUS; + num = constants.SIGFPE; + num = constants.SIGKILL; + num = constants.SIGUSR1; + num = constants.SIGSEGV; + num = constants.SIGUSR2; + num = constants.SIGPIPE; + num = constants.SIGALRM; + num = constants.SIGTERM; + num = constants.SIGCHLD; + num = constants.SIGSTKFLT; + num = constants.SIGCONT; + num = constants.SIGSTOP; + num = constants.SIGTSTP; + num = constants.SIGTTIN; + num = constants.SIGTTOU; + num = constants.SIGURG; + num = constants.SIGXCPU; + num = constants.SIGXFSZ; + num = constants.SIGVTALRM; + num = constants.SIGPROF; + num = constants.SIGWINCH; + num = constants.SIGIO; + num = constants.SIGPOLL; + num = constants.SIGPWR; + num = constants.SIGSYS; + num = constants.SIGUNUSED; + num = constants.O_RDONLY; + num = constants.O_WRONLY; + num = constants.O_RDWR; + num = constants.S_IFMT; + num = constants.S_IFREG; + num = constants.S_IFDIR; + num = constants.S_IFCHR; + num = constants.S_IFBLK; + num = constants.S_IFIFO; + num = constants.S_IFLNK; + num = constants.S_IFSOCK; + num = constants.O_CREAT; + num = constants.O_EXCL; + num = constants.O_NOCTTY; + num = constants.O_TRUNC; + num = constants.O_APPEND; + num = constants.O_DIRECTORY; + num = constants.O_NOATIME; + num = constants.O_NOFOLLOW; + num = constants.O_SYNC; + num = constants.O_DSYNC; + num = constants.O_DIRECT; + num = constants.O_NONBLOCK; + num = constants.S_IRWXU; + num = constants.S_IRUSR; + num = constants.S_IWUSR; + num = constants.S_IXUSR; + num = constants.S_IRWXG; + num = constants.S_IRGRP; + num = constants.S_IWGRP; + num = constants.S_IXGRP; + num = constants.S_IRWXO; + num = constants.S_IROTH; + num = constants.S_IWOTH; + num = constants.S_IXOTH; + num = constants.F_OK; + num = constants.R_OK; + num = constants.W_OK; + num = constants.X_OK; + num = constants.SSL_OP_ALL; + num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION; + num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE; + num = constants.SSL_OP_CISCO_ANYCONNECT; + num = constants.SSL_OP_COOKIE_EXCHANGE; + num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG; + num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; + num = constants.SSL_OP_EPHEMERAL_RSA; + num = constants.SSL_OP_LEGACY_SERVER_CONNECT; + num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER; + num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG; + num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING; + num = constants.SSL_OP_NETSCAPE_CA_DN_BUG; + num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG; + num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG; + num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; + num = constants.SSL_OP_NO_COMPRESSION; + num = constants.SSL_OP_NO_QUERY_MTU; + num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION; + num = constants.SSL_OP_NO_SSLv2; + num = constants.SSL_OP_NO_SSLv3; + num = constants.SSL_OP_NO_TICKET; + num = constants.SSL_OP_NO_TLSv1; + num = constants.SSL_OP_NO_TLSv1_1; + num = constants.SSL_OP_NO_TLSv1_2; + num = constants.SSL_OP_PKCS1_CHECK_1; + num = constants.SSL_OP_PKCS1_CHECK_2; + num = constants.SSL_OP_SINGLE_DH_USE; + num = constants.SSL_OP_SINGLE_ECDH_USE; + num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG; + num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG; + num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG; + num = constants.SSL_OP_TLS_D5_BUG; + num = constants.SSL_OP_TLS_ROLLBACK_BUG; + num = constants.ENGINE_METHOD_RSA; + num = constants.ENGINE_METHOD_DSA; + num = constants.ENGINE_METHOD_DH; + num = constants.ENGINE_METHOD_RAND; + num = constants.ENGINE_METHOD_ECDH; + num = constants.ENGINE_METHOD_ECDSA; + num = constants.ENGINE_METHOD_CIPHERS; + num = constants.ENGINE_METHOD_DIGESTS; + num = constants.ENGINE_METHOD_STORE; + num = constants.ENGINE_METHOD_PKEY_METHS; + num = constants.ENGINE_METHOD_PKEY_ASN1_METHS; + num = constants.ENGINE_METHOD_ALL; + num = constants.ENGINE_METHOD_NONE; + num = constants.DH_CHECK_P_NOT_SAFE_PRIME; + num = constants.DH_CHECK_P_NOT_PRIME; + num = constants.DH_UNABLE_TO_CHECK_GENERATOR; + num = constants.DH_NOT_SUITABLE_GENERATOR; + num = constants.NPN_ENABLED; + num = constants.ALPN_ENABLED; + num = constants.RSA_PKCS1_PADDING; + num = constants.RSA_SSLV23_PADDING; + num = constants.RSA_NO_PADDING; + num = constants.RSA_PKCS1_OAEP_PADDING; + num = constants.RSA_X931_PADDING; + num = constants.RSA_PKCS1_PSS_PADDING; + num = constants.POINT_CONVERSION_COMPRESSED; + num = constants.POINT_CONVERSION_UNCOMPRESSED; + num = constants.POINT_CONVERSION_HYBRID; + str = constants.defaultCoreCipherList; + str = constants.defaultCipherList; +} + +//////////////////////////////////////////////////// +/// AsyncHooks tests : https://nodejs.org/api/async_hooks.html +//////////////////////////////////////////////////// +{ + const hooks: async_hooks.HookCallbacks = { + init() {}, + before() {}, + after() {}, + destroy() {}, + promiseResolve() {}, + }; + + const asyncHook = async_hooks.createHook(hooks); + + asyncHook.enable().disable().enable(); + + const tId: number = async_hooks.triggerAsyncId(); + const eId: number = async_hooks.executionAsyncId(); + + class TestResource extends async_hooks.AsyncResource { + constructor() { + super('TEST_RESOURCE'); + } + } + + class AnotherTestResource extends async_hooks.AsyncResource { + constructor() { + super('TEST_RESOURCE', 42); + const aId: number = this.asyncId(); + const tId: number = this.triggerAsyncId(); + } + run() { + this.runInAsyncScope(() => {}); + this.runInAsyncScope(Array.prototype.find, [], () => true); + } + destroy() { + this.emitDestroy(); + } + } + + // check AsyncResource constructor options. + new async_hooks.AsyncResource(''); + new async_hooks.AsyncResource('', 0); + new async_hooks.AsyncResource('', {}); + new async_hooks.AsyncResource('', { triggerAsyncId: 0 }); + new async_hooks.AsyncResource('', { + triggerAsyncId: 0, + requireManualDestroy: true + }); +} + +/////////////////////////////////////////////////////////// +/// Inspector Tests /// +/////////////////////////////////////////////////////////// + +{ + { + const b: inspector.Console.ConsoleMessage = {source: 'test', text: 'test', level: 'error' }; + inspector.open(); + inspector.open(0); + inspector.open(0, 'localhost'); + inspector.open(0, 'localhost', true); + inspector.close(); + const inspectorUrl: string | undefined = inspector.url(); + + const session = new inspector.Session(); + session.connect(); + session.disconnect(); + + // Unknown post method + session.post('A.b', { key: 'value' }, (err, params) => {}); + // TODO: parameters are implicitly 'any' and need type annotation + session.post('A.b', (err: Error | null, params?: {}) => {}); + session.post('A.b'); + // Known post method + const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; + session.post('Runtime.evaluate', parameter, + (err: Error | null, params: inspector.Runtime.EvaluateReturnType) => {}); + session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { + const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails!; + const resultClassName: string = params.result.className!; + }); + session.post('Runtime.evaluate'); + + // General event + session.on('inspectorNotification', message => { + message; // $ExpectType InspectorNotification<{}> + }); + // Known events + session.on('Debugger.paused', (message: inspector.InspectorNotification) => { + const method: string = message.method; + const pauseReason: string = message.params.reason; + }); + session.on('Debugger.resumed', () => {}); + // Node Inspector events + session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification) => { + const value: Array<{}> = message.params.value; + }); + } +} + +/////////////////////////////////////////////////////////// +/// Trace Events Tests /// +/////////////////////////////////////////////////////////// + +{ + const enabledCategories: string = trace_events.getEnabledCategories(); + const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] }); + const categories: string = tracing.categories; + const enabled: boolean = tracing.enabled; + tracing.enable(); + tracing.disable(); +} + +//////////////////////////////////////////////////// +/// module tests : http://nodejs.org/api/modules.html +//////////////////////////////////////////////////// +import moduleModule = require('module'); + +{ + require.extensions[".ts"] = () => ""; + + Module.runMain(); + const s: string = Module.wrap("some code"); + + const m1: Module = new Module("moduleId"); + const m2: Module = new Module.Module("moduleId"); + const b: string[] = Module.builtinModules; + let paths: string[] = module.paths; + paths = m1.paths; + + moduleModule.createRequireFromPath('./test')('test'); +} + +//////////////////////////////////////////////////// +/// Node.js ESNEXT Support +//////////////////////////////////////////////////// + +{ + const s = 'foo'; + const s1: string = s.trimLeft(); + const s2: string = s.trimRight(); + const s3: string = s.trimStart(); + const s4: string = s.trimEnd(); +} ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// ////////////////////////////////////////////////////////// @@ -40,10 +1218,10 @@ import { types } from 'util'; ////////////////////////////////////////////////////////// { const value: BigInt64Array | BigUint64Array | number = [] as any; - if (types.isBigInt64Array(value)) { + if (util.types.isBigInt64Array(value)) { // $ExpectType BigInt64Array const b = value; - } else if (types.isBigUint64Array(value)) { + } else if (util.types.isBigUint64Array(value)) { // $ExpectType BigUint64Array const b = value; } else { diff --git a/types/node/v11/ts3.6/tslint.json b/types/node/v11/ts3.6/tslint.json index 56086bb86a..65e8b18d2a 100644 --- a/types/node/v11/ts3.6/tslint.json +++ b/types/node/v11/ts3.6/tslint.json @@ -1,6 +1,10 @@ { "extends": "dtslint/dt.json", "rules": { - "no-bad-reference": false + "ban-types": false, + "no-bad-reference": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "unified-signatures": false } } diff --git a/types/node/v11/util.d.ts b/types/node/v11/util.d.ts index 56a879e854..78554b6d16 100644 --- a/types/node/v11/util.d.ts +++ b/types/node/v11/util.d.ts @@ -1,15 +1,181 @@ -// tslint:disable-next-line:no-bad-reference -/// - declare module "util" { + interface InspectOptions extends NodeJS.InspectOptions { } + function format(format: any, ...param: any[]): string; + function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function debug(string: string): void; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function error(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function puts(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function print(...param: any[]): void; + /** @deprecated since v0.11.3 - use a third party module instead. */ + function log(string: string): void; + function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + function inspect(object: any, options: InspectOptions): string; namespace inspect { const custom: unique symbol; + let colors: { + [color: string]: [number, number] | undefined + }; + let styles: { + [style: string]: string | undefined + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; } + /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ + function isArray(object: any): object is any[]; + /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ + function isRegExp(object: any): object is RegExp; + /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ + function isDate(object: any): object is Date; + /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ + function isError(object: any): object is Error; + function inherits(constructor: any, superConstructor: any): void; + function debuglog(key: string): (msg: string, ...param: any[]) => void; + /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ + function isBoolean(object: any): object is boolean; + /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ + function isBuffer(object: any): object is Buffer; + /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ + function isFunction(object: any): boolean; + /** @deprecated since v4.0.0 - use `value === null` instead. */ + function isNull(object: any): object is null; + /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ + function isNullOrUndefined(object: any): object is null | undefined; + /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ + function isNumber(object: any): object is number; + /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ + function isObject(object: any): boolean; + /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ + function isPrimitive(object: any): boolean; + /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ + function isString(object: any): object is string; + /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ + function isSymbol(object: any): object is symbol; + /** @deprecated since v4.0.0 - use `value === undefined` instead. */ + function isUndefined(object: any): object is undefined; + function deprecate(fn: T, message: string): T; + function isDeepStrictEqual(val1: any, val2: any): boolean; + + interface CustomPromisify extends Function { + __promisify__: TCustom; + } + + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + + function promisify(fn: CustomPromisify): TCustom; + function promisify(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise; + function promisify(fn: (callback: (err?: Error) => void) => void): () => Promise; + function promisify(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, callback: (err?: Error) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: Error) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify(fn: Function): Function; + namespace promisify { const custom: unique symbol; } + namespace types { + function isAnyArrayBuffer(object: any): boolean; + function isArgumentsObject(object: any): object is IArguments; + function isArrayBuffer(object: any): object is ArrayBuffer; + function isArrayBufferView(object: any): object is ArrayBufferView; + function isAsyncFunction(object: any): boolean; function isBigInt64Array(value: any): value is BigInt64Array; function isBigUint64Array(value: any): value is BigUint64Array; + function isBooleanObject(object: any): object is Boolean; + function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); + function isDataView(object: any): object is DataView; + function isDate(object: any): object is Date; + function isExternal(object: any): boolean; + function isFloat32Array(object: any): object is Float32Array; + function isFloat64Array(object: any): object is Float64Array; + function isGeneratorFunction(object: any): boolean; + function isGeneratorObject(object: any): boolean; + function isInt8Array(object: any): object is Int8Array; + function isInt16Array(object: any): object is Int16Array; + function isInt32Array(object: any): object is Int32Array; + function isMap(object: any): boolean; + function isMapIterator(object: any): boolean; + function isModuleNamespaceObject(value: any): boolean; + function isNativeError(object: any): object is Error; + function isNumberObject(object: any): object is Number; + function isPromise(object: any): boolean; + function isProxy(object: any): boolean; + function isRegExp(object: any): object is RegExp; + function isSet(object: any): boolean; + function isSetIterator(object: any): boolean; + function isSharedArrayBuffer(object: any): boolean; + function isStringObject(object: any): boolean; + function isSymbolObject(object: any): boolean; + function isTypedArray(object: any): object is NodeJS.TypedArray; + function isUint8Array(object: any): object is Uint8Array; + function isUint8ClampedArray(object: any): object is Uint8ClampedArray; + function isUint16Array(object: any): object is Uint16Array; + function isUint32Array(object: any): object is Uint32Array; + function isWeakMap(object: any): boolean; + function isWeakSet(object: any): boolean; + function isWebAssemblyCompiledModule(object: any): boolean; + } + + class TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { fatal?: boolean; ignoreBOM?: boolean } + ); + decode( + input?: NodeJS.TypedArray | DataView | ArrayBuffer | null, + options?: { stream?: boolean } + ): string; + } + + class TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; } } diff --git a/types/node/v12/fs.d.ts b/types/node/v12/fs.d.ts index f0ae01b17c..4937c21684 100644 --- a/types/node/v12/fs.d.ts +++ b/types/node/v12/fs.d.ts @@ -1,7 +1,2461 @@ -// tslint:disable-next-line:no-bad-reference -/// +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + import { URL } from "url"; + + /** + * Valid types for path values in "fs". + */ + type PathLike = string | Buffer | URL; + + type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + + interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + interface Stats extends StatsBase { + } + + class Stats { + } + + class Dirent { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + name: string; + } + + /** + * A class representing a directory stream. + */ + class Dir { + readonly path: string; + + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + */ + close(): Promise; + close(cb: NoParamCallback): void; + + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + */ + closeSync(): void; + + /** + * Asynchronously read the next directory entry via `readdir(3)` as an `Dirent`. + * After the read is completed, a value is returned that will be resolved with an `Dirent`, or `null` if there are no more directory entries to read. + * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + + /** + * Synchronously read the next directory entry via `readdir(3)` as a `Dirent`. + * If there are no more directory entries to read, null will be returned. + * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. + */ + readSync(): Dirent; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + class ReadStream extends stream.Readable { + close(): void; + bytesRead: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + class WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function renameSync(oldPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function truncate(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + + /** + * Synchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncateSync(path: PathLike, len?: number | null): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + function ftruncate(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + + /** + * Synchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + + /** + * Synchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchownSync(fd: number, uid: number, gid: number): void; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(fd: number, mode: string | number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: string | number): Promise; + } + + /** + * Synchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmodSync(fd: number, mode: string | number): void; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike, options: BigIntOptions, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; + function stat(path: PathLike, options: StatOptions, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options: BigIntOptions): Promise; + function __promisify__(path: PathLike, options: StatOptions): Promise; + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function statSync(path: PathLike, options: BigIntOptions): BigIntStats; + function statSync(path: PathLike, options: StatOptions): Stats | BigIntStats; + function statSync(path: PathLike): Stats; + + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstatSync(fd: number): Stats; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstatSync(path: PathLike): Stats; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function linkSync(existingPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + + type Type = "dir" | "file" | "junction"; + } + + /** + * Synchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink( + path: PathLike, + options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void + ): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void + ): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + function native( + path: PathLike, + options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void + ): void; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + } + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + namespace realpathSync { + function native(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + function native(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + } + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlinkSync(path: PathLike): void; + + interface RmDirOptions { + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, errors are not reported if `path` does not exist, and + * operations are retried on failure. + * @experimental + * @default false + */ + recursive?: boolean; + } + + interface RmDirAsyncOptions extends RmDirOptions { + /** + * If an `EMFILE` error is encountered, Node.js will + * retry the operation with a linear backoff of 1ms longer on each try until the + * timeout duration passes this limit. This option is ignored if the `recursive` + * option is not `true`. + * @default 1000 + */ + emfileWait?: number; + /** + * If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error is + * encountered, Node.js will retry the operation with a linear backoff wait of + * 100ms longer on each try. This option represents the number of retries. This + * option is ignored if the `recursive` option is not `true`. + * @default 3 + */ + maxBusyTries?: number; + } + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike, callback: NoParamCallback): void; + function rmdir(path: PathLike, options: RmDirAsyncOptions, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirAsyncOptions): Promise; + } + + /** + * Synchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdirSync(path: PathLike, options?: RmDirOptions): void; + + interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * @default false + */ + recursive?: boolean; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777. + */ + mode?: number | string; + } + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options: number | string | MakeDirectoryOptions | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function mkdir(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; + } + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes: true }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Promise; + } + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdirSync(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Dirent[]; + + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function close(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function closeSync(fd: number): void; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise; + } + + /** + * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsync(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsyncSync(fd: number): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write( + fd: number, + string: any, + position: number | undefined | null, + encoding: string | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + */ + function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + } + + /** + * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; + + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; + + /** + * Asynchronously reads data from the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null + ): Promise<{ bytesRead: number, buffer: TBuffer }>; + } + + /** + * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: number | null): number; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | number, + options: { encoding?: string | null; flag?: string; } | string | undefined | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, + ): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise; + } + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; + + type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: NoParamCallback): void; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function writeFile(path: PathLike | number, data: any, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: NoParamCallback): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function appendFile(file: PathLike | number, data: any, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + */ + function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Stop watching for changes on `filename`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, + listener?: (event: string, filename: string) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, + listener?: (event: string, filename: string | Buffer) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; + + /** + * Asynchronously tests whether or not the given path exists by checking with the file system. + * @deprecated + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function exists(path: PathLike, callback: (exists: boolean) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronously tests whether or not the given path exists by checking with the file system. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function existsSync(path: PathLike): boolean; + + namespace constants { + // File Access Constants + + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + + // File Copy Constants + + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + 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. */ + 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). + */ + 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. */ + const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + 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. + */ + const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + 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. */ + const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + 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. */ + 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. */ + const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + 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. */ + const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + 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. */ + const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + 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. */ + const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + + /** + * Synchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function accessSync(path: PathLike, mode?: number): void; + + /** + * Returns a new `ReadStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createReadStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + /** + * @default false + */ + emitClose?: boolean; + start?: number; + end?: number; + highWaterMark?: number; + }): ReadStream; + + /** + * Returns a new `WriteStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createWriteStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + emitClose?: boolean; + start?: number; + highWaterMark?: number; + }): WriteStream; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasync(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasyncSync(fd: number): void; + + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + */ + function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace copyFile { + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, + * which causes the copy operation to fail if dest already exists. + */ + function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; + } + + /** + * Synchronously copies src to dest. By default, dest is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; + + /** + * Write an array of ArrayBufferViews to the file specified by fd using writev(). + * position is the offset from the beginning of the file where this data should be written. + * It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use fs.createWriteStream(). + * 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. + */ + function writev( + fd: number, + buffers: NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + function writev( + fd: number, + buffers: NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + + interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + + namespace writev { + function __promisify__(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): Promise; + } + + /** + * See `writev`. + */ + function writevSync(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): number; + + interface OpenDirOptions { + encoding?: BufferEncoding; + } + + function opendirSync(path: string, options?: OpenDirOptions): Dir; + + function opendir(path: string, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + function opendir(path: string, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + + namespace opendir { + function __promisify__(path: string, options?: OpenDirOptions): Promise; + } + + namespace promises { + interface FileHandle { + /** + * Gets the file descriptor for this file handle. + */ + readonly fd: number; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for appending. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + appendFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + */ + chown(uid: number, gid: number): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + chmod(mode: string | number): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + */ + datasync(): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + */ + sync(): Promise; + + /** + * Asynchronously reads data from the file. + * The `FileHandle` must have been opened for reading. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + read(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: null, flag?: string | number } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + */ + stat(): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param len If not specified, defaults to `0`. + */ + truncate(len?: number): Promise; + + /** + * Asynchronously change file timestamps of the file. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously writes `buffer` to the file. + * The `FileHandle` must have been opened for writing. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + write(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + write(data: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + writeFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * See `fs.writev` promisified version. + */ + writev(buffers: NodeJS.ArrayBufferView[], position?: number): Promise; + + /** + * Asynchronous close(2) - close a `FileHandle`. + */ + close(): Promise; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode?: number): Promise; + + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. The only + * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if + * `dest` already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not + * supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode?: string | number): Promise; + + /** + * Asynchronously reads data from the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If + * `null`, data will be read from the current position. + */ + function read( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write(handle: FileHandle, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len?: number): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param handle A `FileHandle`. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(handle: FileHandle, len?: number): Promise; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike, options?: RmDirAsyncOptions): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param handle A `FileHandle`. + */ + function fdatasync(handle: FileHandle): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param handle A `FileHandle`. + */ + function fsync(handle: FileHandle): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + * @param handle A `FileHandle`. + */ + function fstat(handle: FileHandle): Promise; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike): Promise; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike): Promise; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param handle A `FileHandle`. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(handle: FileHandle, mode: string | number): Promise; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number): Promise; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number): Promise; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param handle A `FileHandle`. + */ + function fchown(handle: FileHandle, uid: number, gid: number): Promise; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: string | number } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; + + function opendir(path: string, options?: OpenDirOptions): Promise; + } -declare module 'fs' { interface BigIntStats extends StatsBase { } @@ -19,15 +2473,4 @@ declare module 'fs' { interface StatOptions { bigint: boolean; } - - function stat(path: PathLike, options: BigIntOptions, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; - function stat(path: PathLike, options: StatOptions, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; - - namespace stat { - function __promisify__(path: PathLike, options: BigIntOptions): Promise; - function __promisify__(path: PathLike, options: StatOptions): Promise; - } - - function statSync(path: PathLike, options: BigIntOptions): BigIntStats; - function statSync(path: PathLike, options: StatOptions): Stats | BigIntStats; } diff --git a/types/node/v12/globals.d.ts b/types/node/v12/globals.d.ts index 56ad634485..1a4f1f32bc 100644 --- a/types/node/v12/globals.d.ts +++ b/types/node/v12/globals.d.ts @@ -1,13 +1,257 @@ -// tslint:disable-next-line:no-bad-reference -/// +// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build +interface Console { + Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ + warn(message?: any, ...optionalParams: any[]): void; -declare namespace NodeJS { - interface HRTime { - bigint(): bigint; - } + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * The console.markTimeline() method is the deprecated form of console.timeStamp(). + * + * @deprecated Use console.timeStamp() instead. + */ + markTimeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timeline() method is the deprecated form of console.time(). + * + * @deprecated Use console.time() instead. + */ + timeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timelineEnd() method is the deprecated form of console.timeEnd(). + * + * @deprecated Use console.timeEnd() instead. + */ + timelineEnd(label?: string): void; } -interface Buffer extends Uint8Array { +interface Error { + stack?: string; +} + +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + + stackTraceLimit: number; +} + +interface SymbolConstructor { + readonly observable: symbol; +} + +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; + + /** Returns a copy with leading whitespace removed. */ + trimStart(): string; + /** Returns a copy with trailing whitespace removed. */ + trimEnd(): string; +} + +interface ImportMeta { + url: string; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ +declare var process: NodeJS.Process; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T): Promise; +} +declare function clearTimeout(timeoutId: NodeJS.Timeout): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare function clearInterval(intervalId: NodeJS.Timeout): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; +declare namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T): Promise; +} +declare function clearImmediate(immediateId: NodeJS.Immediate): void; + +declare function queueMicrotask(callback: () => void): void; + +// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. +interface NodeRequireFunction { + /* tslint:disable-next-line:callable-types */ + (id: string): any; +} + +interface NodeRequireCache { + [path: string]: NodeModule; +} + +interface NodeRequire extends NodeRequireFunction { + resolve: RequireResolve; + cache: NodeRequireCache; + /** + * @deprecated + */ + extensions: NodeExtensions; + main: NodeModule | undefined; +} + +interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; +} + +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[]; + /** + * @since 11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"; + +interface Buffer { + constructor: typeof Buffer; readBigUInt64BE(offset?: number): bigint; readBigUInt64LE(offset?: number): bigint; readBigInt64BE(offset?: number): bigint; @@ -17,3 +261,939 @@ interface Buffer extends Uint8Array { writeBigUInt64BE(value: bigint, offset?: number): number; writeBigUInt64LE(value: bigint, offset?: number): number; } + +/** + * 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 class Buffer extends Uint8Array { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + constructor(str: string, encoding?: BufferEncoding); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + constructor(size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + constructor(array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + constructor(arrayBuffer: ArrayBuffer | SharedArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + constructor(array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + constructor(buffer: 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 any TypedArray or a new ArrayBuffer() + */ + static from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + static from(data: number[]): Buffer; + static from(data: Uint8Array): Buffer; + /** + * Creates a new buffer containing the coerced value of an object + * A `TypeError` will be thrown if {obj} has not mentioned methods or is not of other type appropriate for `Buffer.from()` variants. + * @param obj An object supporting `Symbol.toPrimitive` or `valueOf()`. + */ + static from(obj: { valueOf(): string | object } | { [Symbol.toPrimitive](hint: 'string'): string }, byteOffset?: number, length?: number): 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'. + */ + static from(str: string, encoding?: BufferEncoding): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + static of(...items: number[]): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static 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. + */ + static isEncoding(encoding: string): encoding is BufferEncoding; + /** + * 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 | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding + ): 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: Uint8Array[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Uint8Array, buf2: Uint8Array): 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 + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): 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 + */ + static 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 + */ + static allocUnsafeSlow(size: number): Buffer; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + static poolSize: number; + + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer'; data: number[] }; + equals(otherBuffer: Uint8Array): boolean; + compare( + otherBuffer: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number + ): number; + copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. + * + * This method is incompatible with `Uint8Array#slice()`, which returns a copy of the original memory. + * + * @param begin Where the new `Buffer` will start. Default: `0`. + * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. + */ + slice(begin?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. + * + * This method is compatible with `Uint8Array#subarray()`. + * + * @param begin Where the new `Buffer` will start. Default: `0`. + * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. + */ + subarray(begin?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number): number; + writeUIntBE(value: number, offset: number, byteLength: number): number; + writeIntLE(value: number, offset: number, byteLength: number): number; + writeIntBE(value: number, offset: number, byteLength: number): number; + readUIntLE(offset: number, byteLength: number): number; + readUIntBE(offset: number, byteLength: number): number; + readIntLE(offset: number, byteLength: number): number; + readIntBE(offset: number, byteLength: number): number; + readUInt8(offset: number): number; + readUInt16LE(offset: number): number; + readUInt16BE(offset: number): number; + readUInt32LE(offset: number): number; + readUInt32BE(offset: number): number; + readInt8(offset: number): number; + readInt16LE(offset: number): number; + readInt16BE(offset: number): number; + readInt32LE(offset: number): number; + readInt32BE(offset: number): number; + readFloatLE(offset: number): number; + readFloatBE(offset: number): number; + readDoubleLE(offset: number): number; + readDoubleBE(offset: number): number; + reverse(): this; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number): number; + writeUInt16LE(value: number, offset: number): number; + writeUInt16BE(value: number, offset: number): number; + writeUInt32LE(value: number, offset: number): number; + writeUInt32BE(value: number, offset: number): number; + writeInt8(value: number, offset: number): number; + writeInt16LE(value: number, offset: number): number; + writeInt16BE(value: number, offset: number): number; + writeInt32LE(value: number, offset: number): number; + writeInt32BE(value: number, offset: number): number; + writeFloatLE(value: number, offset: number): number; + writeFloatBE(value: number, offset: number): number; + writeDoubleLE(value: number, offset: number): number; + writeDoubleBE(value: number, offset: number): number; + + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean; + showHidden?: boolean; + /** + * @default 2 + */ + depth?: number | null; + colors?: boolean; + customInspect?: boolean; + showProxy?: boolean; + maxArrayLength?: number | null; + breakLength?: number; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default `true` + */ + compact?: boolean | number; + sorted?: boolean | ((a: string, b: string) => number); + } + + interface ConsoleConstructorOptions { + stdout: WritableStream; + stderr?: WritableStream; + ignoreErrors?: boolean; + colorMode?: boolean | 'auto'; + inspectOptions?: InspectOptions; + } + + interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + + interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + class EventEmitter { + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(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: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + eventNames(): Array; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: string, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): void; + end(data: string | Uint8Array, cb?: () => void): void; + end(str: string, encoding?: string, cb?: () => void): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface Domain extends EventEmitter { + run(fn: (...args: any[]) => T, ...args: any[]): T; + add(emitter: EventEmitter | Timer): void; + remove(emitter: EventEmitter | Timer): void; + bind(cb: T): T; + intercept(cb: T): T; + + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + } + + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + } + + interface CpuUsage { + user: number; + system: number; + } + + interface ProcessRelease { + name: string; + sourceUrl?: string; + headersUrl?: string; + libUrl?: string; + lts?: string; + } + + interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | 'cygwin' + | 'netbsd'; + + type Signals = + "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | + "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | + "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type MultipleResolveType = 'resolve' | 'reject'; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = (signal: Signals) => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; + + interface Socket extends ReadWriteStream { + isTTY?: true; + } + + interface ProcessEnv { + [key: string]: string | undefined; + } + + interface HRTime { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @defaul false + */ + reportOnSignal: boolean; + + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + + interface Process extends EventEmitter { + /** + * Can also be a tty.WriteStream, not typed due to limitation.s + */ + stdout: WriteStream; + /** + * Can also be a tty.WriteStream, not typed due to limitation.s + */ + stderr: WriteStream; + stdin: ReadStream; + openStdin(): Socket; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + debugPort: number; + emitWarning(warning: string | Error, name?: string, ctor?: Function): void; + env: ProcessEnv; + exit(code?: number): never; + exitCode?: number; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: Array): void; + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + hasUncaughtExceptionCaptureCallback(): boolean; + 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): true; + pid: number; + ppid: number; + title: string; + arch: string; + platform: Platform; + mainModule?: NodeModule; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * Can only be set if not in worker thread. + */ + umask(mask?: number): number; + uptime(): number; + hrtime: HRTime; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; + disconnect(): void; + connected: boolean; + + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] + * environment variable. + */ + allowedNodeEnvironmentFlags: ReadonlySet; + + /** + * Only available with `--experimental-report` + */ + report?: ProcessReport; + + resourceUsage(): ResourceUsage; + + /** + * EventEmitter + * 1. beforeExit + * 2. disconnect + * 3. exit + * 4. message + * 5. rejectionHandled + * 6. uncaughtException + * 7. unhandledRejection + * 8. warning + * 9. message + * 10. + * 11. newListener/removeListener inherited from EventEmitter + */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; + + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + } + + 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: Immediate) => void; + clearInterval: (intervalId: Timeout) => void; + clearTimeout: (timeoutId: Timeout) => 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[]) => Immediate; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + queueMicrotask: typeof queueMicrotask; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + // compatibility with older typings + interface Timer { + hasRef(): boolean; + ref(): this; + refresh(): this; + unref(): this; + } + + class Immediate { + hasRef(): boolean; + ref(): this; + unref(): this; + _onImmediate: Function; // to distinguish it from the Timeout class + } + + class Timeout implements Timer { + hasRef(): boolean; + ref(): this; + refresh(): this; + unref(): this; + } + + class Module { + static runMain(): void; + static wrap(code: string): string; + + /** + * @deprecated Deprecated since: v12.2.0. Please use createRequire() instead. + */ + static createRequireFromPath(path: string): NodeRequire; + static createRequire(path: string): NodeRequire; + static builtinModules: string[]; + + static Module: typeof Module; + + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: Module | null; + children: Module[]; + /** + * @since 11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + + constructor(id: string, parent?: Module); + } + + type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + // TODO: The value type here is a version of `unknown` with an acceptably lossy amount of accuracy. + // Now that TypeScript's DT support is 3.0+, we can look into replacing this with `unknown`. + type UnknownFacade = {} | null | undefined; + + /** @deprecated - Use `UnknownFacade` instead. It is a better classifier for the type */ + type PoorMansUnknown = UnknownFacade; +} diff --git a/types/node/v12/package.json b/types/node/v12/package.json index 101c324555..8071fb8e8f 100644 --- a/types/node/v12/package.json +++ b/types/node/v12/package.json @@ -2,11 +2,6 @@ "private": true, "types": "index", "typesVersions": { - "<=3.1": { - "*": [ - "ts3.1/*" - ] - }, "<=3.3": { "*": [ "ts3.3/*" diff --git a/types/node/v12/ts3.1/base.d.ts b/types/node/v12/ts3.1/base.d.ts deleted file mode 100644 index 1be74c9f1b..0000000000 --- a/types/node/v12/ts3.1/base.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -// base definitions for all NodeJS modules that are not specific to any version of TypeScript -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// diff --git a/types/node/v12/ts3.1/fs.d.ts b/types/node/v12/ts3.1/fs.d.ts deleted file mode 100644 index 4557959fbe..0000000000 --- a/types/node/v12/ts3.1/fs.d.ts +++ /dev/null @@ -1,2452 +0,0 @@ -declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; - import { URL } from "url"; - - /** - * Valid types for path values in "fs". - */ - type PathLike = string | Buffer | URL; - - type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; - - interface StatsBase { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - - dev: T; - ino: T; - mode: T; - nlink: T; - uid: T; - gid: T; - rdev: T; - size: T; - blksize: T; - blocks: T; - atimeMs: T; - mtimeMs: T; - ctimeMs: T; - birthtimeMs: T; - atime: Date; - mtime: Date; - ctime: Date; - birthtime: Date; - } - - interface Stats extends StatsBase { - } - - class Stats { - } - - class Dirent { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - name: string; - } - - /** - * A class representing a directory stream. - */ - class Dir { - readonly path: string; - - /** - * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. - */ - [Symbol.asyncIterator](): AsyncIterableIterator; - - /** - * Asynchronously close the directory's underlying resource handle. - * Subsequent reads will result in errors. - */ - close(): Promise; - close(cb: NoParamCallback): void; - - /** - * Synchronously close the directory's underlying resource handle. - * Subsequent reads will result in errors. - */ - closeSync(): void; - - /** - * Asynchronously read the next directory entry via `readdir(3)` as an `Dirent`. - * After the read is completed, a value is returned that will be resolved with an `Dirent`, or `null` if there are no more directory entries to read. - * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. - */ - read(): Promise; - read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; - - /** - * Synchronously read the next directory entry via `readdir(3)` as a `Dirent`. - * If there are no more directory entries to read, null will be returned. - * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. - */ - readSync(): Dirent; - } - - interface FSWatcher extends events.EventEmitter { - close(): void; - - /** - * events.EventEmitter - * 1. change - * 2. error - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } - - class ReadStream extends stream.Readable { - close(): void; - bytesRead: number; - path: string | Buffer; - - /** - * events.EventEmitter - * 1. open - * 2. close - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } - - class WriteStream extends stream.Writable { - close(): void; - bytesWritten: number; - path: string | Buffer; - - /** - * events.EventEmitter - * 1. open - * 2. close - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } - - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace rename { - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; - } - - /** - * Synchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function renameSync(oldPath: PathLike, newPath: PathLike): void; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function truncate(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace truncate { - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function __promisify__(path: PathLike, len?: number | null): Promise; - } - - /** - * Synchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function truncateSync(path: PathLike, len?: number | null): void; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - */ - function ftruncate(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace ftruncate { - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - function __promisify__(fd: number, len?: number | null): Promise; - } - - /** - * Synchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - function ftruncateSync(fd: number, len?: number | null): void; - - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace chown { - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - - /** - * Synchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function chownSync(path: PathLike, uid: number, gid: number): void; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fchown { - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - function __promisify__(fd: number, uid: number, gid: number): Promise; - } - - /** - * Synchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - function fchownSync(fd: number, uid: number, gid: number): void; - - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace lchown { - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - - /** - * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lchownSync(path: PathLike, uid: number, gid: number): void; - - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function chmod(path: PathLike, mode: string | number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace chmod { - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(path: PathLike, mode: string | number): Promise; - } - - /** - * Synchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function chmodSync(path: PathLike, mode: string | number): void; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function fchmod(fd: number, mode: string | number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fchmod { - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(fd: number, mode: string | number): Promise; - } - - /** - * Synchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function fchmodSync(fd: number, mode: string | number): void; - - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function lchmod(path: PathLike, mode: string | number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace lchmod { - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(path: PathLike, mode: string | number): Promise; - } - - /** - * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function lchmodSync(path: PathLike, mode: string | number): void; - - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace stat { - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function statSync(path: PathLike): Stats; - - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fstat { - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - function fstatSync(fd: number): Stats; - - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace lstat { - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lstatSync(path: PathLike): Stats; - - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace link { - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; - } - - /** - * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function linkSync(existingPath: PathLike, newPath: PathLike): void; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - */ - function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace symlink { - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; - - type Type = "dir" | "file" | "junction"; - } - - /** - * Synchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink( - path: PathLike, - options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, linkString: string) => void - ): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace readlink { - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - } - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath( - path: PathLike, - options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void - ): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace realpath { - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - - function native( - path: PathLike, - options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void - ): void; - function native(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - function native(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; - function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; - } - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; - - namespace realpathSync { - function native(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - function native(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; - function native(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; - } - - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function unlink(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace unlink { - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function unlinkSync(path: PathLike): void; - - interface RmDirOptions { - /** - * If `true`, perform a recursive directory removal. In - * recursive mode, errors are not reported if `path` does not exist, and - * operations are retried on failure. - * @experimental - * @default false - */ - recursive?: boolean; - } - - interface RmDirAsyncOptions extends RmDirOptions { - /** - * If an `EMFILE` error is encountered, Node.js will - * retry the operation with a linear backoff of 1ms longer on each try until the - * timeout duration passes this limit. This option is ignored if the `recursive` - * option is not `true`. - * @default 1000 - */ - emfileWait?: number; - /** - * If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error is - * encountered, Node.js will retry the operation with a linear backoff wait of - * 100ms longer on each try. This option represents the number of retries. This - * option is ignored if the `recursive` option is not `true`. - * @default 3 - */ - maxBusyTries?: number; - } - - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function rmdir(path: PathLike, callback: NoParamCallback): void; - function rmdir(path: PathLike, options: RmDirAsyncOptions, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace rmdir { - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, options?: RmDirAsyncOptions): Promise; - } - - /** - * Synchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function rmdirSync(path: PathLike, options?: RmDirOptions): void; - - interface MakeDirectoryOptions { - /** - * Indicates whether parent folders should be created. - * @default false - */ - recursive?: boolean; - /** - * A file mode. If a string is passed, it is parsed as an octal integer. If not specified - * @default 0o777. - */ - mode?: number | string; - } - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options: number | string | MakeDirectoryOptions | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function mkdir(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace mkdir { - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; - } - - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - */ - function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace mkdtemp { - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise; - } - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir( - path: PathLike, - options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, - ): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir( - path: PathLike, - options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, - callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, - ): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes: true }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace readdir { - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent - */ - function __promisify__(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Promise; - } - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - function readdirSync(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Dirent[]; - - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - function close(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace close { - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - function closeSync(fd: number): void; - - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - - /** - * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace open { - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise; - } - - /** - * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace utimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; - } - - /** - * Synchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace futimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; - } - - /** - * Synchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - function fsync(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fsync { - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - function fsyncSync(fd: number): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - position: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - */ - function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - */ - function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - */ - function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function write( - fd: number, - string: any, - position: number | undefined | null, - encoding: string | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, - ): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - */ - function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace write { - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function __promisify__( - fd: number, - buffer?: TBuffer, - offset?: number, - length?: number, - position?: number | null, - ): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; - } - - /** - * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; - - /** - * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; - - /** - * Asynchronously reads data from the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - function read( - fd: number, - buffer: TBuffer, - offset: number, - length: number, - position: number | null, - callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, - ): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace read { - /** - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - function __promisify__( - fd: number, - buffer: TBuffer, - offset: number, - length: number, - position: number | null - ): Promise<{ bytesRead: number, buffer: TBuffer }>; - } - - /** - * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: number | null): number; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile( - path: PathLike | number, - options: { encoding?: string | null; flag?: string; } | string | undefined | null, - callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, - ): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - */ - function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace readFile { - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise; - } - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. - */ - function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; - - type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: NoParamCallback): void; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - function writeFile(path: PathLike | number, data: any, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace writeFile { - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise; - } - - /** - * Synchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: NoParamCallback): void; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - function appendFile(file: PathLike | number, data: any, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace appendFile { - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise; - } - - /** - * Synchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; - - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - */ - function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; - - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; - - /** - * Stop watching for changes on `filename`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - function watch( - filename: PathLike, - options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, - listener?: (event: string, filename: string) => void, - ): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - function watch( - filename: PathLike, - options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, - listener?: (event: string, filename: string | Buffer) => void, - ): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; - - /** - * Asynchronously tests whether or not the given path exists by checking with the file system. - * @deprecated - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function exists(path: PathLike, callback: (exists: boolean) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace exists { - /** - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronously tests whether or not the given path exists by checking with the file system. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function existsSync(path: PathLike): boolean; - - namespace constants { - // File Access Constants - - /** Constant for fs.access(). File is visible to the calling process. */ - const F_OK: number; - - /** Constant for fs.access(). File can be read by the calling process. */ - const R_OK: number; - - /** Constant for fs.access(). File can be written by the calling process. */ - const W_OK: number; - - /** Constant for fs.access(). File can be executed by the calling process. */ - const X_OK: number; - - // File Copy Constants - - /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ - const COPYFILE_EXCL: number; - - /** - * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. - * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. - */ - const COPYFILE_FICLONE: number; - - /** - * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. - * If the underlying platform does not support copy-on-write, then the operation will fail with an error. - */ - const COPYFILE_FICLONE_FORCE: number; - - // File Open Constants - - /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ - const O_RDONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ - const O_WRONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ - const O_RDWR: number; - - /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ - 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. */ - 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). - */ - 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. */ - const O_TRUNC: number; - - /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ - const O_APPEND: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ - 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. - */ - const O_NOATIME: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ - const O_NOFOLLOW: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ - const O_SYNC: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ - const O_DSYNC: number; - - /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ - const O_SYMLINK: number; - - /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ - const O_DIRECT: number; - - /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ - 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. */ - const S_IFMT: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ - const S_IFREG: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ - 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. */ - 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. */ - const S_IFBLK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ - const S_IFIFO: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ - const S_IFLNK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ - 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. */ - const S_IRWXU: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ - const S_IRUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ - const S_IWUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ - 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. */ - const S_IRWXG: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ - const S_IRGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ - const S_IWGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ - 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. */ - const S_IRWXO: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ - const S_IROTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ - const S_IWOTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ - const S_IXOTH: number; - - /** - * When set, a memory file mapping is used to access the file. This flag - * is available on Windows operating systems only. On other operating systems, - * this flag is ignored. - */ - const UV_FS_O_FILEMAP: number; - } - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function access(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace access { - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike, mode?: number): Promise; - } - - /** - * Synchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function accessSync(path: PathLike, mode?: number): void; - - /** - * Returns a new `ReadStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function createReadStream(path: PathLike, options?: string | { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - /** - * @default false - */ - emitClose?: boolean; - start?: number; - end?: number; - highWaterMark?: number; - }): ReadStream; - - /** - * Returns a new `WriteStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function createWriteStream(path: PathLike, options?: string | { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - emitClose?: boolean; - start?: number; - highWaterMark?: number; - }): WriteStream; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - function fdatasync(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fdatasync { - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - function fdatasyncSync(fd: number): void; - - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - */ - function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - function copyFile(src: PathLike, dest: PathLike, flags: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace copyFile { - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. - * The only supported flag is fs.constants.COPYFILE_EXCL, - * which causes the copy operation to fail if dest already exists. - */ - function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; - } - - /** - * Synchronously copies src to dest. By default, dest is overwritten if it already exists. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. - * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; - - /** - * Write an array of ArrayBufferViews to the file specified by fd using writev(). - * position is the offset from the beginning of the file where this data should be written. - * It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use fs.createWriteStream(). - * 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. - */ - function writev( - fd: number, - buffers: NodeJS.ArrayBufferView[], - cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - function writev( - fd: number, - buffers: NodeJS.ArrayBufferView[], - position: number, - cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - - interface WriteVResult { - bytesWritten: number; - buffers: NodeJS.ArrayBufferView[]; - } - - namespace writev { - function __promisify__(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): Promise; - } - - /** - * See `writev`. - */ - function writevSync(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): number; - - interface OpenDirOptions { - encoding?: BufferEncoding; - } - - function opendirSync(path: string, options?: OpenDirOptions): Dir; - - function opendir(path: string, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; - function opendir(path: string, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; - - namespace opendir { - function __promisify__(path: string, options?: OpenDirOptions): Promise; - } - - namespace promises { - interface FileHandle { - /** - * Gets the file descriptor for this file handle. - */ - readonly fd: number; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for appending. - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - appendFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - */ - chown(uid: number, gid: number): Promise; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - chmod(mode: string | number): Promise; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - */ - datasync(): Promise; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - */ - sync(): Promise; - - /** - * Asynchronously reads data from the file. - * The `FileHandle` must have been opened for reading. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - read(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; - - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile(options?: { encoding?: null, flag?: string | number } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile(options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; - - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile(options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; - - /** - * Asynchronous fstat(2) - Get file status. - */ - stat(): Promise; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param len If not specified, defaults to `0`. - */ - truncate(len?: number): Promise; - - /** - * Asynchronously change file timestamps of the file. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - utimes(atime: string | number | Date, mtime: string | number | Date): Promise; - - /** - * Asynchronously writes `buffer` to the file. - * The `FileHandle` must have been opened for writing. - * @param buffer The buffer that the data will be written to. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - write(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file. - * The `FileHandle` must have been opened for writing. - * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` - * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - write(data: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for writing. - * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - writeFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; - - /** - * See `fs.writev` promisified version. - */ - writev(buffers: NodeJS.ArrayBufferView[], position?: number): Promise; - - /** - * Asynchronous close(2) - close a `FileHandle`. - */ - close(): Promise; - } - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function access(path: PathLike, mode?: number): Promise; - - /** - * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. The only - * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if - * `dest` already exists. - */ - function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise; - - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not - * supplied, defaults to `0o666`. - */ - function open(path: PathLike, flags: string | number, mode?: string | number): Promise; - - /** - * Asynchronously reads data from the file referenced by the supplied `FileHandle`. - * @param handle A `FileHandle`. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If - * `null`, data will be read from the current position. - */ - function read( - handle: FileHandle, - buffer: TBuffer, - offset?: number | null, - length?: number | null, - position?: number | null, - ): Promise<{ bytesRead: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. - * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` - * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. - * @param handle A `FileHandle`. - * @param buffer The buffer that the data will be written to. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function write( - handle: FileHandle, - buffer: TBuffer, - offset?: number | null, - length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. - * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` - * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. - * @param handle A `FileHandle`. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function write(handle: FileHandle, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; - - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function rename(oldPath: PathLike, newPath: PathLike): Promise; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function truncate(path: PathLike, len?: number): Promise; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param handle A `FileHandle`. - * @param len If not specified, defaults to `0`. - */ - function ftruncate(handle: FileHandle, len?: number): Promise; - - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function rmdir(path: PathLike, options?: RmDirAsyncOptions): Promise; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param handle A `FileHandle`. - */ - function fdatasync(handle: FileHandle): Promise; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param handle A `FileHandle`. - */ - function fsync(handle: FileHandle): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options?: { encoding?: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; - - /** - * Asynchronous fstat(2) - Get file status. - * @param handle A `FileHandle`. - */ - function fstat(handle: FileHandle): Promise; - - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lstat(path: PathLike): Promise; - - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function stat(path: PathLike): Promise; - - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function link(existingPath: PathLike, newPath: PathLike): Promise; - - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function unlink(path: PathLike): Promise; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param handle A `FileHandle`. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function fchmod(handle: FileHandle, mode: string | number): Promise; - - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function chmod(path: PathLike, mode: string | number): Promise; - - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function lchmod(path: PathLike, mode: string | number): Promise; - - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lchown(path: PathLike, uid: number, gid: number): Promise; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param handle A `FileHandle`. - */ - function fchown(handle: FileHandle, uid: number, gid: number): Promise; - - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function chown(path: PathLike, uid: number, gid: number): Promise; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. - * @param handle A `FileHandle`. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options?: { encoding?: string | null } | string | null): Promise; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function writeFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function appendFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: string | number } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | FileHandle, options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; - - function opendir(path: string, options?: OpenDirOptions): Promise; - } -} diff --git a/types/node/v12/ts3.1/globals.d.ts b/types/node/v12/ts3.1/globals.d.ts deleted file mode 100644 index d329735d86..0000000000 --- a/types/node/v12/ts3.1/globals.d.ts +++ /dev/null @@ -1,1190 +0,0 @@ -// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build -interface Console { - Console: NodeJS.ConsoleConstructor; - /** - * A simple assertion test that verifies whether `value` is truthy. - * If it is not, an `AssertionError` is thrown. - * If provided, the error `message` is formatted using `util.format()` and used as the error message. - */ - assert(value: any, message?: string, ...optionalParams: any[]): void; - /** - * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. - * When `stdout` is not a TTY, this method does nothing. - */ - clear(): void; - /** - * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. - */ - count(label?: string): void; - /** - * Resets the internal counter specific to `label`. - */ - countReset(label?: string): void; - /** - * The `console.debug()` function is an alias for {@link console.log()}. - */ - debug(message?: any, ...optionalParams: any[]): void; - /** - * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. - * This function bypasses any custom `inspect()` function defined on `obj`. - */ - dir(obj: any, options?: NodeJS.InspectOptions): void; - /** - * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting - */ - dirxml(...data: any[]): void; - /** - * Prints to `stderr` with newline. - */ - error(message?: any, ...optionalParams: any[]): void; - /** - * Increases indentation of subsequent lines by two spaces. - * If one or more `label`s are provided, those are printed first without the additional indentation. - */ - group(...label: any[]): void; - /** - * The `console.groupCollapsed()` function is an alias for {@link console.group()}. - */ - groupCollapsed(...label: any[]): void; - /** - * Decreases indentation of subsequent lines by two spaces. - */ - groupEnd(): void; - /** - * The {@link console.info()} function is an alias for {@link console.log()}. - */ - info(message?: any, ...optionalParams: any[]): void; - /** - * Prints to `stdout` with newline. - */ - log(message?: any, ...optionalParams: any[]): void; - /** - * This method does not display anything unless used in the inspector. - * Prints to `stdout` the array `array` formatted as a table. - */ - table(tabularData: any, properties?: string[]): void; - /** - * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. - */ - time(label?: string): void; - /** - * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. - */ - timeEnd(label?: string): void; - /** - * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. - */ - timeLog(label?: string, ...data: any[]): void; - /** - * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. - */ - trace(message?: any, ...optionalParams: any[]): void; - /** - * The {@link console.warn()} function is an alias for {@link console.error()}. - */ - warn(message?: any, ...optionalParams: any[]): void; - - // --- Inspector mode only --- - /** - * This method does not display anything unless used in the inspector. - * The console.markTimeline() method is the deprecated form of console.timeStamp(). - * - * @deprecated Use console.timeStamp() instead. - */ - markTimeline(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Starts a JavaScript CPU profile with an optional label. - */ - profile(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. - */ - profileEnd(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Adds an event with the label `label` to the Timeline panel of the inspector. - */ - timeStamp(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * The console.timeline() method is the deprecated form of console.time(). - * - * @deprecated Use console.time() instead. - */ - timeline(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * The console.timelineEnd() method is the deprecated form of console.timeEnd(). - * - * @deprecated Use console.timeEnd() instead. - */ - timelineEnd(label?: string): void; -} - -interface Error { - stack?: string; -} - -// Declare "static" methods in Error -interface ErrorConstructor { - /** Create .stack property on a target object */ - captureStackTrace(targetObject: Object, constructorOpt?: Function): void; - - /** - * Optional override for formatting stack traces - * - * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces - */ - prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; - - stackTraceLimit: number; -} - -interface SymbolConstructor { - readonly observable: symbol; -} - -// Node.js ESNEXT support -interface String { - /** Removes whitespace from the left end of a string. */ - trimLeft(): string; - /** Removes whitespace from the right end of a string. */ - trimRight(): string; - - /** Returns a copy with leading whitespace removed. */ - trimStart(): string; - /** Returns a copy with trailing whitespace removed. */ - trimEnd(): string; -} - -interface ImportMeta { - url: string; -} - -/*-----------------------------------------------* - * * - * GLOBAL * - * * - ------------------------------------------------*/ -declare var process: NodeJS.Process; -declare var console: Console; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare namespace setTimeout { - function __promisify__(ms: number): Promise; - function __promisify__(ms: number, value: T): Promise; -} -declare function clearTimeout(timeoutId: NodeJS.Timeout): void; -declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare function clearInterval(intervalId: NodeJS.Timeout): void; -declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; -declare namespace setImmediate { - function __promisify__(): Promise; - function __promisify__(value: T): Promise; -} -declare function clearImmediate(immediateId: NodeJS.Immediate): void; - -declare function queueMicrotask(callback: () => void): void; - -// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. -interface NodeRequireFunction { - /* tslint:disable-next-line:callable-types */ - (id: string): any; -} - -interface NodeRequireCache { - [path: string]: NodeModule; -} - -interface NodeRequire extends NodeRequireFunction { - resolve: RequireResolve; - cache: NodeRequireCache; - /** - * @deprecated - */ - extensions: NodeExtensions; - main: NodeModule | undefined; -} - -interface RequireResolve { - (id: string, options?: { paths?: string[]; }): string; - paths(request: string): string[] | null; -} - -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[]; - /** - * @since 11.14.0 - * - * The directory name of the module. This is usually the same as the path.dirname() of the module.id. - */ - path: string; - paths: string[]; -} - -declare var module: NodeModule; - -// Same as module.exports -declare var exports: any; - -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"; - -interface Buffer { - constructor: typeof Buffer; -} - -/** - * 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 class Buffer extends Uint8Array { - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. - */ - constructor(str: string, encoding?: BufferEncoding); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). - */ - constructor(size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - constructor(array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}/{SharedArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. - */ - constructor(arrayBuffer: ArrayBuffer | SharedArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - constructor(array: any[]); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. - */ - constructor(buffer: 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 any TypedArray or a new ArrayBuffer() - */ - static from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param data data to create a new Buffer - */ - static from(data: number[]): Buffer; - static from(data: Uint8Array): Buffer; - /** - * Creates a new buffer containing the coerced value of an object - * A `TypeError` will be thrown if {obj} has not mentioned methods or is not of other type appropriate for `Buffer.from()` variants. - * @param obj An object supporting `Symbol.toPrimitive` or `valueOf()`. - */ - static from(obj: { valueOf(): string | object } | { [Symbol.toPrimitive](hint: 'string'): string }, byteOffset?: number, length?: number): 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'. - */ - static from(str: string, encoding?: BufferEncoding): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param values to create a new Buffer - */ - static of(...items: number[]): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - static 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. - */ - static isEncoding(encoding: string): encoding is BufferEncoding; - /** - * 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 | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, - encoding?: BufferEncoding - ): 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: Uint8Array[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - static compare(buf1: Uint8Array, buf2: Uint8Array): 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 - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): 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 - */ - static 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 - */ - static allocUnsafeSlow(size: number): Buffer; - /** - * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. - */ - static poolSize: number; - - write(string: string, encoding?: BufferEncoding): number; - write(string: string, offset: number, encoding?: BufferEncoding): number; - write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer'; data: number[] }; - equals(otherBuffer: Uint8Array): boolean; - compare( - otherBuffer: Uint8Array, - targetStart?: number, - targetEnd?: number, - sourceStart?: number, - sourceEnd?: number - ): number; - copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - /** - * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. - * - * This method is incompatible with `Uint8Array#slice()`, which returns a copy of the original memory. - * - * @param begin Where the new `Buffer` will start. Default: `0`. - * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. - */ - slice(begin?: number, end?: number): Buffer; - /** - * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. - * - * This method is compatible with `Uint8Array#subarray()`. - * - * @param begin Where the new `Buffer` will start. Default: `0`. - * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. - */ - subarray(begin?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number): number; - writeUIntBE(value: number, offset: number, byteLength: number): number; - writeIntLE(value: number, offset: number, byteLength: number): number; - writeIntBE(value: number, offset: number, byteLength: number): number; - readUIntLE(offset: number, byteLength: number): number; - readUIntBE(offset: number, byteLength: number): number; - readIntLE(offset: number, byteLength: number): number; - readIntBE(offset: number, byteLength: number): number; - readUInt8(offset: number): number; - readUInt16LE(offset: number): number; - readUInt16BE(offset: number): number; - readUInt32LE(offset: number): number; - readUInt32BE(offset: number): number; - readInt8(offset: number): number; - readInt16LE(offset: number): number; - readInt16BE(offset: number): number; - readInt32LE(offset: number): number; - readInt32BE(offset: number): number; - readFloatLE(offset: number): number; - readFloatBE(offset: number): number; - readDoubleLE(offset: number): number; - readDoubleBE(offset: number): number; - reverse(): this; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number): number; - writeUInt16LE(value: number, offset: number): number; - writeUInt16BE(value: number, offset: number): number; - writeUInt32LE(value: number, offset: number): number; - writeUInt32BE(value: number, offset: number): number; - writeInt8(value: number, offset: number): number; - writeInt16LE(value: number, offset: number): number; - writeInt16BE(value: number, offset: number): number; - writeInt32LE(value: number, offset: number): number; - writeInt32BE(value: number, offset: number): number; - writeFloatLE(value: number, offset: number): number; - writeFloatBE(value: number, offset: number): number; - writeDoubleLE(value: number, offset: number): number; - writeDoubleBE(value: number, offset: number): number; - - fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; - - indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; - lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; - keys(): IterableIterator; - values(): IterableIterator; -} - -/*----------------------------------------------* -* * -* GLOBAL INTERFACES * -* * -*-----------------------------------------------*/ -declare namespace NodeJS { - interface InspectOptions { - /** - * If set to `true`, getters are going to be - * inspected as well. If set to `'get'` only getters without setter are going - * to be inspected. If set to `'set'` only getters having a corresponding - * setter are going to be inspected. This might cause side effects depending on - * the getter function. - * @default `false` - */ - getters?: 'get' | 'set' | boolean; - showHidden?: boolean; - /** - * @default 2 - */ - depth?: number | null; - colors?: boolean; - customInspect?: boolean; - showProxy?: boolean; - maxArrayLength?: number | null; - breakLength?: number; - /** - * Setting this to `false` causes each object key - * to be displayed on a new line. It will also add new lines to text that is - * longer than `breakLength`. If set to a number, the most `n` inner elements - * are united on a single line as long as all properties fit into - * `breakLength`. Short array elements are also grouped together. Note that no - * text will be reduced below 16 characters, no matter the `breakLength` size. - * For more information, see the example below. - * @default `true` - */ - compact?: boolean | number; - sorted?: boolean | ((a: string, b: string) => number); - } - - interface ConsoleConstructorOptions { - stdout: WritableStream; - stderr?: WritableStream; - ignoreErrors?: boolean; - colorMode?: boolean | 'auto'; - inspectOptions?: InspectOptions; - } - - interface ConsoleConstructor { - prototype: Console; - new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; - new(options: ConsoleConstructorOptions): Console; - } - - interface CallSite { - /** - * Value of "this" - */ - getThis(): any; - - /** - * Type of "this" as a string. - * This is the name of the function stored in the constructor field of - * "this", if available. Otherwise the object's [[Class]] internal - * property. - */ - getTypeName(): string | null; - - /** - * Current function - */ - getFunction(): Function | undefined; - - /** - * Name of the current function, typically its name property. - * If a name property is not available an attempt will be made to try - * to infer a name from the function's context. - */ - getFunctionName(): string | null; - - /** - * Name of the property [of "this" or one of its prototypes] that holds - * the current function - */ - getMethodName(): string | null; - - /** - * Name of the script [if this function was defined in a script] - */ - getFileName(): string | null; - - /** - * Current line number [if this function was defined in a script] - */ - getLineNumber(): number | null; - - /** - * Current column number [if this function was defined in a script] - */ - getColumnNumber(): number | null; - - /** - * A call site object representing the location where eval was called - * [if this function was created using a call to eval] - */ - getEvalOrigin(): string | undefined; - - /** - * Is this a toplevel invocation, that is, is "this" the global object? - */ - isToplevel(): boolean; - - /** - * Does this call take place in code defined by a call to eval? - */ - isEval(): boolean; - - /** - * Is this call in native V8 code? - */ - isNative(): boolean; - - /** - * Is this a constructor call? - */ - isConstructor(): boolean; - } - - interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } - - class EventEmitter { - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - rawListeners(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: (...args: any[]) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - eventNames(): Array; - } - - interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: WritableStream): this; - unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; - wrap(oldStream: ReadableStream): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - interface WritableStream extends EventEmitter { - writable: boolean; - write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; - write(str: string, encoding?: string, cb?: (err?: Error | null) => void): boolean; - end(cb?: () => void): void; - end(data: string | Uint8Array, cb?: () => void): void; - end(str: string, encoding?: string, cb?: () => void): void; - } - - interface ReadWriteStream extends ReadableStream, WritableStream { } - - interface Domain extends EventEmitter { - run(fn: (...args: any[]) => T, ...args: any[]): T; - add(emitter: EventEmitter | Timer): void; - remove(emitter: EventEmitter | Timer): void; - bind(cb: T): T; - intercept(cb: T): T; - - addListener(event: string, listener: (...args: any[]) => void): this; - on(event: string, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - removeListener(event: string, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string): this; - } - - interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - external: number; - } - - interface CpuUsage { - user: number; - system: number; - } - - interface ProcessRelease { - name: string; - sourceUrl?: string; - headersUrl?: string; - libUrl?: string; - lts?: string; - } - - interface ProcessVersions { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } - - type Platform = 'aix' - | 'android' - | 'darwin' - | 'freebsd' - | 'linux' - | 'openbsd' - | 'sunos' - | 'win32' - | 'cygwin' - | 'netbsd'; - - type Signals = - "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | - "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | - "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | - "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; - - type MultipleResolveType = 'resolve' | 'reject'; - - type BeforeExitListener = (code: number) => void; - type DisconnectListener = () => void; - type ExitListener = (code: number) => void; - type RejectionHandledListener = (promise: Promise) => void; - type UncaughtExceptionListener = (error: Error) => void; - type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; - type WarningListener = (warning: Error) => void; - type MessageListener = (message: any, sendHandle: any) => void; - type SignalsListener = (signal: Signals) => void; - type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; - - interface Socket extends ReadWriteStream { - isTTY?: true; - } - - interface ProcessEnv { - [key: string]: string | undefined; - } - - interface HRTime { - (time?: [number, number]): [number, number]; - } - - interface ProcessReport { - /** - * Directory where the report is written. - * working directory of the Node.js process. - * @default '' indicating that reports are written to the current - */ - directory: string; - - /** - * Filename where the report is written. - * The default value is the empty string. - * @default '' the output filename will be comprised of a timestamp, - * PID, and sequence number. - */ - filename: string; - - /** - * Returns a JSON-formatted diagnostic report for the running process. - * The report's JavaScript stack trace is taken from err, if present. - */ - getReport(err?: Error): string; - - /** - * If true, a diagnostic report is generated on fatal errors, - * such as out of memory errors or failed C++ assertions. - * @default false - */ - reportOnFatalError: boolean; - - /** - * If true, a diagnostic report is generated when the process - * receives the signal specified by process.report.signal. - * @defaul false - */ - reportOnSignal: boolean; - - /** - * If true, a diagnostic report is generated on uncaught exception. - * @default false - */ - reportOnUncaughtException: boolean; - - /** - * The signal used to trigger the creation of a diagnostic report. - * @default 'SIGUSR2' - */ - signal: Signals; - - /** - * Writes a diagnostic report to a file. If filename is not provided, the default filename - * includes the date, time, PID, and a sequence number. - * The report's JavaScript stack trace is taken from err, if present. - * - * @param fileName Name of the file where the report is written. - * This should be a relative path, that will be appended to the directory specified in - * `process.report.directory`, or the current working directory of the Node.js process, - * if unspecified. - * @param error A custom error used for reporting the JavaScript stack. - * @return Filename of the generated report. - */ - writeReport(fileName?: string): string; - writeReport(error?: Error): string; - writeReport(fileName?: string, err?: Error): string; - } - - interface ResourceUsage { - fsRead: number; - fsWrite: number; - involuntaryContextSwitches: number; - ipcReceived: number; - ipcSent: number; - majorPageFault: number; - maxRSS: number; - minorPageFault: number; - sharedMemorySize: number; - signalsCount: number; - swappedOut: number; - systemCPUTime: number; - unsharedDataSize: number; - unsharedStackSize: number; - userCPUTime: number; - voluntaryContextSwitches: number; - } - - interface Process extends EventEmitter { - /** - * Can also be a tty.WriteStream, not typed due to limitation.s - */ - stdout: WriteStream; - /** - * Can also be a tty.WriteStream, not typed due to limitation.s - */ - stderr: WriteStream; - stdin: ReadStream; - openStdin(): Socket; - argv: string[]; - argv0: string; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - debugPort: number; - emitWarning(warning: string | Error, name?: string, ctor?: Function): void; - env: ProcessEnv; - exit(code?: number): never; - exitCode?: number; - getgid(): number; - setgid(id: number | string): void; - getuid(): number; - setuid(id: number | string): void; - geteuid(): number; - seteuid(id: number | string): void; - getegid(): number; - setegid(id: number | string): void; - getgroups(): number[]; - setgroups(groups: Array): void; - setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; - hasUncaughtExceptionCaptureCallback(): boolean; - 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): true; - pid: number; - ppid: number; - title: string; - arch: string; - platform: Platform; - mainModule?: NodeModule; - memoryUsage(): MemoryUsage; - cpuUsage(previousValue?: CpuUsage): CpuUsage; - nextTick(callback: Function, ...args: any[]): void; - release: ProcessRelease; - features: { - inspector: boolean; - debug: boolean; - uv: boolean; - ipv6: boolean; - tls_alpn: boolean; - tls_sni: boolean; - tls_ocsp: boolean; - tls: boolean; - }; - /** - * Can only be set if not in worker thread. - */ - umask(mask?: number): number; - uptime(): number; - hrtime: HRTime; - domain: Domain; - - // Worker - send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; - disconnect(): void; - connected: boolean; - - /** - * The `process.allowedNodeEnvironmentFlags` property is a special, - * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] - * environment variable. - */ - allowedNodeEnvironmentFlags: ReadonlySet; - - /** - * Only available with `--experimental-report` - */ - report?: ProcessReport; - - resourceUsage(): ResourceUsage; - - /** - * EventEmitter - * 1. beforeExit - * 2. disconnect - * 3. exit - * 4. message - * 5. rejectionHandled - * 6. uncaughtException - * 7. unhandledRejection - * 8. warning - * 9. message - * 10. - * 11. newListener/removeListener inherited from EventEmitter - */ - addListener(event: "beforeExit", listener: BeforeExitListener): this; - addListener(event: "disconnect", listener: DisconnectListener): this; - addListener(event: "exit", listener: ExitListener): this; - addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - addListener(event: "warning", listener: WarningListener): this; - addListener(event: "message", listener: MessageListener): this; - addListener(event: Signals, listener: SignalsListener): this; - addListener(event: "newListener", listener: NewListenerListener): this; - addListener(event: "removeListener", listener: RemoveListenerListener): this; - addListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - emit(event: "beforeExit", code: number): boolean; - emit(event: "disconnect"): boolean; - emit(event: "exit", code: number): boolean; - emit(event: "rejectionHandled", promise: Promise): boolean; - emit(event: "uncaughtException", error: Error): boolean; - emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; - emit(event: "warning", warning: Error): boolean; - emit(event: "message", message: any, sendHandle: any): this; - emit(event: Signals, signal: Signals): boolean; - emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; - emit(event: "multipleResolves", listener: MultipleResolveListener): this; - - on(event: "beforeExit", listener: BeforeExitListener): this; - on(event: "disconnect", listener: DisconnectListener): this; - on(event: "exit", listener: ExitListener): this; - on(event: "rejectionHandled", listener: RejectionHandledListener): this; - on(event: "uncaughtException", listener: UncaughtExceptionListener): this; - on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - on(event: "warning", listener: WarningListener): this; - on(event: "message", listener: MessageListener): this; - on(event: Signals, listener: SignalsListener): this; - on(event: "newListener", listener: NewListenerListener): this; - on(event: "removeListener", listener: RemoveListenerListener): this; - on(event: "multipleResolves", listener: MultipleResolveListener): this; - - once(event: "beforeExit", listener: BeforeExitListener): this; - once(event: "disconnect", listener: DisconnectListener): this; - once(event: "exit", listener: ExitListener): this; - once(event: "rejectionHandled", listener: RejectionHandledListener): this; - once(event: "uncaughtException", listener: UncaughtExceptionListener): this; - once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - once(event: "warning", listener: WarningListener): this; - once(event: "message", listener: MessageListener): this; - once(event: Signals, listener: SignalsListener): this; - once(event: "newListener", listener: NewListenerListener): this; - once(event: "removeListener", listener: RemoveListenerListener): this; - once(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependListener(event: "beforeExit", listener: BeforeExitListener): this; - prependListener(event: "disconnect", listener: DisconnectListener): this; - prependListener(event: "exit", listener: ExitListener): this; - prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependListener(event: "warning", listener: WarningListener): this; - prependListener(event: "message", listener: MessageListener): this; - prependListener(event: Signals, listener: SignalsListener): this; - prependListener(event: "newListener", listener: NewListenerListener): this; - prependListener(event: "removeListener", listener: RemoveListenerListener): this; - prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; - prependOnceListener(event: "disconnect", listener: DisconnectListener): this; - prependOnceListener(event: "exit", listener: ExitListener): this; - prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependOnceListener(event: "warning", listener: WarningListener): this; - prependOnceListener(event: "message", listener: MessageListener): this; - prependOnceListener(event: Signals, listener: SignalsListener): this; - prependOnceListener(event: "newListener", listener: NewListenerListener): this; - prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; - prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - listeners(event: "beforeExit"): BeforeExitListener[]; - listeners(event: "disconnect"): DisconnectListener[]; - listeners(event: "exit"): ExitListener[]; - listeners(event: "rejectionHandled"): RejectionHandledListener[]; - listeners(event: "uncaughtException"): UncaughtExceptionListener[]; - listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; - listeners(event: "warning"): WarningListener[]; - listeners(event: "message"): MessageListener[]; - listeners(event: Signals): SignalsListener[]; - listeners(event: "newListener"): NewListenerListener[]; - listeners(event: "removeListener"): RemoveListenerListener[]; - listeners(event: "multipleResolves"): MultipleResolveListener[]; - } - - 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: Immediate) => void; - clearInterval: (intervalId: Timeout) => void; - clearTimeout: (timeoutId: Timeout) => 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[]) => Immediate; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - queueMicrotask: typeof queueMicrotask; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } - - // compatibility with older typings - interface Timer { - hasRef(): boolean; - ref(): this; - refresh(): this; - unref(): this; - } - - class Immediate { - hasRef(): boolean; - ref(): this; - unref(): this; - _onImmediate: Function; // to distinguish it from the Timeout class - } - - class Timeout implements Timer { - hasRef(): boolean; - ref(): this; - refresh(): this; - unref(): this; - } - - class Module { - static runMain(): void; - static wrap(code: string): string; - - /** - * @deprecated Deprecated since: v12.2.0. Please use createRequire() instead. - */ - static createRequireFromPath(path: string): NodeRequire; - static createRequire(path: string): NodeRequire; - static builtinModules: string[]; - - static Module: typeof Module; - - exports: any; - require: NodeRequireFunction; - id: string; - filename: string; - loaded: boolean; - parent: Module | null; - children: Module[]; - /** - * @since 11.14.0 - * - * The directory name of the module. This is usually the same as the path.dirname() of the module.id. - */ - path: string; - paths: string[]; - - constructor(id: string, parent?: Module); - } - - type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; - type ArrayBufferView = TypedArray | DataView; - - // TODO: The value type here is a version of `unknown` with an acceptably lossy amount of accuracy. - // Now that TypeScript's DT support is 3.0+, we can look into replacing this with `unknown`. - type UnknownFacade = {} | null | undefined; - - /** @deprecated - Use `UnknownFacade` instead. It is a better classifier for the type */ - type PoorMansUnknown = UnknownFacade; -} diff --git a/types/node/v12/ts3.1/index.d.ts b/types/node/v12/ts3.1/index.d.ts deleted file mode 100644 index 2210ba4b31..0000000000 --- a/types/node/v12/ts3.1/index.d.ts +++ /dev/null @@ -1,65 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.2. - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 - -// NOTE: Augmentations for TypeScript 3.2 and later should use individual files for overrides -// within the respective ~/ts3.2 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.2, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -/// - -// We can't include globals.global.d.ts in globals.d.ts, as it'll cause duplication errors in TypeScript 3.4+ -/// - -// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in TypeScript 3.7+ -/// - -// TypeScript 2.1-specific augmentations: - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files -// just to ensure the names are known and node typings can be used without importing these libs. -// if someone really needs these types the libs need to be added via --lib or in tsconfig.json -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } -interface Set {} -interface Map {} -interface ReadonlySet {} -interface Iterable { } -interface IteratorResult { } -interface AsyncIterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IterableIterator { } -interface AsyncIterableIterator {} -interface SymbolConstructor { - readonly iterator: symbol; - readonly asyncIterator: symbol; -} -declare var Symbol: SymbolConstructor; -// even this is just a forward declaration some properties are added otherwise -// it would be allowed to pass anything to e.g. Buffer.from() -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; -} - -declare module "util" { - namespace inspect { - const custom: symbol; - } - namespace promisify { - const custom: symbol; - } - namespace types { - function isBigInt64Array(value: any): boolean; - function isBigUint64Array(value: any): boolean; - } -} diff --git a/types/node/v12/ts3.1/node-tests.ts b/types/node/v12/ts3.1/node-tests.ts deleted file mode 100644 index ccd5b74cdf..0000000000 --- a/types/node/v12/ts3.1/node-tests.ts +++ /dev/null @@ -1,900 +0,0 @@ -import assert = require("assert"); -import * as fs from "fs"; -import * as url from "url"; -import * as util from "util"; -import * as http from "http"; -import * as https from "https"; -import * as console2 from "console"; -import * as timers from "timers"; -import * as dns from "dns"; -import * as inspector from "inspector"; -import * as trace_events from "trace_events"; -import * as dgram from "dgram"; -import Module = require("module"); - -//////////////////////////////////////////////////// -/// Url tests : http://nodejs.org/api/url.html -//////////////////////////////////////////////////// - -{ - { - url.format(url.parse('http://www.example.com/xyz')); - - url.format('http://www.example.com/xyz'); - - // https://google.com/search?q=you're%20a%20lizard%2C%20gary - url.format({ - protocol: 'https', - host: "google.com", - pathname: 'search', - query: { q: "you're a lizard, gary" } - }); - - const myURL = new url.URL('https://a:b@你好你好?abc#foo'); - url.format(myURL, { fragment: false, unicode: true, auth: false }); - } - - { - const helloUrl = url.parse('http://example.com/?hello=world', true); - let helloQuery = helloUrl.query['hello']; - assert.equal(helloUrl.query['hello'], 'world'); - - let strUrl = url.parse('http://example.com/?hello=world'); - let queryStr: string = strUrl.query!; - - strUrl = url.parse('http://example.com/?hello=world', false); - queryStr = strUrl.query!; - - function getBoolean(): boolean { return false; } - const urlUrl = url.parse('http://example.com/?hello=world', getBoolean()); - if (typeof(urlUrl.query) === 'string') { - queryStr = urlUrl.query; - } else if (urlUrl.query) { - helloQuery = urlUrl.query['hello']; - } - } - - { - const ascii: string = url.domainToASCII('español.com'); - const unicode: string = url.domainToUnicode('xn--espaol-zwa.com'); - } - - { - let myURL = new url.URL('https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.hash, '#bar'); - assert.equal(myURL.host, 'example.org:81'); - assert.equal(myURL.hostname, 'example.org'); - assert.equal(myURL.href, 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.origin, 'https://example.org:81'); - assert.equal(myURL.password, 'thepwd'); - assert.equal(myURL.username, 'theuser'); - assert.equal(myURL.pathname, '/foo/path'); - assert.equal(myURL.port, "81"); - assert.equal(myURL.protocol, "https:"); - assert.equal(myURL.search, "?query=string"); - assert.equal(myURL.toString(), 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert(myURL.searchParams instanceof url.URLSearchParams); - - myURL.host = 'example.org:82'; - myURL.hostname = 'example.com'; - myURL.href = 'http://other.com'; - myURL.hash = 'baz'; - myURL.password = "otherpwd"; - myURL.username = "otheruser"; - myURL.pathname = "/otherPath"; - myURL.port = "82"; - myURL.protocol = "http"; - myURL.search = "a=b"; - assert.equal(myURL.href, 'http://otheruser:otherpwd@other.com:82/otherPath?a=b#baz'); - - myURL = new url.URL('/foo', 'https://example.org/'); - assert.equal(myURL.href, 'https://example.org/foo'); - assert.equal(myURL.toJSON(), myURL.href); - } - - { - const searchParams = new url.URLSearchParams('abc=123'); - - assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { - assert.equal(name, 'abc'); - assert.equal(value, '123'); - assert.equal(me, searchParams); - }); - - assert.equal(searchParams.get('abc'), '123'); - - searchParams.append('abc', 'xyz'); - - assert.deepEqual(searchParams.getAll('abc'), ['123', 'xyz']); - - const entries = searchParams.entries(); - assert.deepEqual(entries.next(), { value: ["abc", "123"], done: false }); - assert.deepEqual(entries.next(), { value: ["abc", "xyz"], done: false }); - assert.deepEqual(entries.next(), { value: undefined, done: true }); - - const keys = searchParams.keys(); - assert.deepEqual(keys.next(), { value: "abc", done: false }); - assert.deepEqual(keys.next(), { value: "abc", done: false }); - assert.deepEqual(keys.next(), { value: undefined, done: true }); - - const values = searchParams.values(); - assert.deepEqual(values.next(), { value: "123", done: false }); - assert.deepEqual(values.next(), { value: "xyz", done: false }); - assert.deepEqual(values.next(), { value: undefined, done: true }); - - searchParams.set('abc', 'b'); - assert.deepEqual(searchParams.getAll('abc'), ['b']); - - searchParams.delete('a'); - assert(!searchParams.has('a')); - assert.equal(searchParams.get('a'), null); - - searchParams.sort(); - } - - { - const searchParams = new url.URLSearchParams({ - user: 'abc', - query: ['first', 'second'] - }); - - assert.equal(searchParams.toString(), 'user=abc&query=first%2Csecond'); - assert.deepEqual(searchParams.getAll('query'), ['first,second']); - } - - { - // Using an array - const params = new url.URLSearchParams([ - ['user', 'abc'], - ['query', 'first'], - ['query', 'second'], - // ts 2.1/2.* compatibility - // tslint:disable-next-line no-unnecessary-type-assertion - ] as Array<[string, string]>); - assert.equal(params.toString(), 'user=abc&query=first&query=second'); - } - - { - let path: string = url.fileURLToPath('file://test'); - path = url.fileURLToPath(new url.URL('file://test')); - } - - { - const path: url.URL = url.pathToFileURL('file://test'); - } -} - -////////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html /// -////////////////////////////////////////////////////// - -{ - let agent: https.Agent = new https.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256, - maxCachedSessions: 100, - timeout: 15000 - }); - - agent = https.globalAgent; - - https.request({ - agent: false - }); - https.request({ - agent - }); - https.request({ - agent: undefined - }); - - https.get('http://www.example.com/xyz'); - https.request('http://www.example.com/xyz'); - - https.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - https.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - - https.get(new url.URL('http://www.example.com/xyz')); - https.request(new url.URL('http://www.example.com/xyz')); - - https.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - https.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - - const opts: https.RequestOptions = { - path: '/some/path' - }; - https.get(new url.URL('http://www.example.com'), opts); - https.request(new url.URL('http://www.example.com'), opts); - https.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - https.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - - https.globalAgent.options.ca = []; - - { - function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} - - class MyIncomingMessage extends http.IncomingMessage { - foo: number; - } - - class MyServerResponse extends http.ServerResponse { - foo: string; - } - - let server: https.Server; - - server = new https.Server(); - server = new https.Server(reqListener); - server = new https.Server({ IncomingMessage: MyIncomingMessage}); - - server = new https.Server({ - IncomingMessage: MyIncomingMessage, - ServerResponse: MyServerResponse - }, reqListener); - - server = https.createServer(); - server = https.createServer(reqListener); - server = https.createServer({ IncomingMessage: MyIncomingMessage }); - server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); - - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - const maxHeadersCount: number | null = server.maxHeadersCount; - const headersTimeout: number = server.headersTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } -} - -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - -{ - { - const immediate = timers - .setImmediate(() => { - console.log('immediate'); - }) - .unref() - .ref(); - const b: boolean = immediate.hasRef(); - timers.clearImmediate(immediate); - } - { - const timeout = timers - .setInterval(() => { - console.log('interval'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearInterval(timeout); - } - { - const timeout = timers - .setTimeout(() => { - console.log('timeout'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearTimeout(timeout); - } - async function testPromisify() { - const setTimeout = util.promisify(timers.setTimeout); - let v: void = await setTimeout(100); // tslint:disable-line no-void-expression void-return - let s: string = await setTimeout(100, ""); - - const setImmediate = util.promisify(timers.setImmediate); - v = await setImmediate(); // tslint:disable-line no-void-expression - s = await setImmediate(""); - } -} - -///////////////////////////////////////////////////////// -/// Errors Tests : https://nodejs.org/api/errors.html /// -///////////////////////////////////////////////////////// - -{ - { - Error.stackTraceLimit = Infinity; - } - { - const myObject = {}; - Error.captureStackTrace(myObject); - } - { - const frames: NodeJS.CallSite[] = []; - Error.prepareStackTrace!(new Error(), frames); - } - { - const frame: NodeJS.CallSite = null!; - const frameThis: any = frame.getThis(); - const typeName: string | null = frame.getTypeName(); - const func: Function | undefined = frame.getFunction(); - const funcName: string | null = frame.getFunctionName(); - const meth: string | null = frame.getMethodName(); - const fname: string | null = frame.getFileName(); - const lineno: number | null = frame.getLineNumber(); - const colno: number | null = frame.getColumnNumber(); - const evalOrigin: string | undefined = frame.getEvalOrigin(); - const isTop: boolean = frame.isToplevel(); - const isEval: boolean = frame.isEval(); - const isNative: boolean = frame.isNative(); - const isConstr: boolean = frame.isConstructor(); - } -} - -/////////////////////////////////////////////////////////// -/// Console Tests : https://nodejs.org/api/console.html /// -/////////////////////////////////////////////////////////// - -{ - { - let _c: Console = console; - _c = console2; - } - { - const writeStream = fs.createWriteStream('./index.d.ts'); - let consoleInstance: Console = new console.Console(writeStream); - - consoleInstance = new console.Console(writeStream, writeStream); - consoleInstance = new console.Console(writeStream, writeStream, true); - consoleInstance = new console.Console({ - stdout: writeStream, - stderr: writeStream, - colorMode: 'auto', - ignoreErrors: true - }); - consoleInstance = new console.Console({ - stdout: writeStream, - colorMode: false - }); - consoleInstance = new console.Console({ - stdout: writeStream - }); - } - { - console.assert('value'); - console.assert('value', 'message'); - console.assert('value', 'message', 'foo', 'bar'); - console.clear(); - console.count(); - console.count('label'); - console.countReset(); - console.countReset('label'); - console.debug(); - console.debug('message'); - console.debug('message', 'foo', 'bar'); - console.dir('obj'); - console.dir('obj', { depth: 1 }); - console.error(); - console.error('message'); - console.error('message', 'foo', 'bar'); - console.group(); - console.group('label'); - console.group('label1', 'label2'); - console.groupCollapsed(); - console.groupEnd(); - console.info(); - console.info('message'); - console.info('message', 'foo', 'bar'); - console.log(); - console.log('message'); - console.log('message', 'foo', 'bar'); - console.table({ foo: 'bar' }); - console.table([{ foo: 'bar' }]); - console.table([{ foo: 'bar' }], ['foo']); - console.time(); - console.time('label'); - console.timeEnd(); - console.timeEnd('label'); - console.timeLog(); - console.timeLog('label'); - console.timeLog('label', 'foo', 'bar'); - console.trace(); - console.trace('message'); - console.trace('message', 'foo', 'bar'); - console.warn(); - console.warn('message'); - console.warn('message', 'foo', 'bar'); - - // --- Inspector mode only --- - console.markTimeline(); - console.markTimeline('label'); - console.profile(); - console.profile('label'); - console.profileEnd(); - console.profileEnd('label'); - console.timeStamp(); - console.timeStamp('label'); - console.timeline(); - console.timeline('label'); - console.timelineEnd(); - console.timelineEnd('label'); - } -} - -/////////////////////////////////////////////////// -/// DNS Tests : https://nodejs.org/api/dns.html /// -/////////////////////////////////////////////////// - -{ - dns.lookup("nodejs.org", (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 4, (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 6, (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", {}, (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup( - "nodejs.org", - { - family: 4, - hints: dns.ADDRCONFIG | dns.V4MAPPED, - all: false - }, - (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - } - ); - dns.lookup("nodejs.org", { all: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: dns.LookupAddress[] = addresses; - }); - dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: dns.LookupAddress[] = addresses; - }); - - function trueOrFalse(): boolean { - return Math.random() > 0.5 ? true : false; - } - dns.lookup("nodejs.org", { all: trueOrFalse() }, (err, addresses, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _addresses: string | dns.LookupAddress[] = addresses; - const _family: number | undefined = family; - }); - - dns.lookupService("127.0.0.1", 0, (err, hostname, service) => { - const _err: NodeJS.ErrnoException | null = err; - const _hostname: string = hostname; - const _service: string = service; - }); - - dns.resolve("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "A", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "AAAA", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "ANY", (err, addresses) => { - const _addresses: dns.AnyRecord[] = addresses; - }); - dns.resolve("nodejs.org", "MX", (err, addresses) => { - const _addresses: dns.MxRecord[] = addresses; - }); - - dns.resolve4("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve4("nodejs.org", { ttl: true }, (err, addresses) => { - const _addresses: dns.RecordWithTtl[] = addresses; - }); - { - const ttl = false; - dns.resolve4("nodejs.org", { ttl }, (err, addresses) => { - const _addresses: string[] | dns.RecordWithTtl[] = addresses; - }); - } - - dns.resolve6("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve6("nodejs.org", { ttl: true }, (err, addresses) => { - const _addresses: dns.RecordWithTtl[] = addresses; - }); - { - const ttl = false; - dns.resolve6("nodejs.org", { ttl }, (err, addresses) => { - const _addresses: string[] | dns.RecordWithTtl[] = addresses; - }); - } - { - const resolver = new dns.Resolver(); - resolver.setServers(["4.4.4.4"]); - resolver.resolve("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - resolver.cancel(); - } -} - -/***************************************************************************** - * * - * The following tests are the modules not mentioned in document but existed * - * * - *****************************************************************************/ - -/////////////////////////////////////////////////////////// -/// Constants Tests /// -/////////////////////////////////////////////////////////// - -import * as constants from 'constants'; -{ - let str: string; - let num: number; - num = constants.SIGHUP; - num = constants.SIGINT; - num = constants.SIGQUIT; - num = constants.SIGILL; - num = constants.SIGTRAP; - num = constants.SIGABRT; - num = constants.SIGIOT; - num = constants.SIGBUS; - num = constants.SIGFPE; - num = constants.SIGKILL; - num = constants.SIGUSR1; - num = constants.SIGSEGV; - num = constants.SIGUSR2; - num = constants.SIGPIPE; - num = constants.SIGALRM; - num = constants.SIGTERM; - num = constants.SIGCHLD; - num = constants.SIGSTKFLT; - num = constants.SIGCONT; - num = constants.SIGSTOP; - num = constants.SIGTSTP; - num = constants.SIGTTIN; - num = constants.SIGTTOU; - num = constants.SIGURG; - num = constants.SIGXCPU; - num = constants.SIGXFSZ; - num = constants.SIGVTALRM; - num = constants.SIGPROF; - num = constants.SIGWINCH; - num = constants.SIGIO; - num = constants.SIGPOLL; - num = constants.SIGPWR; - num = constants.SIGSYS; - num = constants.SIGUNUSED; - num = constants.O_RDONLY; - num = constants.O_WRONLY; - num = constants.O_RDWR; - num = constants.S_IFMT; - num = constants.S_IFREG; - num = constants.S_IFDIR; - num = constants.S_IFCHR; - num = constants.S_IFBLK; - num = constants.S_IFIFO; - num = constants.S_IFLNK; - num = constants.S_IFSOCK; - num = constants.O_CREAT; - num = constants.O_EXCL; - num = constants.O_NOCTTY; - num = constants.O_TRUNC; - num = constants.O_APPEND; - num = constants.O_DIRECTORY; - num = constants.O_NOATIME; - num = constants.O_NOFOLLOW; - num = constants.O_SYNC; - num = constants.O_DSYNC; - num = constants.O_DIRECT; - num = constants.O_NONBLOCK; - num = constants.S_IRWXU; - num = constants.S_IRUSR; - num = constants.S_IWUSR; - num = constants.S_IXUSR; - num = constants.S_IRWXG; - num = constants.S_IRGRP; - num = constants.S_IWGRP; - num = constants.S_IXGRP; - num = constants.S_IRWXO; - num = constants.S_IROTH; - num = constants.S_IWOTH; - num = constants.S_IXOTH; - num = constants.F_OK; - num = constants.R_OK; - num = constants.W_OK; - num = constants.X_OK; - num = constants.SSL_OP_ALL; - num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION; - num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE; - num = constants.SSL_OP_CISCO_ANYCONNECT; - num = constants.SSL_OP_COOKIE_EXCHANGE; - num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG; - num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; - num = constants.SSL_OP_EPHEMERAL_RSA; - num = constants.SSL_OP_LEGACY_SERVER_CONNECT; - num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER; - num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG; - num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING; - num = constants.SSL_OP_NETSCAPE_CA_DN_BUG; - num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG; - num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG; - num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; - num = constants.SSL_OP_NO_COMPRESSION; - num = constants.SSL_OP_NO_QUERY_MTU; - num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION; - num = constants.SSL_OP_NO_SSLv2; - num = constants.SSL_OP_NO_SSLv3; - num = constants.SSL_OP_NO_TICKET; - num = constants.SSL_OP_NO_TLSv1; - num = constants.SSL_OP_NO_TLSv1_1; - num = constants.SSL_OP_NO_TLSv1_2; - num = constants.SSL_OP_PKCS1_CHECK_1; - num = constants.SSL_OP_PKCS1_CHECK_2; - num = constants.SSL_OP_SINGLE_DH_USE; - num = constants.SSL_OP_SINGLE_ECDH_USE; - num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG; - num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG; - num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG; - num = constants.SSL_OP_TLS_D5_BUG; - num = constants.SSL_OP_TLS_ROLLBACK_BUG; - num = constants.ENGINE_METHOD_RSA; - num = constants.ENGINE_METHOD_DSA; - num = constants.ENGINE_METHOD_DH; - num = constants.ENGINE_METHOD_RAND; - num = constants.ENGINE_METHOD_ECDH; - num = constants.ENGINE_METHOD_ECDSA; - num = constants.ENGINE_METHOD_CIPHERS; - num = constants.ENGINE_METHOD_DIGESTS; - num = constants.ENGINE_METHOD_STORE; - num = constants.ENGINE_METHOD_PKEY_METHS; - num = constants.ENGINE_METHOD_PKEY_ASN1_METHS; - num = constants.ENGINE_METHOD_ALL; - num = constants.ENGINE_METHOD_NONE; - num = constants.DH_CHECK_P_NOT_SAFE_PRIME; - num = constants.DH_CHECK_P_NOT_PRIME; - num = constants.DH_UNABLE_TO_CHECK_GENERATOR; - num = constants.DH_NOT_SUITABLE_GENERATOR; - num = constants.ALPN_ENABLED; - num = constants.RSA_PKCS1_PADDING; - num = constants.RSA_SSLV23_PADDING; - num = constants.RSA_NO_PADDING; - num = constants.RSA_PKCS1_OAEP_PADDING; - num = constants.RSA_X931_PADDING; - num = constants.RSA_PKCS1_PSS_PADDING; - num = constants.POINT_CONVERSION_COMPRESSED; - num = constants.POINT_CONVERSION_UNCOMPRESSED; - num = constants.POINT_CONVERSION_HYBRID; - str = constants.defaultCoreCipherList; - str = constants.defaultCipherList; -} - -/////////////////////////////////////////////////////////// -/// Inspector Tests /// -/////////////////////////////////////////////////////////// - -{ - { - const b: inspector.Console.ConsoleMessage = {source: 'test', text: 'test', level: 'error' }; - inspector.open(); - inspector.open(0); - inspector.open(0, 'localhost'); - inspector.open(0, 'localhost', true); - inspector.close(); - const inspectorUrl: string | undefined = inspector.url(); - - const session = new inspector.Session(); - session.connect(); - session.disconnect(); - - // Unknown post method - session.post('A.b', { key: 'value' }, (err, params) => {}); - // TODO: parameters are implicitly 'any' and need type annotation - session.post('A.b', (err: Error | null, params?: {}) => {}); - session.post('A.b'); - // Known post method - const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; - session.post('Runtime.evaluate', parameter, - (err: Error | null, params: inspector.Runtime.EvaluateReturnType) => {}); - session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { - const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails!; - const resultClassName: string = params.result.className!; - }); - session.post('Runtime.evaluate'); - - // General event - session.on('inspectorNotification', message => { - message; // $ExpectType InspectorNotification<{}> - }); - // Known events - session.on('Debugger.paused', (message: inspector.InspectorNotification) => { - const method: string = message.method; - const pauseReason: string = message.params.reason; - }); - session.on('Debugger.resumed', () => {}); - // Node Inspector events - session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification) => { - const value: Array<{}> = message.params.value; - }); - } -} - -/////////////////////////////////////////////////////////// -/// Trace Events Tests /// -/////////////////////////////////////////////////////////// - -{ - const enabledCategories: string | undefined = trace_events.getEnabledCategories(); - const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] }); - const categories: string = tracing.categories; - const enabled: boolean = tracing.enabled; - tracing.enable(); - tracing.disable(); -} - -//////////////////////////////////////////////////// -/// module tests : http://nodejs.org/api/modules.html -//////////////////////////////////////////////////// -import moduleModule = require('module'); - -{ - require.extensions[".ts"] = () => ""; - - Module.runMain(); - const s: string = Module.wrap("some code"); - - const m1: Module = new Module("moduleId"); - const m2: Module = new Module.Module("moduleId"); - const b: string[] = Module.builtinModules; - let paths: string[] = module.paths; - const path: string = module.path; - paths = m1.paths; - - const customRequire1 = moduleModule.createRequireFromPath('./test'); - const customRequire2 = moduleModule.createRequire('./test'); - - customRequire1('test'); - customRequire2('test'); - - const resolved1: string = customRequire1.resolve('test'); - const resolved2: string = customRequire2.resolve('test'); - - const paths1: string[] | null = customRequire1.resolve.paths('test'); - const paths2: string[] | null = customRequire2.resolve.paths('test'); - - const cachedModule1: Module = customRequire1.cache['/path/to/module.js']; - const cachedModule2: Module = customRequire2.cache['/path/to/module.js']; - - const main1: Module | undefined = customRequire1.main; - const main2: Module | undefined = customRequire2.main; -} - -///////////////////////////////////////////////////////// -/// stream tests : https://nodejs.org/api/stream.html /// -///////////////////////////////////////////////////////// -import stream = require('stream'); -import tty = require('tty'); - -{ - const writeStream = fs.createWriteStream('./index.d.ts'); - const _wom = writeStream.writableObjectMode; // $ExpectType boolean - - const readStream = fs.createReadStream('./index.d.ts'); - const _rom = readStream.readableObjectMode; // $ExpectType boolean - - const x: stream.Readable = process.stdin; - const stdin: tty.ReadStream = process.stdin; - const stdout: tty.WriteStream = process.stdout; - const stderr: tty.WriteStream = process.stderr; -} - -///////////////////////////////////////////////////////// -/// dgram tests : https://nodejs.org/api/dgram.html /// -///////////////////////////////////////////////////////// -{ - let sock: dgram.Socket = dgram.createSocket("udp4"); - sock = dgram.createSocket({ type: "udp4" }); - sock = dgram.createSocket({ - type: "udp4", - reuseAddr: true, - ipv6Only: false, - recvBufferSize: 4096, - sendBufferSize: 4096, - lookup: dns.lookup, - }); - sock = dgram.createSocket("udp6", (msg, rinfo) => { - msg; // $ExpectType Buffer - rinfo; // $ExpectType RemoteInfo - }); - sock.addMembership("233.252.0.0"); - sock.addMembership("233.252.0.0", "192.0.2.1"); - sock.address().address; // $ExpectType string - sock.address().family; // $ExpectType string - sock.address().port; // $ExpectType number - sock.bind(); - sock.bind(() => undefined); - sock.bind(8000); - sock.bind(8000, () => undefined); - sock.bind(8000, "192.0.2.1"); - sock.bind(8000, "192.0.2.1", () => undefined); - sock.bind({}, () => undefined); - sock.bind({ port: 8000, address: "192.0.2.1", exclusive: true }); - sock.bind({ fd: 7, exclusive: true }); - sock.close(); - sock.close(() => undefined); - sock.connect(8000); - sock.connect(8000, "192.0.2.1"); - sock.connect(8000, () => undefined); - sock.connect(8000, "192.0.2.1", () => undefined); - sock.disconnect(); - sock.dropMembership("233.252.0.0"); - sock.dropMembership("233.252.0.0", "192.0.2.1"); - sock.getRecvBufferSize(); // $ExpectType number - sock.getSendBufferSize(); // $ExpectType number - sock = sock.ref(); - sock.remoteAddress().address; // $ExpectType string - sock.remoteAddress().family; // $ExpectType string - sock.remoteAddress().port; // $ExpectType number - sock.send("datagram"); - sock.send(new Uint8Array(256), 8000, (err) => { - err; // $ExpectType Error | null - }); - sock.send(Buffer.alloc(256), 8000, "192.0.2.1"); - sock.send(new Uint8Array(256), 128, 64); - sock.send("datagram", 128, 64, (err) => undefined); - sock.send(new Uint8Array(256), 128, 64, 8000); - sock.send(new Uint8Array(256), 128, 64, 8000, (err) => undefined); - sock.send(Buffer.alloc(256), 128, 64, 8000, "192.0.2.1"); - sock.send("datagram", 128, 64, 8000, "192.0.2.1", (err) => undefined); - sock.setBroadcast(true); - sock.setMulticastInterface("192.0.2.1"); - sock.setMulticastLoopback(false); - sock.setMulticastTTL(128); - sock.setRecvBufferSize(4096); - sock.setSendBufferSize(4096); - sock.setTTL(128); - sock = sock.unref(); - - sock.on("close", () => undefined); - sock.on("connect", () => undefined); - sock.on("error", (exception) => { - exception; // $ExpectType Error - }); - sock.on("listening", () => undefined); - sock.on("message", (msg, rinfo) => { - msg; // $ExpectType Buffer - rinfo.address; // $ExpectType string - rinfo.family; // $ExpectType "IPv4" | "IPv6" - rinfo.port; // $ExpectType number - rinfo.size; // $ExpectType number - }); -} - -//////////////////////////////////////////////////// -/// Node.js ESNEXT Support -//////////////////////////////////////////////////// - -{ - const s = 'foo'; - const s1: string = s.trimLeft(); - const s2: string = s.trimRight(); - const s3: string = s.trimStart(); - const s4: string = s.trimEnd(); -} diff --git a/types/node/v12/ts3.1/tsconfig.json b/types/node/v12/ts3.1/tsconfig.json deleted file mode 100644 index 0f6b81b812..0000000000 --- a/types/node/v12/ts3.1/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "files": [ - "index.d.ts", - "node-tests.ts" - ], - "compilerOptions": { - "module": "commonjs", - "target": "esnext", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../../../", - "typeRoots": [ - "../../../" - ], - "paths": { - "node": [ - "node/v12" - ] - }, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - } -} diff --git a/types/node/v12/ts3.1/tslint.json b/types/node/v12/ts3.1/tslint.json deleted file mode 100644 index 65e8b18d2a..0000000000 --- a/types/node/v12/ts3.1/tslint.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "no-bad-reference": false, - "no-empty-interface": false, - "no-single-declare-module": false, - "unified-signatures": false - } -} diff --git a/types/node/v12/ts3.1/util.d.ts b/types/node/v12/ts3.1/util.d.ts deleted file mode 100644 index 0a24f56a05..0000000000 --- a/types/node/v12/ts3.1/util.d.ts +++ /dev/null @@ -1,181 +0,0 @@ -declare module "util" { - interface InspectOptions extends NodeJS.InspectOptions { } - function format(format: any, ...param: any[]): string; - function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; - /** @deprecated since v0.11.3 - use a third party module instead. */ - function log(string: string): void; - function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - function inspect(object: any, options: InspectOptions): string; - namespace inspect { - let colors: { - [color: string]: [number, number] | undefined - }; - let styles: { - [style: string]: string | undefined - }; - let defaultOptions: InspectOptions; - /** - * Allows changing inspect settings from the repl. - */ - let replDefaults: InspectOptions; - } - /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ - function isArray(object: any): object is any[]; - /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ - function isRegExp(object: any): object is RegExp; - /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ - function isDate(object: any): object is Date; - /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ - function isError(object: any): object is Error; - function inherits(constructor: any, superConstructor: any): void; - function debuglog(key: string): (msg: string, ...param: any[]) => void; - /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ - function isBoolean(object: any): object is boolean; - /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ - function isBuffer(object: any): object is Buffer; - /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ - function isFunction(object: any): boolean; - /** @deprecated since v4.0.0 - use `value === null` instead. */ - function isNull(object: any): object is null; - /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ - function isNullOrUndefined(object: any): object is null | undefined; - /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ - function isNumber(object: any): object is number; - /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ - function isObject(object: any): boolean; - /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ - function isPrimitive(object: any): boolean; - /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ - function isString(object: any): object is string; - /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ - function isSymbol(object: any): object is symbol; - /** @deprecated since v4.0.0 - use `value === undefined` instead. */ - function isUndefined(object: any): object is undefined; - function deprecate(fn: T, message: string, code?: string): T; - function isDeepStrictEqual(val1: any, val2: any): boolean; - - interface CustomPromisify extends Function { - __promisify__: TCustom; - } - - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - - function promisify(fn: CustomPromisify): TCustom; - function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; - function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; - function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): - (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): - (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify(fn: Function): Function; - - namespace types { - function isAnyArrayBuffer(object: any): boolean; - function isArgumentsObject(object: any): object is IArguments; - function isArrayBuffer(object: any): object is ArrayBuffer; - function isArrayBufferView(object: any): object is ArrayBufferView; - function isAsyncFunction(object: any): boolean; - function isBooleanObject(object: any): object is Boolean; - function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); - function isDataView(object: any): object is DataView; - function isDate(object: any): object is Date; - function isExternal(object: any): boolean; - function isFloat32Array(object: any): object is Float32Array; - function isFloat64Array(object: any): object is Float64Array; - function isGeneratorFunction(object: any): boolean; - function isGeneratorObject(object: any): boolean; - function isInt8Array(object: any): object is Int8Array; - function isInt16Array(object: any): object is Int16Array; - function isInt32Array(object: any): object is Int32Array; - function isMap(object: any): boolean; - function isMapIterator(object: any): boolean; - function isModuleNamespaceObject(value: any): boolean; - function isNativeError(object: any): object is Error; - function isNumberObject(object: any): object is Number; - function isPromise(object: any): boolean; - function isProxy(object: any): boolean; - function isRegExp(object: any): object is RegExp; - function isSet(object: any): boolean; - function isSetIterator(object: any): boolean; - function isSharedArrayBuffer(object: any): boolean; - function isStringObject(object: any): boolean; - function isSymbolObject(object: any): boolean; - function isTypedArray(object: any): object is NodeJS.TypedArray; - function isUint8Array(object: any): object is Uint8Array; - function isUint8ClampedArray(object: any): object is Uint8ClampedArray; - function isUint16Array(object: any): object is Uint16Array; - function isUint32Array(object: any): object is Uint32Array; - function isWeakMap(object: any): boolean; - function isWeakSet(object: any): boolean; - function isWebAssemblyCompiledModule(object: any): boolean; - } - - class TextDecoder { - readonly encoding: string; - readonly fatal: boolean; - readonly ignoreBOM: boolean; - constructor( - encoding?: string, - options?: { fatal?: boolean; ignoreBOM?: boolean } - ); - decode( - input?: NodeJS.ArrayBufferView | ArrayBuffer | null, - options?: { stream?: boolean } - ): string; - } - - interface EncodeIntoResult { - /** - * The read Unicode code units of input. - */ - - read: number; - /** - * The written UTF-8 bytes of output. - */ - written: number; - } - - class TextEncoder { - readonly encoding: string; - encode(input?: string): Uint8Array; - encodeInto(input: string, output: Uint8Array): EncodeIntoResult; - } -} diff --git a/types/node/v12/ts3.1/assert.d.ts b/types/node/v12/ts3.3/assert.d.ts similarity index 100% rename from types/node/v12/ts3.1/assert.d.ts rename to types/node/v12/ts3.3/assert.d.ts diff --git a/types/node/v12/ts3.3/base.d.ts b/types/node/v12/ts3.3/base.d.ts index ae43027b06..0276b86e05 100644 --- a/types/node/v12/ts3.3/base.d.ts +++ b/types/node/v12/ts3.3/base.d.ts @@ -13,10 +13,42 @@ /// // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -// tslint:disable-next-line:no-bad-reference -/// - -// TypeScript 3.2-specific augmentations: -/// -/// /// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/node/v12/ts3.1/globals.global.d.ts b/types/node/v12/ts3.3/globals.global.d.ts similarity index 100% rename from types/node/v12/ts3.1/globals.global.d.ts rename to types/node/v12/ts3.3/globals.global.d.ts diff --git a/types/node/v12/ts3.3/index.d.ts b/types/node/v12/ts3.3/index.d.ts index 405b82a8c6..28aaabb245 100644 --- a/types/node/v12/ts3.3/index.d.ts +++ b/types/node/v12/ts3.3/index.d.ts @@ -4,9 +4,5 @@ // Typically type modifiations should be made in base.d.ts instead of here /// - -// tslint:disable-next-line:no-bad-reference -/// - -// tslint:disable-next-line:no-bad-reference -/// +/// +/// diff --git a/types/node/v12/ts3.3/node-tests.ts b/types/node/v12/ts3.3/node-tests.ts index 9767cd9212..566f65b386 100644 --- a/types/node/v12/ts3.3/node-tests.ts +++ b/types/node/v12/ts3.3/node-tests.ts @@ -1,31 +1,903 @@ -// tslint:disable-next-line:no-bad-reference -import '../ts3.1/node-tests'; -import '../ts3.1/assert'; -import '../ts3.1/buffer'; -import '../ts3.1/child_process'; -import '../ts3.1/cluster'; -import '../ts3.1/crypto'; -import '../ts3.1/dgram'; -import '../ts3.1/global'; -import '../ts3.1/http'; -import '../ts3.1/http2'; -import '../ts3.1/net'; -import '../ts3.1/os'; -import '../ts3.1/path'; -import '../ts3.1/perf_hooks'; -import '../ts3.1/process'; -import '../ts3.1/querystring'; -import '../ts3.1/readline'; -import '../ts3.1/repl'; -import '../ts3.1/stream'; -import '../ts3.1/tls'; -import '../ts3.1/tty'; -import '../ts3.1/util'; -import '../ts3.1/worker_threads'; -import '../ts3.1/zlib'; +import assert = require("assert"); +import * as fs from "fs"; +import * as url from "url"; +import * as util from "util"; +import * as http from "http"; +import * as https from "https"; +import * as console2 from "console"; +import * as timers from "timers"; +import * as dns from "dns"; +import * as inspector from "inspector"; +import * as trace_events from "trace_events"; +import * as dgram from "dgram"; +import Module = require("module"); -import { types, promisify } from 'util'; -import { BigIntStats, statSync, Stats } from 'fs'; +//////////////////////////////////////////////////// +/// Url tests : http://nodejs.org/api/url.html +//////////////////////////////////////////////////// + +{ + { + url.format(url.parse('http://www.example.com/xyz')); + + url.format('http://www.example.com/xyz'); + + // https://google.com/search?q=you're%20a%20lizard%2C%20gary + url.format({ + protocol: 'https', + host: "google.com", + pathname: 'search', + query: { q: "you're a lizard, gary" } + }); + + const myURL = new url.URL('https://a:b@你好你好?abc#foo'); + url.format(myURL, { fragment: false, unicode: true, auth: false }); + } + + { + const helloUrl = url.parse('http://example.com/?hello=world', true); + let helloQuery = helloUrl.query['hello']; + assert.equal(helloUrl.query['hello'], 'world'); + + let strUrl = url.parse('http://example.com/?hello=world'); + let queryStr: string = strUrl.query!; + + strUrl = url.parse('http://example.com/?hello=world', false); + queryStr = strUrl.query!; + + function getBoolean(): boolean { return false; } + const urlUrl = url.parse('http://example.com/?hello=world', getBoolean()); + if (typeof(urlUrl.query) === 'string') { + queryStr = urlUrl.query; + } else if (urlUrl.query) { + helloQuery = urlUrl.query['hello']; + } + } + + { + const ascii: string = url.domainToASCII('español.com'); + const unicode: string = url.domainToUnicode('xn--espaol-zwa.com'); + } + + { + let myURL = new url.URL('https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert.equal(myURL.hash, '#bar'); + assert.equal(myURL.host, 'example.org:81'); + assert.equal(myURL.hostname, 'example.org'); + assert.equal(myURL.href, 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert.equal(myURL.origin, 'https://example.org:81'); + assert.equal(myURL.password, 'thepwd'); + assert.equal(myURL.username, 'theuser'); + assert.equal(myURL.pathname, '/foo/path'); + assert.equal(myURL.port, "81"); + assert.equal(myURL.protocol, "https:"); + assert.equal(myURL.search, "?query=string"); + assert.equal(myURL.toString(), 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert(myURL.searchParams instanceof url.URLSearchParams); + + myURL.host = 'example.org:82'; + myURL.hostname = 'example.com'; + myURL.href = 'http://other.com'; + myURL.hash = 'baz'; + myURL.password = "otherpwd"; + myURL.username = "otheruser"; + myURL.pathname = "/otherPath"; + myURL.port = "82"; + myURL.protocol = "http"; + myURL.search = "a=b"; + assert.equal(myURL.href, 'http://otheruser:otherpwd@other.com:82/otherPath?a=b#baz'); + + myURL = new url.URL('/foo', 'https://example.org/'); + assert.equal(myURL.href, 'https://example.org/foo'); + assert.equal(myURL.toJSON(), myURL.href); + } + + { + const searchParams = new url.URLSearchParams('abc=123'); + + assert.equal(searchParams.toString(), 'abc=123'); + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { + assert.equal(name, 'abc'); + assert.equal(value, '123'); + assert.equal(me, searchParams); + }); + + assert.equal(searchParams.get('abc'), '123'); + + searchParams.append('abc', 'xyz'); + + assert.deepEqual(searchParams.getAll('abc'), ['123', 'xyz']); + + const entries = searchParams.entries(); + assert.deepEqual(entries.next(), { value: ["abc", "123"], done: false }); + assert.deepEqual(entries.next(), { value: ["abc", "xyz"], done: false }); + assert.deepEqual(entries.next(), { value: undefined, done: true }); + + const keys = searchParams.keys(); + assert.deepEqual(keys.next(), { value: "abc", done: false }); + assert.deepEqual(keys.next(), { value: "abc", done: false }); + assert.deepEqual(keys.next(), { value: undefined, done: true }); + + const values = searchParams.values(); + assert.deepEqual(values.next(), { value: "123", done: false }); + assert.deepEqual(values.next(), { value: "xyz", done: false }); + assert.deepEqual(values.next(), { value: undefined, done: true }); + + searchParams.set('abc', 'b'); + assert.deepEqual(searchParams.getAll('abc'), ['b']); + + searchParams.delete('a'); + assert(!searchParams.has('a')); + assert.equal(searchParams.get('a'), null); + + searchParams.sort(); + } + + { + const searchParams = new url.URLSearchParams({ + user: 'abc', + query: ['first', 'second'] + }); + + assert.equal(searchParams.toString(), 'user=abc&query=first%2Csecond'); + assert.deepEqual(searchParams.getAll('query'), ['first,second']); + } + + { + // Using an array + const params = new url.URLSearchParams([ + ['user', 'abc'], + ['query', 'first'], + ['query', 'second'], + // ts 2.1/2.* compatibility + // tslint:disable-next-line no-unnecessary-type-assertion + ] as Array<[string, string]>); + assert.equal(params.toString(), 'user=abc&query=first&query=second'); + } + + { + let path: string = url.fileURLToPath('file://test'); + path = url.fileURLToPath(new url.URL('file://test')); + } + + { + const path: url.URL = url.pathToFileURL('file://test'); + } +} + +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + +{ + let agent: https.Agent = new https.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256, + maxCachedSessions: 100, + timeout: 15000 + }); + + agent = https.globalAgent; + + https.request({ + agent: false + }); + https.request({ + agent + }); + https.request({ + agent: undefined + }); + + https.get('http://www.example.com/xyz'); + https.request('http://www.example.com/xyz'); + + https.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + https.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + + https.get(new url.URL('http://www.example.com/xyz')); + https.request(new url.URL('http://www.example.com/xyz')); + + https.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + https.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + + const opts: https.RequestOptions = { + path: '/some/path' + }; + https.get(new url.URL('http://www.example.com'), opts); + https.request(new url.URL('http://www.example.com'), opts); + https.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + https.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + + https.globalAgent.options.ca = []; + + { + function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} + + class MyIncomingMessage extends http.IncomingMessage { + foo: number; + } + + class MyServerResponse extends http.ServerResponse { + foo: string; + } + + let server: https.Server; + + server = new https.Server(); + server = new https.Server(reqListener); + server = new https.Server({ IncomingMessage: MyIncomingMessage}); + + server = new https.Server({ + IncomingMessage: MyIncomingMessage, + ServerResponse: MyServerResponse + }, reqListener); + + server = https.createServer(); + server = https.createServer(reqListener); + server = https.createServer({ IncomingMessage: MyIncomingMessage }); + server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); + + const timeout: number = server.timeout; + const listening: boolean = server.listening; + const keepAliveTimeout: number = server.keepAliveTimeout; + const maxHeadersCount: number | null = server.maxHeadersCount; + const headersTimeout: number = server.headersTimeout; + server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); + } +} + +///////////////////////////////////////////////////// +/// Timers tests : https://nodejs.org/api/timers.html +///////////////////////////////////////////////////// + +{ + { + const immediate = timers + .setImmediate(() => { + console.log('immediate'); + }) + .unref() + .ref(); + const b: boolean = immediate.hasRef(); + timers.clearImmediate(immediate); + } + { + const timeout = timers + .setInterval(() => { + console.log('interval'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearInterval(timeout); + } + { + const timeout = timers + .setTimeout(() => { + console.log('timeout'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearTimeout(timeout); + } + async function testPromisify() { + const setTimeout = util.promisify(timers.setTimeout); + let v: void = await setTimeout(100); // tslint:disable-line no-void-expression void-return + let s: string = await setTimeout(100, ""); + + const setImmediate = util.promisify(timers.setImmediate); + v = await setImmediate(); // tslint:disable-line no-void-expression + s = await setImmediate(""); + } +} + +///////////////////////////////////////////////////////// +/// Errors Tests : https://nodejs.org/api/errors.html /// +///////////////////////////////////////////////////////// + +{ + { + Error.stackTraceLimit = Infinity; + } + { + const myObject = {}; + Error.captureStackTrace(myObject); + } + { + const frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace!(new Error(), frames); + } + { + const frame: NodeJS.CallSite = null!; + const frameThis: any = frame.getThis(); + const typeName: string | null = frame.getTypeName(); + const func: Function | undefined = frame.getFunction(); + const funcName: string | null = frame.getFunctionName(); + const meth: string | null = frame.getMethodName(); + const fname: string | null = frame.getFileName(); + const lineno: number | null = frame.getLineNumber(); + const colno: number | null = frame.getColumnNumber(); + const evalOrigin: string | undefined = frame.getEvalOrigin(); + const isTop: boolean = frame.isToplevel(); + const isEval: boolean = frame.isEval(); + const isNative: boolean = frame.isNative(); + const isConstr: boolean = frame.isConstructor(); + } +} + +/////////////////////////////////////////////////////////// +/// Console Tests : https://nodejs.org/api/console.html /// +/////////////////////////////////////////////////////////// + +{ + { + let _c: Console = console; + _c = console2; + } + { + const writeStream = fs.createWriteStream('./index.d.ts'); + let consoleInstance: Console = new console.Console(writeStream); + + consoleInstance = new console.Console(writeStream, writeStream); + consoleInstance = new console.Console(writeStream, writeStream, true); + consoleInstance = new console.Console({ + stdout: writeStream, + stderr: writeStream, + colorMode: 'auto', + ignoreErrors: true + }); + consoleInstance = new console.Console({ + stdout: writeStream, + colorMode: false + }); + consoleInstance = new console.Console({ + stdout: writeStream + }); + } + { + console.assert('value'); + console.assert('value', 'message'); + console.assert('value', 'message', 'foo', 'bar'); + console.clear(); + console.count(); + console.count('label'); + console.countReset(); + console.countReset('label'); + console.debug(); + console.debug('message'); + console.debug('message', 'foo', 'bar'); + console.dir('obj'); + console.dir('obj', { depth: 1 }); + console.error(); + console.error('message'); + console.error('message', 'foo', 'bar'); + console.group(); + console.group('label'); + console.group('label1', 'label2'); + console.groupCollapsed(); + console.groupEnd(); + console.info(); + console.info('message'); + console.info('message', 'foo', 'bar'); + console.log(); + console.log('message'); + console.log('message', 'foo', 'bar'); + console.table({ foo: 'bar' }); + console.table([{ foo: 'bar' }]); + console.table([{ foo: 'bar' }], ['foo']); + console.time(); + console.time('label'); + console.timeEnd(); + console.timeEnd('label'); + console.timeLog(); + console.timeLog('label'); + console.timeLog('label', 'foo', 'bar'); + console.trace(); + console.trace('message'); + console.trace('message', 'foo', 'bar'); + console.warn(); + console.warn('message'); + console.warn('message', 'foo', 'bar'); + + // --- Inspector mode only --- + console.markTimeline(); + console.markTimeline('label'); + console.profile(); + console.profile('label'); + console.profileEnd(); + console.profileEnd('label'); + console.timeStamp(); + console.timeStamp('label'); + console.timeline(); + console.timeline('label'); + console.timelineEnd(); + console.timelineEnd('label'); + } +} + +/////////////////////////////////////////////////// +/// DNS Tests : https://nodejs.org/api/dns.html /// +/////////////////////////////////////////////////// + +{ + dns.lookup("nodejs.org", (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 4, (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 6, (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", {}, (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup( + "nodejs.org", + { + family: 4, + hints: dns.ADDRCONFIG | dns.V4MAPPED, + all: false + }, + (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + } + ); + dns.lookup("nodejs.org", { all: true }, (err, addresses) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: dns.LookupAddress[] = addresses; + }); + dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: dns.LookupAddress[] = addresses; + }); + + function trueOrFalse(): boolean { + return Math.random() > 0.5 ? true : false; + } + dns.lookup("nodejs.org", { all: trueOrFalse() }, (err, addresses, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _addresses: string | dns.LookupAddress[] = addresses; + const _family: number | undefined = family; + }); + + dns.lookupService("127.0.0.1", 0, (err, hostname, service) => { + const _err: NodeJS.ErrnoException | null = err; + const _hostname: string = hostname; + const _service: string = service; + }); + + dns.resolve("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "A", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "AAAA", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "ANY", (err, addresses) => { + const _addresses: dns.AnyRecord[] = addresses; + }); + dns.resolve("nodejs.org", "MX", (err, addresses) => { + const _addresses: dns.MxRecord[] = addresses; + }); + + dns.resolve4("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve4("nodejs.org", { ttl: true }, (err, addresses) => { + const _addresses: dns.RecordWithTtl[] = addresses; + }); + { + const ttl = false; + dns.resolve4("nodejs.org", { ttl }, (err, addresses) => { + const _addresses: string[] | dns.RecordWithTtl[] = addresses; + }); + } + + dns.resolve6("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve6("nodejs.org", { ttl: true }, (err, addresses) => { + const _addresses: dns.RecordWithTtl[] = addresses; + }); + { + const ttl = false; + dns.resolve6("nodejs.org", { ttl }, (err, addresses) => { + const _addresses: string[] | dns.RecordWithTtl[] = addresses; + }); + } + { + const resolver = new dns.Resolver(); + resolver.setServers(["4.4.4.4"]); + resolver.resolve("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + resolver.cancel(); + } +} + +/***************************************************************************** + * * + * The following tests are the modules not mentioned in document but existed * + * * + *****************************************************************************/ + +/////////////////////////////////////////////////////////// +/// Constants Tests /// +/////////////////////////////////////////////////////////// + +import * as constants from 'constants'; +{ + let str: string; + let num: number; + num = constants.SIGHUP; + num = constants.SIGINT; + num = constants.SIGQUIT; + num = constants.SIGILL; + num = constants.SIGTRAP; + num = constants.SIGABRT; + num = constants.SIGIOT; + num = constants.SIGBUS; + num = constants.SIGFPE; + num = constants.SIGKILL; + num = constants.SIGUSR1; + num = constants.SIGSEGV; + num = constants.SIGUSR2; + num = constants.SIGPIPE; + num = constants.SIGALRM; + num = constants.SIGTERM; + num = constants.SIGCHLD; + num = constants.SIGSTKFLT; + num = constants.SIGCONT; + num = constants.SIGSTOP; + num = constants.SIGTSTP; + num = constants.SIGTTIN; + num = constants.SIGTTOU; + num = constants.SIGURG; + num = constants.SIGXCPU; + num = constants.SIGXFSZ; + num = constants.SIGVTALRM; + num = constants.SIGPROF; + num = constants.SIGWINCH; + num = constants.SIGIO; + num = constants.SIGPOLL; + num = constants.SIGPWR; + num = constants.SIGSYS; + num = constants.SIGUNUSED; + num = constants.O_RDONLY; + num = constants.O_WRONLY; + num = constants.O_RDWR; + num = constants.S_IFMT; + num = constants.S_IFREG; + num = constants.S_IFDIR; + num = constants.S_IFCHR; + num = constants.S_IFBLK; + num = constants.S_IFIFO; + num = constants.S_IFLNK; + num = constants.S_IFSOCK; + num = constants.O_CREAT; + num = constants.O_EXCL; + num = constants.O_NOCTTY; + num = constants.O_TRUNC; + num = constants.O_APPEND; + num = constants.O_DIRECTORY; + num = constants.O_NOATIME; + num = constants.O_NOFOLLOW; + num = constants.O_SYNC; + num = constants.O_DSYNC; + num = constants.O_DIRECT; + num = constants.O_NONBLOCK; + num = constants.S_IRWXU; + num = constants.S_IRUSR; + num = constants.S_IWUSR; + num = constants.S_IXUSR; + num = constants.S_IRWXG; + num = constants.S_IRGRP; + num = constants.S_IWGRP; + num = constants.S_IXGRP; + num = constants.S_IRWXO; + num = constants.S_IROTH; + num = constants.S_IWOTH; + num = constants.S_IXOTH; + num = constants.F_OK; + num = constants.R_OK; + num = constants.W_OK; + num = constants.X_OK; + num = constants.SSL_OP_ALL; + num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION; + num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE; + num = constants.SSL_OP_CISCO_ANYCONNECT; + num = constants.SSL_OP_COOKIE_EXCHANGE; + num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG; + num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; + num = constants.SSL_OP_EPHEMERAL_RSA; + num = constants.SSL_OP_LEGACY_SERVER_CONNECT; + num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER; + num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG; + num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING; + num = constants.SSL_OP_NETSCAPE_CA_DN_BUG; + num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG; + num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG; + num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; + num = constants.SSL_OP_NO_COMPRESSION; + num = constants.SSL_OP_NO_QUERY_MTU; + num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION; + num = constants.SSL_OP_NO_SSLv2; + num = constants.SSL_OP_NO_SSLv3; + num = constants.SSL_OP_NO_TICKET; + num = constants.SSL_OP_NO_TLSv1; + num = constants.SSL_OP_NO_TLSv1_1; + num = constants.SSL_OP_NO_TLSv1_2; + num = constants.SSL_OP_PKCS1_CHECK_1; + num = constants.SSL_OP_PKCS1_CHECK_2; + num = constants.SSL_OP_SINGLE_DH_USE; + num = constants.SSL_OP_SINGLE_ECDH_USE; + num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG; + num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG; + num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG; + num = constants.SSL_OP_TLS_D5_BUG; + num = constants.SSL_OP_TLS_ROLLBACK_BUG; + num = constants.ENGINE_METHOD_RSA; + num = constants.ENGINE_METHOD_DSA; + num = constants.ENGINE_METHOD_DH; + num = constants.ENGINE_METHOD_RAND; + num = constants.ENGINE_METHOD_ECDH; + num = constants.ENGINE_METHOD_ECDSA; + num = constants.ENGINE_METHOD_CIPHERS; + num = constants.ENGINE_METHOD_DIGESTS; + num = constants.ENGINE_METHOD_STORE; + num = constants.ENGINE_METHOD_PKEY_METHS; + num = constants.ENGINE_METHOD_PKEY_ASN1_METHS; + num = constants.ENGINE_METHOD_ALL; + num = constants.ENGINE_METHOD_NONE; + num = constants.DH_CHECK_P_NOT_SAFE_PRIME; + num = constants.DH_CHECK_P_NOT_PRIME; + num = constants.DH_UNABLE_TO_CHECK_GENERATOR; + num = constants.DH_NOT_SUITABLE_GENERATOR; + num = constants.ALPN_ENABLED; + num = constants.RSA_PKCS1_PADDING; + num = constants.RSA_SSLV23_PADDING; + num = constants.RSA_NO_PADDING; + num = constants.RSA_PKCS1_OAEP_PADDING; + num = constants.RSA_X931_PADDING; + num = constants.RSA_PKCS1_PSS_PADDING; + num = constants.POINT_CONVERSION_COMPRESSED; + num = constants.POINT_CONVERSION_UNCOMPRESSED; + num = constants.POINT_CONVERSION_HYBRID; + str = constants.defaultCoreCipherList; + str = constants.defaultCipherList; +} + +/////////////////////////////////////////////////////////// +/// Inspector Tests /// +/////////////////////////////////////////////////////////// + +{ + { + const b: inspector.Console.ConsoleMessage = {source: 'test', text: 'test', level: 'error' }; + inspector.open(); + inspector.open(0); + inspector.open(0, 'localhost'); + inspector.open(0, 'localhost', true); + inspector.close(); + const inspectorUrl: string | undefined = inspector.url(); + + const session = new inspector.Session(); + session.connect(); + session.disconnect(); + + // Unknown post method + session.post('A.b', { key: 'value' }, (err, params) => {}); + // TODO: parameters are implicitly 'any' and need type annotation + session.post('A.b', (err: Error | null, params?: {}) => {}); + session.post('A.b'); + // Known post method + const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; + session.post('Runtime.evaluate', parameter, + (err: Error | null, params: inspector.Runtime.EvaluateReturnType) => {}); + session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { + const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails!; + const resultClassName: string = params.result.className!; + }); + session.post('Runtime.evaluate'); + + // General event + session.on('inspectorNotification', message => { + message; // $ExpectType InspectorNotification<{}> + }); + // Known events + session.on('Debugger.paused', (message: inspector.InspectorNotification) => { + const method: string = message.method; + const pauseReason: string = message.params.reason; + }); + session.on('Debugger.resumed', () => {}); + // Node Inspector events + session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification) => { + const value: Array<{}> = message.params.value; + }); + } +} + +/////////////////////////////////////////////////////////// +/// Trace Events Tests /// +/////////////////////////////////////////////////////////// + +{ + const enabledCategories: string | undefined = trace_events.getEnabledCategories(); + const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] }); + const categories: string = tracing.categories; + const enabled: boolean = tracing.enabled; + tracing.enable(); + tracing.disable(); +} + +//////////////////////////////////////////////////// +/// module tests : http://nodejs.org/api/modules.html +//////////////////////////////////////////////////// +import moduleModule = require('module'); + +{ + require.extensions[".ts"] = () => ""; + + Module.runMain(); + const s: string = Module.wrap("some code"); + + const m1: Module = new Module("moduleId"); + const m2: Module = new Module.Module("moduleId"); + const b: string[] = Module.builtinModules; + let paths: string[] = module.paths; + const path: string = module.path; + paths = m1.paths; + + const customRequire1 = moduleModule.createRequireFromPath('./test'); + const customRequire2 = moduleModule.createRequire('./test'); + + customRequire1('test'); + customRequire2('test'); + + const resolved1: string = customRequire1.resolve('test'); + const resolved2: string = customRequire2.resolve('test'); + + const paths1: string[] | null = customRequire1.resolve.paths('test'); + const paths2: string[] | null = customRequire2.resolve.paths('test'); + + const cachedModule1: Module = customRequire1.cache['/path/to/module.js']; + const cachedModule2: Module = customRequire2.cache['/path/to/module.js']; + + const main1: Module | undefined = customRequire1.main; + const main2: Module | undefined = customRequire2.main; +} + +///////////////////////////////////////////////////////// +/// stream tests : https://nodejs.org/api/stream.html /// +///////////////////////////////////////////////////////// +import stream = require('stream'); +import tty = require('tty'); + +{ + const writeStream = fs.createWriteStream('./index.d.ts'); + const _wom = writeStream.writableObjectMode; // $ExpectType boolean + + const readStream = fs.createReadStream('./index.d.ts'); + const _rom = readStream.readableObjectMode; // $ExpectType boolean + + const x: stream.Readable = process.stdin; + const stdin: tty.ReadStream = process.stdin; + const stdout: tty.WriteStream = process.stdout; + const stderr: tty.WriteStream = process.stderr; +} + +///////////////////////////////////////////////////////// +/// dgram tests : https://nodejs.org/api/dgram.html /// +///////////////////////////////////////////////////////// +{ + let sock: dgram.Socket = dgram.createSocket("udp4"); + sock = dgram.createSocket({ type: "udp4" }); + sock = dgram.createSocket({ + type: "udp4", + reuseAddr: true, + ipv6Only: false, + recvBufferSize: 4096, + sendBufferSize: 4096, + lookup: dns.lookup, + }); + sock = dgram.createSocket("udp6", (msg, rinfo) => { + msg; // $ExpectType Buffer + rinfo; // $ExpectType RemoteInfo + }); + sock.addMembership("233.252.0.0"); + sock.addMembership("233.252.0.0", "192.0.2.1"); + sock.address().address; // $ExpectType string + sock.address().family; // $ExpectType string + sock.address().port; // $ExpectType number + sock.bind(); + sock.bind(() => undefined); + sock.bind(8000); + sock.bind(8000, () => undefined); + sock.bind(8000, "192.0.2.1"); + sock.bind(8000, "192.0.2.1", () => undefined); + sock.bind({}, () => undefined); + sock.bind({ port: 8000, address: "192.0.2.1", exclusive: true }); + sock.bind({ fd: 7, exclusive: true }); + sock.close(); + sock.close(() => undefined); + sock.connect(8000); + sock.connect(8000, "192.0.2.1"); + sock.connect(8000, () => undefined); + sock.connect(8000, "192.0.2.1", () => undefined); + sock.disconnect(); + sock.dropMembership("233.252.0.0"); + sock.dropMembership("233.252.0.0", "192.0.2.1"); + sock.getRecvBufferSize(); // $ExpectType number + sock.getSendBufferSize(); // $ExpectType number + sock = sock.ref(); + sock.remoteAddress().address; // $ExpectType string + sock.remoteAddress().family; // $ExpectType string + sock.remoteAddress().port; // $ExpectType number + sock.send("datagram"); + sock.send(new Uint8Array(256), 8000, (err) => { + err; // $ExpectType Error | null + }); + sock.send(Buffer.alloc(256), 8000, "192.0.2.1"); + sock.send(new Uint8Array(256), 128, 64); + sock.send("datagram", 128, 64, (err) => undefined); + sock.send(new Uint8Array(256), 128, 64, 8000); + sock.send(new Uint8Array(256), 128, 64, 8000, (err) => undefined); + sock.send(Buffer.alloc(256), 128, 64, 8000, "192.0.2.1"); + sock.send("datagram", 128, 64, 8000, "192.0.2.1", (err) => undefined); + sock.setBroadcast(true); + sock.setMulticastInterface("192.0.2.1"); + sock.setMulticastLoopback(false); + sock.setMulticastTTL(128); + sock.setRecvBufferSize(4096); + sock.setSendBufferSize(4096); + sock.setTTL(128); + sock = sock.unref(); + + sock.on("close", () => undefined); + sock.on("connect", () => undefined); + sock.on("error", (exception) => { + exception; // $ExpectType Error + }); + sock.on("listening", () => undefined); + sock.on("message", (msg, rinfo) => { + msg; // $ExpectType Buffer + rinfo.address; // $ExpectType string + rinfo.family; // $ExpectType "IPv4" | "IPv6" + rinfo.port; // $ExpectType number + rinfo.size; // $ExpectType number + }); +} + +//////////////////////////////////////////////////// +/// Node.js ESNEXT Support +//////////////////////////////////////////////////// + +{ + const s = 'foo'; + const s1: string = s.trimLeft(); + const s2: string = s.trimRight(); + const s3: string = s.trimStart(); + const s4: string = s.trimEnd(); +} ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -39,10 +911,10 @@ import { BigIntStats, statSync, Stats } from 'fs'; // Util Tests { const value: BigInt64Array | BigUint64Array | number = [] as any; - if (types.isBigInt64Array(value)) { + if (util.types.isBigInt64Array(value)) { // $ExpectType BigInt64Array const b = value; - } else if (types.isBigUint64Array(value)) { + } else if (util.types.isBigUint64Array(value)) { // $ExpectType BigUint64Array const b = value; } else { @@ -50,14 +922,14 @@ import { BigIntStats, statSync, Stats } from 'fs'; const b = value; } - const arg1UnknownError: (arg: string) => Promise = promisify((arg: string, cb: (err: unknown, result: number) => void): void => { }); - const arg1AnyError: (arg: string) => Promise = promisify((arg: string, cb: (err: any, result: number) => void): void => { }); + const arg1UnknownError: (arg: string) => Promise = util.promisify((arg: string, cb: (err: unknown, result: number) => void): void => { }); + const arg1AnyError: (arg: string) => Promise = util.promisify((arg: string, cb: (err: any, result: number) => void): void => { }); } // FS Tests { - const bigStats: BigIntStats = statSync('.', { bigint: true }); - const anyStats: Stats | BigIntStats = statSync('.', { bigint: Math.random() > 0.5 }); + const bigStats: fs.BigIntStats = fs.statSync('.', { bigint: true }); + const anyStats: fs.Stats | fs.BigIntStats = fs.statSync('.', { bigint: Math.random() > 0.5 }); } // Global Tests diff --git a/types/node/v12/ts3.3/tslint.json b/types/node/v12/ts3.3/tslint.json index 56086bb86a..65e8b18d2a 100644 --- a/types/node/v12/ts3.3/tslint.json +++ b/types/node/v12/ts3.3/tslint.json @@ -1,6 +1,10 @@ { "extends": "dtslint/dt.json", "rules": { - "no-bad-reference": false + "ban-types": false, + "no-bad-reference": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "unified-signatures": false } } diff --git a/types/node/v12/ts3.6/index.d.ts b/types/node/v12/ts3.6/index.d.ts index abd760c87c..dc2155d011 100644 --- a/types/node/v12/ts3.6/index.d.ts +++ b/types/node/v12/ts3.6/index.d.ts @@ -5,4 +5,4 @@ /// // tslint:disable-next-line:no-bad-reference -/// +/// diff --git a/types/node/v12/util.d.ts b/types/node/v12/util.d.ts index 56a879e854..a23138addb 100644 --- a/types/node/v12/util.d.ts +++ b/types/node/v12/util.d.ts @@ -1,15 +1,187 @@ -// tslint:disable-next-line:no-bad-reference -/// - declare module "util" { + interface InspectOptions extends NodeJS.InspectOptions { } + function format(format: any, ...param: any[]): string; + function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; + /** @deprecated since v0.11.3 - use a third party module instead. */ + function log(string: string): void; + function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + function inspect(object: any, options: InspectOptions): string; namespace inspect { const custom: unique symbol; + let colors: { + [color: string]: [number, number] | undefined + }; + let styles: { + [style: string]: string | undefined + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; } + /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ + function isArray(object: any): object is any[]; + /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ + function isRegExp(object: any): object is RegExp; + /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ + function isDate(object: any): object is Date; + /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ + function isError(object: any): object is Error; + function inherits(constructor: any, superConstructor: any): void; + function debuglog(key: string): (msg: string, ...param: any[]) => void; + /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ + function isBoolean(object: any): object is boolean; + /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ + function isBuffer(object: any): object is Buffer; + /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ + function isFunction(object: any): boolean; + /** @deprecated since v4.0.0 - use `value === null` instead. */ + function isNull(object: any): object is null; + /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ + function isNullOrUndefined(object: any): object is null | undefined; + /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ + function isNumber(object: any): object is number; + /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ + function isObject(object: any): boolean; + /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ + function isPrimitive(object: any): boolean; + /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ + function isString(object: any): object is string; + /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ + function isSymbol(object: any): object is symbol; + /** @deprecated since v4.0.0 - use `value === undefined` instead. */ + function isUndefined(object: any): object is undefined; + function deprecate(fn: T, message: string, code?: string): T; + function isDeepStrictEqual(val1: any, val2: any): boolean; + + interface CustomPromisify extends Function { + __promisify__: TCustom; + } + + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + + function promisify(fn: CustomPromisify): TCustom; + function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; + function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): + (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): + (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify(fn: Function): Function; namespace promisify { const custom: unique symbol; } + namespace types { + function isAnyArrayBuffer(object: any): boolean; + function isArgumentsObject(object: any): object is IArguments; + function isArrayBuffer(object: any): object is ArrayBuffer; + function isArrayBufferView(object: any): object is ArrayBufferView; + function isAsyncFunction(object: any): boolean; function isBigInt64Array(value: any): value is BigInt64Array; function isBigUint64Array(value: any): value is BigUint64Array; + function isBooleanObject(object: any): object is Boolean; + function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); + function isDataView(object: any): object is DataView; + function isDate(object: any): object is Date; + function isExternal(object: any): boolean; + function isFloat32Array(object: any): object is Float32Array; + function isFloat64Array(object: any): object is Float64Array; + function isGeneratorFunction(object: any): boolean; + function isGeneratorObject(object: any): boolean; + function isInt8Array(object: any): object is Int8Array; + function isInt16Array(object: any): object is Int16Array; + function isInt32Array(object: any): object is Int32Array; + function isMap(object: any): boolean; + function isMapIterator(object: any): boolean; + function isModuleNamespaceObject(value: any): boolean; + function isNativeError(object: any): object is Error; + function isNumberObject(object: any): object is Number; + function isPromise(object: any): boolean; + function isProxy(object: any): boolean; + function isRegExp(object: any): object is RegExp; + function isSet(object: any): boolean; + function isSetIterator(object: any): boolean; + function isSharedArrayBuffer(object: any): boolean; + function isStringObject(object: any): boolean; + function isSymbolObject(object: any): boolean; + function isTypedArray(object: any): object is NodeJS.TypedArray; + function isUint8Array(object: any): object is Uint8Array; + function isUint8ClampedArray(object: any): object is Uint8ClampedArray; + function isUint16Array(object: any): object is Uint16Array; + function isUint32Array(object: any): object is Uint32Array; + function isWeakMap(object: any): boolean; + function isWeakSet(object: any): boolean; + function isWebAssemblyCompiledModule(object: any): boolean; + } + + class TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { fatal?: boolean; ignoreBOM?: boolean } + ); + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { stream?: boolean } + ): string; + } + + interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + + class TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; + encodeInto(input: string, output: Uint8Array): EncodeIntoResult; } } diff --git a/types/node/v13/fs.d.ts b/types/node/v13/fs.d.ts index f0ae01b17c..cff06bd489 100644 --- a/types/node/v13/fs.d.ts +++ b/types/node/v13/fs.d.ts @@ -1,7 +1,2653 @@ -// tslint:disable-next-line:no-bad-reference -/// +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + import { URL } from "url"; + + /** + * Valid types for path values in "fs". + */ + type PathLike = string | Buffer | URL; + + type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + + interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + interface Stats extends StatsBase { + } + + class Stats { + } + + class Dirent { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + name: string; + } + + /** + * A class representing a directory stream. + */ + class Dir { + readonly path: string; + + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + */ + close(): Promise; + close(cb: NoParamCallback): void; + + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + */ + closeSync(): void; + + /** + * Asynchronously read the next directory entry via `readdir(3)` as an `Dirent`. + * After the read is completed, a value is returned that will be resolved with an `Dirent`, or `null` if there are no more directory entries to read. + * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + + /** + * Synchronously read the next directory entry via `readdir(3)` as a `Dirent`. + * If there are no more directory entries to read, null will be returned. + * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. + */ + readSync(): Dirent; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + class ReadStream extends stream.Readable { + close(): void; + bytesRead: number; + path: string | Buffer; + pending: boolean; + + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "ready", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "ready", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + class WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + pending: boolean; + + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + 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: "open", listener: (fd: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "ready", listener: () => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function renameSync(oldPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function truncate(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + + /** + * Synchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncateSync(path: PathLike, len?: number | null): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + function ftruncate(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + + /** + * Synchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + + /** + * Synchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchownSync(fd: number, uid: number, gid: number): void; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(fd: number, mode: string | number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: string | number): Promise; + } + + /** + * Synchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmodSync(fd: number, mode: string | number): void; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike, options: BigIntOptions, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; + function stat(path: PathLike, options: StatOptions, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options: BigIntOptions): Promise; + function __promisify__(path: PathLike, options: StatOptions): Promise; + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function statSync(path: PathLike, options: BigIntOptions): BigIntStats; + function statSync(path: PathLike, options: StatOptions): Stats | BigIntStats; + function statSync(path: PathLike): Stats; + + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstatSync(fd: number): Stats; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstatSync(path: PathLike): Stats; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function linkSync(existingPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + + type Type = "dir" | "file" | "junction"; + } + + /** + * Synchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink( + path: PathLike, + options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void + ): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void + ): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + function native( + path: PathLike, + options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void + ): void; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + } + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + namespace realpathSync { + function native(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + function native(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + } + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlinkSync(path: PathLike): void; + + interface RmDirOptions { + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, errors are not reported if `path` does not exist, and + * operations are retried on failure. + * @experimental + * @default false + */ + recursive?: boolean; + } + + interface RmDirAsyncOptions extends RmDirOptions { + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number; + } + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike, callback: NoParamCallback): void; + function rmdir(path: PathLike, options: RmDirAsyncOptions, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirAsyncOptions): Promise; + } + + /** + * Synchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdirSync(path: PathLike, options?: RmDirOptions): void; + + interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: number | string; + } + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true }, callback: (err: NodeJS.ErrnoException | null, path: string) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options: number | string | (MakeDirectoryOptions & { recursive?: false; }) | null | undefined, callback: NoParamCallback): void; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options: number | string | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path: string | undefined) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function mkdir(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: number | string | (MakeDirectoryOptions & { recursive?: false; }) | null): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; + } + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): string; + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync(path: PathLike, options?: number | string | (MakeDirectoryOptions & { recursive?: false; }) | null): void; + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): string | undefined; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes: true }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Promise; + } + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdirSync(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Dirent[]; + + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function close(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function closeSync(fd: number): void; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise; + } + + /** + * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsync(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsyncSync(fd: number): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write( + fd: number, + string: any, + position: number | undefined | null, + encoding: string | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + */ + function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + } + + /** + * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; + + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; + + /** + * Asynchronously reads data from the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null + ): Promise<{ bytesRead: number, buffer: TBuffer }>; + } + + interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number; + /** + * @default `length of buffer` + */ + length?: number; + /** + * @default null + */ + position?: number | null; + } + + /** + * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: number | null): number; + + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | number, + options: { encoding?: string | null; flag?: string; } | string | undefined | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, + ): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise; + } + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; + + type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: NoParamCallback): void; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function writeFile(path: PathLike | number, data: any, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: NoParamCallback): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function appendFile(file: PathLike | number, data: any, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + */ + function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Stop watching for changes on `filename`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, + listener?: (event: string, filename: string) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, + listener?: (event: string, filename: string | Buffer) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; + + /** + * Asynchronously tests whether or not the given path exists by checking with the file system. + * @deprecated + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function exists(path: PathLike, callback: (exists: boolean) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronously tests whether or not the given path exists by checking with the file system. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function existsSync(path: PathLike): boolean; + + namespace constants { + // File Access Constants + + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + + // File Copy Constants + + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + 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. */ + 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). + */ + 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. */ + const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + 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. + */ + const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + 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. */ + const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + 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. */ + 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. */ + const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + 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. */ + const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + 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. */ + const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + 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. */ + const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + + /** + * Synchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function accessSync(path: PathLike, mode?: number): void; + + /** + * Returns a new `ReadStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createReadStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + /** + * @default false + */ + emitClose?: boolean; + start?: number; + end?: number; + highWaterMark?: number; + }): ReadStream; + + /** + * Returns a new `WriteStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createWriteStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + emitClose?: boolean; + start?: number; + highWaterMark?: number; + }): WriteStream; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasync(fd: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasyncSync(fd: number): void; + + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + */ + function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags: number, callback: NoParamCallback): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace copyFile { + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, + * which causes the copy operation to fail if dest already exists. + */ + function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; + } + + /** + * Synchronously copies src to dest. By default, dest is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; + + /** + * Write an array of ArrayBufferViews to the file specified by fd using writev(). + * position is the offset from the beginning of the file where this data should be written. + * It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use fs.createWriteStream(). + * 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. + */ + function writev( + fd: number, + buffers: NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + function writev( + fd: number, + buffers: NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + + interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + + namespace writev { + function __promisify__(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): Promise; + } + + /** + * See `writev`. + */ + function writevSync(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): number; + + function readv( + fd: number, + buffers: NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + function readv( + fd: number, + buffers: NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + + interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + + namespace readv { + function __promisify__(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): Promise; + } + + /** + * See `readv`. + */ + function readvSync(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): number; + + interface OpenDirOptions { + encoding?: BufferEncoding; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number; + } + + function opendirSync(path: string, options?: OpenDirOptions): Dir; + + function opendir(path: string, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + function opendir(path: string, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + + namespace opendir { + function __promisify__(path: string, options?: OpenDirOptions): Promise; + } + + namespace promises { + interface FileHandle { + /** + * Gets the file descriptor for this file handle. + */ + readonly fd: number; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for appending. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + appendFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + */ + chown(uid: number, gid: number): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + chmod(mode: string | number): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + */ + datasync(): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + */ + sync(): Promise; + + /** + * Asynchronously reads data from the file. + * The `FileHandle` must have been opened for reading. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + read(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: null, flag?: string | number } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + */ + stat(): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param len If not specified, defaults to `0`. + */ + truncate(len?: number): Promise; + + /** + * Asynchronously change file timestamps of the file. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously writes `buffer` to the file. + * The `FileHandle` must have been opened for writing. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + write(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + write(data: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + writeFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * See `fs.writev` promisified version. + */ + writev(buffers: NodeJS.ArrayBufferView[], position?: number): Promise; + + /** + * See `fs.readv` promisified version. + */ + readv(buffers: NodeJS.ArrayBufferView[], position?: number): Promise; + + /** + * Asynchronous close(2) - close a `FileHandle`. + */ + close(): Promise; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode?: number): Promise; + + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. The only + * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if + * `dest` already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not + * supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode?: string | number): Promise; + + /** + * Asynchronously reads data from the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If + * `null`, data will be read from the current position. + */ + function read( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write(handle: FileHandle, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len?: number): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param handle A `FileHandle`. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(handle: FileHandle, len?: number): Promise; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike, options?: RmDirAsyncOptions): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param handle A `FileHandle`. + */ + function fdatasync(handle: FileHandle): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param handle A `FileHandle`. + */ + function fsync(handle: FileHandle): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: number | string | (MakeDirectoryOptions & { recursive?: false; }) | null): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + * @param handle A `FileHandle`. + */ + function fstat(handle: FileHandle): Promise; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike): Promise; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike): Promise; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param handle A `FileHandle`. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(handle: FileHandle, mode: string | number): Promise; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number): Promise; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number): Promise; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param handle A `FileHandle`. + */ + function fchown(handle: FileHandle, uid: number, gid: number): Promise; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: string | number } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; + + function opendir(path: string, options?: OpenDirOptions): Promise; + } -declare module 'fs' { interface BigIntStats extends StatsBase { } @@ -19,15 +2665,4 @@ declare module 'fs' { interface StatOptions { bigint: boolean; } - - function stat(path: PathLike, options: BigIntOptions, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; - function stat(path: PathLike, options: StatOptions, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; - - namespace stat { - function __promisify__(path: PathLike, options: BigIntOptions): Promise; - function __promisify__(path: PathLike, options: StatOptions): Promise; - } - - function statSync(path: PathLike, options: BigIntOptions): BigIntStats; - function statSync(path: PathLike, options: StatOptions): Stats | BigIntStats; } diff --git a/types/node/v13/globals.d.ts b/types/node/v13/globals.d.ts index 56ad634485..a40a054173 100644 --- a/types/node/v13/globals.d.ts +++ b/types/node/v13/globals.d.ts @@ -1,10 +1,414 @@ -// tslint:disable-next-line:no-bad-reference -/// +// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build +interface Console { + Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ + warn(message?: any, ...optionalParams: any[]): void; -declare namespace NodeJS { - interface HRTime { - bigint(): bigint; - } + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; +} + +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + + stackTraceLimit: number; +} + +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; + + /** Returns a copy with leading whitespace removed. */ + trimStart(): string; + /** Returns a copy with trailing whitespace removed. */ + trimEnd(): string; +} + +interface ImportMeta { + url: string; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + +// For backwards compability +interface NodeRequire extends NodeJS.Require {} +interface RequireResolve extends NodeJS.RequireResolve {} +interface NodeModule extends NodeJS.Module {} + +declare var process: NodeJS.Process; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T): Promise; +} +declare function clearTimeout(timeoutId: NodeJS.Timeout): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare function clearInterval(intervalId: NodeJS.Timeout): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; +declare namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T): Promise; +} +declare function clearImmediate(immediateId: NodeJS.Immediate): void; + +declare function queueMicrotask(callback: () => void): void; + +declare var require: NodeRequire; +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"; + +/** + * 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 class Buffer extends Uint8Array { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + constructor(str: string, encoding?: BufferEncoding); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + constructor(size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + constructor(array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + constructor(arrayBuffer: ArrayBuffer | SharedArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + constructor(array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + constructor(buffer: 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 any TypedArray or a new ArrayBuffer() + */ + static from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + static from(data: number[]): Buffer; + static from(data: Uint8Array): Buffer; + /** + * Creates a new buffer containing the coerced value of an object + * A `TypeError` will be thrown if {obj} has not mentioned methods or is not of other type appropriate for `Buffer.from()` variants. + * @param obj An object supporting `Symbol.toPrimitive` or `valueOf()`. + */ + static from(obj: { valueOf(): string | object } | { [Symbol.toPrimitive](hint: 'string'): string }, byteOffset?: number, length?: number): 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'. + */ + static from(str: string, encoding?: BufferEncoding): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + static of(...items: number[]): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static 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. + */ + static isEncoding(encoding: string): encoding is BufferEncoding; + /** + * 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 | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding + ): 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: Uint8Array[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Uint8Array, buf2: Uint8Array): 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 + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): 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 + */ + static 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 + */ + static allocUnsafeSlow(size: number): Buffer; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + static poolSize: number; + + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer'; data: number[] }; + equals(otherBuffer: Uint8Array): boolean; + compare( + otherBuffer: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number + ): number; + copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. + * + * This method is incompatible with `Uint8Array#slice()`, which returns a copy of the original memory. + * + * @param begin Where the new `Buffer` will start. Default: `0`. + * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. + */ + slice(begin?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. + * + * This method is compatible with `Uint8Array#subarray()`. + * + * @param begin Where the new `Buffer` will start. Default: `0`. + * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. + */ + subarray(begin?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number): number; + writeUIntBE(value: number, offset: number, byteLength: number): number; + writeIntLE(value: number, offset: number, byteLength: number): number; + writeIntBE(value: number, offset: number, byteLength: number): number; + readUIntLE(offset: number, byteLength: number): number; + readUIntBE(offset: number, byteLength: number): number; + readIntLE(offset: number, byteLength: number): number; + readIntBE(offset: number, byteLength: number): number; + readUInt8(offset?: number): number; + readUInt16LE(offset?: number): number; + readUInt16BE(offset?: number): number; + readUInt32LE(offset?: number): number; + readUInt32BE(offset?: number): number; + readInt8(offset?: number): number; + readInt16LE(offset?: number): number; + readInt16BE(offset?: number): number; + readInt32LE(offset?: number): number; + readInt32BE(offset?: number): number; + readFloatLE(offset?: number): number; + readFloatBE(offset?: number): number; + readDoubleLE(offset?: number): number; + readDoubleBE(offset?: number): number; + reverse(): this; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset?: number): number; + writeUInt16LE(value: number, offset?: number): number; + writeUInt16BE(value: number, offset?: number): number; + writeUInt32LE(value: number, offset?: number): number; + writeUInt32BE(value: number, offset?: number): number; + writeInt8(value: number, offset?: number): number; + writeInt16LE(value: number, offset?: number): number; + writeInt16BE(value: number, offset?: number): number; + writeInt32LE(value: number, offset?: number): number; + writeInt32BE(value: number, offset?: number): number; + writeFloatLE(value: number, offset?: number): number; + writeFloatBE(value: number, offset?: number): number; + writeDoubleLE(value: number, offset?: number): number; + writeDoubleBE(value: number, offset?: number): number; + + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + keys(): IterableIterator; + values(): IterableIterator; } interface Buffer extends Uint8Array { @@ -17,3 +421,717 @@ interface Buffer extends Uint8Array { writeBigUInt64BE(value: bigint, offset?: number): number; writeBigUInt64LE(value: bigint, offset?: number): number; } + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean; + showHidden?: boolean; + /** + * @default 2 + */ + depth?: number | null; + colors?: boolean; + customInspect?: boolean; + showProxy?: boolean; + maxArrayLength?: number | null; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default Infinity + */ + maxStringLength?: number | null; + breakLength?: number; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default `true` + */ + compact?: boolean | number; + sorted?: boolean | ((a: string, b: string) => number); + } + + interface ConsoleConstructorOptions { + stdout: WritableStream; + stderr?: WritableStream; + ignoreErrors?: boolean; + colorMode?: boolean | 'auto'; + inspectOptions?: InspectOptions; + } + + interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + + interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + interface EventEmitter { + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(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: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + eventNames(): Array; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: string, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): void; + end(data: string | Uint8Array, cb?: () => void): void; + end(str: string, encoding?: string, cb?: () => void): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface Domain extends EventEmitter { + run(fn: (...args: any[]) => T, ...args: any[]): T; + add(emitter: EventEmitter | Timer): void; + remove(emitter: EventEmitter | Timer): void; + bind(cb: T): T; + intercept(cb: T): T; + + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + } + + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; + } + + interface CpuUsage { + user: number; + system: number; + } + + interface ProcessRelease { + name: string; + sourceUrl?: string; + headersUrl?: string; + libUrl?: string; + lts?: string; + } + + interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | 'cygwin' + | 'netbsd'; + + type Signals = + "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | + "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | + "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type MultipleResolveType = 'resolve' | 'reject'; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = (signal: Signals) => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; + + interface Socket extends ReadWriteStream { + isTTY?: true; + } + + // Alias for compatibility + interface ProcessEnv extends Dict {} + + interface HRTime { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @defaul false + */ + reportOnSignal: boolean; + + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + + interface Process extends EventEmitter { + /** + * Can also be a tty.WriteStream, not typed due to limitation.s + */ + stdout: WriteStream; + /** + * Can also be a tty.WriteStream, not typed due to limitation.s + */ + stderr: WriteStream; + stdin: ReadStream; + openStdin(): Socket; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + debugPort: number; + emitWarning(warning: string | Error, name?: string, ctor?: Function): void; + env: ProcessEnv; + exit(code?: number): never; + exitCode?: number; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: Array): void; + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + hasUncaughtExceptionCaptureCallback(): boolean; + 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; + ppid: number; + title: string; + arch: string; + platform: Platform; + mainModule?: Module; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * Can only be set if not in worker thread. + */ + umask(mask?: number): number; + uptime(): number; + hrtime: HRTime; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; + disconnect(): void; + connected: boolean; + + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] + * environment variable. + */ + allowedNodeEnvironmentFlags: ReadonlySet; + + /** + * Only available with `--experimental-report` + */ + report?: ProcessReport; + + resourceUsage(): ResourceUsage; + + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; + + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + } + + 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: typeof Promise; + 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: typeof Uint8ClampedArray; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: Immediate) => void; + clearInterval: (intervalId: Timeout) => void; + clearTimeout: (timeoutId: Timeout) => 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; + /** + * @deprecated Use `global`. + */ + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + queueMicrotask: typeof queueMicrotask; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + interface RefCounted { + ref(): this; + unref(): this; + } + + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + } + + interface Immediate extends RefCounted { + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + } + + interface Timeout extends Timer { + hasRef(): boolean; + refresh(): this; + } + + type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + /* tslint:disable-next-line:callable-types */ + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + '.js': (m: Module, filename: string) => any; + '.json': (m: Module, filename: string) => any; + '.node': (m: Module, filename: string) => any; + } + interface Module { + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** + * @since 11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + parent: Module | null; + children: Module[]; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } +} diff --git a/types/node/v13/package.json b/types/node/v13/package.json index dd84e4f705..b17d6c5bc5 100644 --- a/types/node/v13/package.json +++ b/types/node/v13/package.json @@ -2,11 +2,6 @@ "private": true, "types": "index", "typesVersions": { - "<=3.1": { - "*": [ - "ts3.1/*" - ] - }, "<=3.4": { "*": [ "ts3.4/*" diff --git a/types/node/v13/ts3.1/base.d.ts b/types/node/v13/ts3.1/base.d.ts deleted file mode 100644 index 1be74c9f1b..0000000000 --- a/types/node/v13/ts3.1/base.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -// base definitions for all NodeJS modules that are not specific to any version of TypeScript -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// diff --git a/types/node/v13/ts3.1/fs.d.ts b/types/node/v13/ts3.1/fs.d.ts deleted file mode 100644 index ce8dbe19a9..0000000000 --- a/types/node/v13/ts3.1/fs.d.ts +++ /dev/null @@ -1,2644 +0,0 @@ -declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; - import { URL } from "url"; - - /** - * Valid types for path values in "fs". - */ - type PathLike = string | Buffer | URL; - - type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; - - interface StatsBase { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - - dev: T; - ino: T; - mode: T; - nlink: T; - uid: T; - gid: T; - rdev: T; - size: T; - blksize: T; - blocks: T; - atimeMs: T; - mtimeMs: T; - ctimeMs: T; - birthtimeMs: T; - atime: Date; - mtime: Date; - ctime: Date; - birthtime: Date; - } - - interface Stats extends StatsBase { - } - - class Stats { - } - - class Dirent { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - name: string; - } - - /** - * A class representing a directory stream. - */ - class Dir { - readonly path: string; - - /** - * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. - */ - [Symbol.asyncIterator](): AsyncIterableIterator; - - /** - * Asynchronously close the directory's underlying resource handle. - * Subsequent reads will result in errors. - */ - close(): Promise; - close(cb: NoParamCallback): void; - - /** - * Synchronously close the directory's underlying resource handle. - * Subsequent reads will result in errors. - */ - closeSync(): void; - - /** - * Asynchronously read the next directory entry via `readdir(3)` as an `Dirent`. - * After the read is completed, a value is returned that will be resolved with an `Dirent`, or `null` if there are no more directory entries to read. - * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. - */ - read(): Promise; - read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; - - /** - * Synchronously read the next directory entry via `readdir(3)` as a `Dirent`. - * If there are no more directory entries to read, null will be returned. - * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. - */ - readSync(): Dirent; - } - - interface FSWatcher extends events.EventEmitter { - close(): void; - - /** - * events.EventEmitter - * 1. change - * 2. error - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } - - class ReadStream extends stream.Readable { - close(): void; - bytesRead: number; - path: string | Buffer; - pending: boolean; - - /** - * events.EventEmitter - * 1. open - * 2. close - * 3. ready - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "ready", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "ready", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "ready", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "ready", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "ready", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - class WriteStream extends stream.Writable { - close(): void; - bytesWritten: number; - path: string | Buffer; - pending: boolean; - - /** - * events.EventEmitter - * 1. open - * 2. close - * 3. ready - */ - 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: "open", listener: (fd: number) => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "ready", listener: () => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "ready", listener: () => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "ready", listener: () => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "ready", listener: () => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): 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: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "ready", listener: () => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace rename { - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; - } - - /** - * Synchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function renameSync(oldPath: PathLike, newPath: PathLike): void; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function truncate(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace truncate { - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function __promisify__(path: PathLike, len?: number | null): Promise; - } - - /** - * Synchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function truncateSync(path: PathLike, len?: number | null): void; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - */ - function ftruncate(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace ftruncate { - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - function __promisify__(fd: number, len?: number | null): Promise; - } - - /** - * Synchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - function ftruncateSync(fd: number, len?: number | null): void; - - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace chown { - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - - /** - * Synchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function chownSync(path: PathLike, uid: number, gid: number): void; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fchown { - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - function __promisify__(fd: number, uid: number, gid: number): Promise; - } - - /** - * Synchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - function fchownSync(fd: number, uid: number, gid: number): void; - - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace lchown { - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - - /** - * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lchownSync(path: PathLike, uid: number, gid: number): void; - - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function chmod(path: PathLike, mode: string | number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace chmod { - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(path: PathLike, mode: string | number): Promise; - } - - /** - * Synchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function chmodSync(path: PathLike, mode: string | number): void; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function fchmod(fd: number, mode: string | number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fchmod { - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(fd: number, mode: string | number): Promise; - } - - /** - * Synchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function fchmodSync(fd: number, mode: string | number): void; - - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function lchmod(path: PathLike, mode: string | number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace lchmod { - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(path: PathLike, mode: string | number): Promise; - } - - /** - * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function lchmodSync(path: PathLike, mode: string | number): void; - - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace stat { - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function statSync(path: PathLike): Stats; - - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fstat { - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - function fstatSync(fd: number): Stats; - - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace lstat { - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lstatSync(path: PathLike): Stats; - - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace link { - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; - } - - /** - * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function linkSync(existingPath: PathLike, newPath: PathLike): void; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - */ - function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace symlink { - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; - - type Type = "dir" | "file" | "junction"; - } - - /** - * Synchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink( - path: PathLike, - options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, linkString: string) => void - ): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace readlink { - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - } - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath( - path: PathLike, - options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void - ): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace realpath { - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - - function native( - path: PathLike, - options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void - ): void; - function native(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - function native(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; - function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; - } - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; - - namespace realpathSync { - function native(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - function native(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; - function native(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; - } - - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function unlink(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace unlink { - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function unlinkSync(path: PathLike): void; - - interface RmDirOptions { - /** - * If `true`, perform a recursive directory removal. In - * recursive mode, errors are not reported if `path` does not exist, and - * operations are retried on failure. - * @experimental - * @default false - */ - recursive?: boolean; - } - - interface RmDirAsyncOptions extends RmDirOptions { - /** - * The amount of time in milliseconds to wait between retries. - * This option is ignored if the `recursive` option is not `true`. - * @default 100 - */ - retryDelay?: number; - /** - * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or - * `EPERM` error is encountered, Node.js will retry the operation with a linear - * backoff wait of `retryDelay` ms longer on each try. This option represents the - * number of retries. This option is ignored if the `recursive` option is not - * `true`. - * @default 0 - */ - maxRetries?: number; - } - - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function rmdir(path: PathLike, callback: NoParamCallback): void; - function rmdir(path: PathLike, options: RmDirAsyncOptions, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace rmdir { - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, options?: RmDirAsyncOptions): Promise; - } - - /** - * Synchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function rmdirSync(path: PathLike, options?: RmDirOptions): void; - - interface MakeDirectoryOptions { - /** - * Indicates whether parent folders should be created. - * If a folder was created, the path to the first created folder will be returned. - * @default false - */ - recursive?: boolean; - /** - * A file mode. If a string is passed, it is parsed as an octal integer. If not specified - * @default 0o777 - */ - mode?: number | string; - } - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true }, callback: (err: NodeJS.ErrnoException | null, path: string) => void): void; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options: number | string | (MakeDirectoryOptions & { recursive?: false; }) | null | undefined, callback: NoParamCallback): void; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options: number | string | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path: string | undefined) => void): void; - - /** - * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function mkdir(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace mkdir { - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__(path: PathLike, options?: number | string | (MakeDirectoryOptions & { recursive?: false; }) | null): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; - } - - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdirSync(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): string; - - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdirSync(path: PathLike, options?: number | string | (MakeDirectoryOptions & { recursive?: false; }) | null): void; - - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): string | undefined; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - */ - function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace mkdtemp { - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise; - } - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir( - path: PathLike, - options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, - ): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir( - path: PathLike, - options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, - callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, - ): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes: true }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace readdir { - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent - */ - function __promisify__(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Promise; - } - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - function readdirSync(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Dirent[]; - - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - function close(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace close { - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - function closeSync(fd: number): void; - - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - - /** - * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace open { - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise; - } - - /** - * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace utimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; - } - - /** - * Synchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace futimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; - } - - /** - * Synchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - function fsync(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fsync { - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - function fsyncSync(fd: number): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - position: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - */ - function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - */ - function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - */ - function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function write( - fd: number, - string: any, - position: number | undefined | null, - encoding: string | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, - ): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - */ - function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace write { - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function __promisify__( - fd: number, - buffer?: TBuffer, - offset?: number, - length?: number, - position?: number | null, - ): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; - } - - /** - * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; - - /** - * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; - - /** - * Asynchronously reads data from the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - function read( - fd: number, - buffer: TBuffer, - offset: number, - length: number, - position: number | null, - callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, - ): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace read { - /** - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - function __promisify__( - fd: number, - buffer: TBuffer, - offset: number, - length: number, - position: number | null - ): Promise<{ bytesRead: number, buffer: TBuffer }>; - } - - interface ReadSyncOptions { - /** - * @default 0 - */ - offset?: number; - /** - * @default `length of buffer` - */ - length?: number; - /** - * @default null - */ - position?: number | null; - } - - /** - * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: number | null): number; - - /** - * Similar to the above `fs.readSync` function, this version takes an optional `options` object. - * If no `options` object is specified, it will default with the above values. - */ - function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile( - path: PathLike | number, - options: { encoding?: string | null; flag?: string; } | string | undefined | null, - callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, - ): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - */ - function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace readFile { - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise; - } - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. - */ - function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; - - type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: NoParamCallback): void; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - function writeFile(path: PathLike | number, data: any, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace writeFile { - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise; - } - - /** - * Synchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: NoParamCallback): void; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - function appendFile(file: PathLike | number, data: any, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace appendFile { - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise; - } - - /** - * Synchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; - - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - */ - function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; - - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; - - /** - * Stop watching for changes on `filename`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - function watch( - filename: PathLike, - options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, - listener?: (event: string, filename: string) => void, - ): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - function watch( - filename: PathLike, - options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, - listener?: (event: string, filename: string | Buffer) => void, - ): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; - - /** - * Asynchronously tests whether or not the given path exists by checking with the file system. - * @deprecated - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function exists(path: PathLike, callback: (exists: boolean) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace exists { - /** - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronously tests whether or not the given path exists by checking with the file system. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function existsSync(path: PathLike): boolean; - - namespace constants { - // File Access Constants - - /** Constant for fs.access(). File is visible to the calling process. */ - const F_OK: number; - - /** Constant for fs.access(). File can be read by the calling process. */ - const R_OK: number; - - /** Constant for fs.access(). File can be written by the calling process. */ - const W_OK: number; - - /** Constant for fs.access(). File can be executed by the calling process. */ - const X_OK: number; - - // File Copy Constants - - /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ - const COPYFILE_EXCL: number; - - /** - * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. - * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. - */ - const COPYFILE_FICLONE: number; - - /** - * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. - * If the underlying platform does not support copy-on-write, then the operation will fail with an error. - */ - const COPYFILE_FICLONE_FORCE: number; - - // File Open Constants - - /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ - const O_RDONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ - const O_WRONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ - const O_RDWR: number; - - /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ - 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. */ - 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). - */ - 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. */ - const O_TRUNC: number; - - /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ - const O_APPEND: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ - 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. - */ - const O_NOATIME: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ - const O_NOFOLLOW: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ - const O_SYNC: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ - const O_DSYNC: number; - - /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ - const O_SYMLINK: number; - - /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ - const O_DIRECT: number; - - /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ - 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. */ - const S_IFMT: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ - const S_IFREG: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ - 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. */ - 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. */ - const S_IFBLK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ - const S_IFIFO: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ - const S_IFLNK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ - 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. */ - const S_IRWXU: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ - const S_IRUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ - const S_IWUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ - 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. */ - const S_IRWXG: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ - const S_IRGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ - const S_IWGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ - 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. */ - const S_IRWXO: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ - const S_IROTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ - const S_IWOTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ - const S_IXOTH: number; - - /** - * When set, a memory file mapping is used to access the file. This flag - * is available on Windows operating systems only. On other operating systems, - * this flag is ignored. - */ - const UV_FS_O_FILEMAP: number; - } - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function access(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace access { - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike, mode?: number): Promise; - } - - /** - * Synchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function accessSync(path: PathLike, mode?: number): void; - - /** - * Returns a new `ReadStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function createReadStream(path: PathLike, options?: string | { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - /** - * @default false - */ - emitClose?: boolean; - start?: number; - end?: number; - highWaterMark?: number; - }): ReadStream; - - /** - * Returns a new `WriteStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function createWriteStream(path: PathLike, options?: string | { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - emitClose?: boolean; - start?: number; - highWaterMark?: number; - }): WriteStream; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - function fdatasync(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace fdatasync { - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - function fdatasyncSync(fd: number): void; - - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - */ - function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - function copyFile(src: PathLike, dest: PathLike, flags: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace copyFile { - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. - * The only supported flag is fs.constants.COPYFILE_EXCL, - * which causes the copy operation to fail if dest already exists. - */ - function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; - } - - /** - * Synchronously copies src to dest. By default, dest is overwritten if it already exists. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. - * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; - - /** - * Write an array of ArrayBufferViews to the file specified by fd using writev(). - * position is the offset from the beginning of the file where this data should be written. - * It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use fs.createWriteStream(). - * 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. - */ - function writev( - fd: number, - buffers: NodeJS.ArrayBufferView[], - cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - function writev( - fd: number, - buffers: NodeJS.ArrayBufferView[], - position: number, - cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - - interface WriteVResult { - bytesWritten: number; - buffers: NodeJS.ArrayBufferView[]; - } - - namespace writev { - function __promisify__(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): Promise; - } - - /** - * See `writev`. - */ - function writevSync(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): number; - - function readv( - fd: number, - buffers: NodeJS.ArrayBufferView[], - cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - function readv( - fd: number, - buffers: NodeJS.ArrayBufferView[], - position: number, - cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - - interface ReadVResult { - bytesRead: number; - buffers: NodeJS.ArrayBufferView[]; - } - - namespace readv { - function __promisify__(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): Promise; - } - - /** - * See `readv`. - */ - function readvSync(fd: number, buffers: NodeJS.ArrayBufferView[], position?: number): number; - - interface OpenDirOptions { - encoding?: BufferEncoding; - /** - * Number of directory entries that are buffered - * internally when reading from the directory. Higher values lead to better - * performance but higher memory usage. - * @default 32 - */ - bufferSize?: number; - } - - function opendirSync(path: string, options?: OpenDirOptions): Dir; - - function opendir(path: string, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; - function opendir(path: string, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; - - namespace opendir { - function __promisify__(path: string, options?: OpenDirOptions): Promise; - } - - namespace promises { - interface FileHandle { - /** - * Gets the file descriptor for this file handle. - */ - readonly fd: number; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for appending. - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - appendFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - */ - chown(uid: number, gid: number): Promise; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - chmod(mode: string | number): Promise; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - */ - datasync(): Promise; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - */ - sync(): Promise; - - /** - * Asynchronously reads data from the file. - * The `FileHandle` must have been opened for reading. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - read(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; - - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile(options?: { encoding?: null, flag?: string | number } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile(options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; - - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile(options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; - - /** - * Asynchronous fstat(2) - Get file status. - */ - stat(): Promise; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param len If not specified, defaults to `0`. - */ - truncate(len?: number): Promise; - - /** - * Asynchronously change file timestamps of the file. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - utimes(atime: string | number | Date, mtime: string | number | Date): Promise; - - /** - * Asynchronously writes `buffer` to the file. - * The `FileHandle` must have been opened for writing. - * @param buffer The buffer that the data will be written to. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - write(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file. - * The `FileHandle` must have been opened for writing. - * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` - * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - write(data: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for writing. - * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - writeFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; - - /** - * See `fs.writev` promisified version. - */ - writev(buffers: NodeJS.ArrayBufferView[], position?: number): Promise; - - /** - * See `fs.readv` promisified version. - */ - readv(buffers: NodeJS.ArrayBufferView[], position?: number): Promise; - - /** - * Asynchronous close(2) - close a `FileHandle`. - */ - close(): Promise; - } - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function access(path: PathLike, mode?: number): Promise; - - /** - * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. The only - * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if - * `dest` already exists. - */ - function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise; - - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not - * supplied, defaults to `0o666`. - */ - function open(path: PathLike, flags: string | number, mode?: string | number): Promise; - - /** - * Asynchronously reads data from the file referenced by the supplied `FileHandle`. - * @param handle A `FileHandle`. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If - * `null`, data will be read from the current position. - */ - function read( - handle: FileHandle, - buffer: TBuffer, - offset?: number | null, - length?: number | null, - position?: number | null, - ): Promise<{ bytesRead: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. - * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` - * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. - * @param handle A `FileHandle`. - * @param buffer The buffer that the data will be written to. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function write( - handle: FileHandle, - buffer: TBuffer, - offset?: number | null, - length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. - * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` - * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. - * @param handle A `FileHandle`. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function write(handle: FileHandle, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; - - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function rename(oldPath: PathLike, newPath: PathLike): Promise; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function truncate(path: PathLike, len?: number): Promise; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param handle A `FileHandle`. - * @param len If not specified, defaults to `0`. - */ - function ftruncate(handle: FileHandle, len?: number): Promise; - - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function rmdir(path: PathLike, options?: RmDirAsyncOptions): Promise; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param handle A `FileHandle`. - */ - function fdatasync(handle: FileHandle): Promise; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param handle A `FileHandle`. - */ - function fsync(handle: FileHandle): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options?: number | string | (MakeDirectoryOptions & { recursive?: false; }) | null): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options?: { encoding?: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; - - /** - * Asynchronous fstat(2) - Get file status. - * @param handle A `FileHandle`. - */ - function fstat(handle: FileHandle): Promise; - - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lstat(path: PathLike): Promise; - - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function stat(path: PathLike): Promise; - - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function link(existingPath: PathLike, newPath: PathLike): Promise; - - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function unlink(path: PathLike): Promise; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param handle A `FileHandle`. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function fchmod(handle: FileHandle, mode: string | number): Promise; - - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function chmod(path: PathLike, mode: string | number): Promise; - - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function lchmod(path: PathLike, mode: string | number): Promise; - - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lchown(path: PathLike, uid: number, gid: number): Promise; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param handle A `FileHandle`. - */ - function fchown(handle: FileHandle, uid: number, gid: number): Promise; - - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function chown(path: PathLike, uid: number, gid: number): Promise; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. - * @param handle A `FileHandle`. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options?: { encoding?: string | null } | string | null): Promise; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function writeFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function appendFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: string | number } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | FileHandle, options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; - - function opendir(path: string, options?: OpenDirOptions): Promise; - } -} diff --git a/types/node/v13/ts3.1/globals.d.ts b/types/node/v13/ts3.1/globals.d.ts deleted file mode 100644 index 201b74c1c6..0000000000 --- a/types/node/v13/ts3.1/globals.d.ts +++ /dev/null @@ -1,1125 +0,0 @@ -// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build -interface Console { - Console: NodeJS.ConsoleConstructor; - /** - * A simple assertion test that verifies whether `value` is truthy. - * If it is not, an `AssertionError` is thrown. - * If provided, the error `message` is formatted using `util.format()` and used as the error message. - */ - assert(value: any, message?: string, ...optionalParams: any[]): void; - /** - * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. - * When `stdout` is not a TTY, this method does nothing. - */ - clear(): void; - /** - * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. - */ - count(label?: string): void; - /** - * Resets the internal counter specific to `label`. - */ - countReset(label?: string): void; - /** - * The `console.debug()` function is an alias for {@link console.log()}. - */ - debug(message?: any, ...optionalParams: any[]): void; - /** - * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. - * This function bypasses any custom `inspect()` function defined on `obj`. - */ - dir(obj: any, options?: NodeJS.InspectOptions): void; - /** - * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting - */ - dirxml(...data: any[]): void; - /** - * Prints to `stderr` with newline. - */ - error(message?: any, ...optionalParams: any[]): void; - /** - * Increases indentation of subsequent lines by two spaces. - * If one or more `label`s are provided, those are printed first without the additional indentation. - */ - group(...label: any[]): void; - /** - * The `console.groupCollapsed()` function is an alias for {@link console.group()}. - */ - groupCollapsed(...label: any[]): void; - /** - * Decreases indentation of subsequent lines by two spaces. - */ - groupEnd(): void; - /** - * The {@link console.info()} function is an alias for {@link console.log()}. - */ - info(message?: any, ...optionalParams: any[]): void; - /** - * Prints to `stdout` with newline. - */ - log(message?: any, ...optionalParams: any[]): void; - /** - * This method does not display anything unless used in the inspector. - * Prints to `stdout` the array `array` formatted as a table. - */ - table(tabularData: any, properties?: string[]): void; - /** - * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. - */ - time(label?: string): void; - /** - * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. - */ - timeEnd(label?: string): void; - /** - * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. - */ - timeLog(label?: string, ...data: any[]): void; - /** - * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. - */ - trace(message?: any, ...optionalParams: any[]): void; - /** - * The {@link console.warn()} function is an alias for {@link console.error()}. - */ - warn(message?: any, ...optionalParams: any[]): void; - - // --- Inspector mode only --- - /** - * This method does not display anything unless used in the inspector. - * Starts a JavaScript CPU profile with an optional label. - */ - profile(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. - */ - profileEnd(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Adds an event with the label `label` to the Timeline panel of the inspector. - */ - timeStamp(label?: string): void; -} - -// Declare "static" methods in Error -interface ErrorConstructor { - /** Create .stack property on a target object */ - captureStackTrace(targetObject: object, constructorOpt?: Function): void; - - /** - * Optional override for formatting stack traces - * - * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces - */ - prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; - - stackTraceLimit: number; -} - -// Node.js ESNEXT support -interface String { - /** Removes whitespace from the left end of a string. */ - trimLeft(): string; - /** Removes whitespace from the right end of a string. */ - trimRight(): string; - - /** Returns a copy with leading whitespace removed. */ - trimStart(): string; - /** Returns a copy with trailing whitespace removed. */ - trimEnd(): string; -} - -interface ImportMeta { - url: string; -} - -/*-----------------------------------------------* - * * - * GLOBAL * - * * - ------------------------------------------------*/ - -// For backwards compability -interface NodeRequire extends NodeJS.Require {} -interface RequireResolve extends NodeJS.RequireResolve {} -interface NodeModule extends NodeJS.Module {} - -declare var process: NodeJS.Process; -declare var console: Console; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare namespace setTimeout { - function __promisify__(ms: number): Promise; - function __promisify__(ms: number, value: T): Promise; -} -declare function clearTimeout(timeoutId: NodeJS.Timeout): void; -declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare function clearInterval(intervalId: NodeJS.Timeout): void; -declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; -declare namespace setImmediate { - function __promisify__(): Promise; - function __promisify__(value: T): Promise; -} -declare function clearImmediate(immediateId: NodeJS.Immediate): void; - -declare function queueMicrotask(callback: () => void): void; - -declare var require: NodeRequire; -declare var module: NodeModule; - -// Same as module.exports -declare var exports: any; - -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"; - -/** - * 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 class Buffer extends Uint8Array { - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. - */ - constructor(str: string, encoding?: BufferEncoding); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). - */ - constructor(size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - constructor(array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}/{SharedArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. - */ - constructor(arrayBuffer: ArrayBuffer | SharedArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - constructor(array: any[]); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. - */ - constructor(buffer: 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 any TypedArray or a new ArrayBuffer() - */ - static from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param data data to create a new Buffer - */ - static from(data: number[]): Buffer; - static from(data: Uint8Array): Buffer; - /** - * Creates a new buffer containing the coerced value of an object - * A `TypeError` will be thrown if {obj} has not mentioned methods or is not of other type appropriate for `Buffer.from()` variants. - * @param obj An object supporting `Symbol.toPrimitive` or `valueOf()`. - */ - static from(obj: { valueOf(): string | object } | { [Symbol.toPrimitive](hint: 'string'): string }, byteOffset?: number, length?: number): 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'. - */ - static from(str: string, encoding?: BufferEncoding): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param values to create a new Buffer - */ - static of(...items: number[]): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - static 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. - */ - static isEncoding(encoding: string): encoding is BufferEncoding; - /** - * 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 | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, - encoding?: BufferEncoding - ): 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: Uint8Array[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - static compare(buf1: Uint8Array, buf2: Uint8Array): 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 - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): 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 - */ - static 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 - */ - static allocUnsafeSlow(size: number): Buffer; - /** - * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. - */ - static poolSize: number; - - write(string: string, encoding?: BufferEncoding): number; - write(string: string, offset: number, encoding?: BufferEncoding): number; - write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer'; data: number[] }; - equals(otherBuffer: Uint8Array): boolean; - compare( - otherBuffer: Uint8Array, - targetStart?: number, - targetEnd?: number, - sourceStart?: number, - sourceEnd?: number - ): number; - copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - /** - * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. - * - * This method is incompatible with `Uint8Array#slice()`, which returns a copy of the original memory. - * - * @param begin Where the new `Buffer` will start. Default: `0`. - * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. - */ - slice(begin?: number, end?: number): Buffer; - /** - * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. - * - * This method is compatible with `Uint8Array#subarray()`. - * - * @param begin Where the new `Buffer` will start. Default: `0`. - * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. - */ - subarray(begin?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number): number; - writeUIntBE(value: number, offset: number, byteLength: number): number; - writeIntLE(value: number, offset: number, byteLength: number): number; - writeIntBE(value: number, offset: number, byteLength: number): number; - readUIntLE(offset: number, byteLength: number): number; - readUIntBE(offset: number, byteLength: number): number; - readIntLE(offset: number, byteLength: number): number; - readIntBE(offset: number, byteLength: number): number; - readUInt8(offset?: number): number; - readUInt16LE(offset?: number): number; - readUInt16BE(offset?: number): number; - readUInt32LE(offset?: number): number; - readUInt32BE(offset?: number): number; - readInt8(offset?: number): number; - readInt16LE(offset?: number): number; - readInt16BE(offset?: number): number; - readInt32LE(offset?: number): number; - readInt32BE(offset?: number): number; - readFloatLE(offset?: number): number; - readFloatBE(offset?: number): number; - readDoubleLE(offset?: number): number; - readDoubleBE(offset?: number): number; - reverse(): this; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset?: number): number; - writeUInt16LE(value: number, offset?: number): number; - writeUInt16BE(value: number, offset?: number): number; - writeUInt32LE(value: number, offset?: number): number; - writeUInt32BE(value: number, offset?: number): number; - writeInt8(value: number, offset?: number): number; - writeInt16LE(value: number, offset?: number): number; - writeInt16BE(value: number, offset?: number): number; - writeInt32LE(value: number, offset?: number): number; - writeInt32BE(value: number, offset?: number): number; - writeFloatLE(value: number, offset?: number): number; - writeFloatBE(value: number, offset?: number): number; - writeDoubleLE(value: number, offset?: number): number; - writeDoubleBE(value: number, offset?: number): number; - - fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; - - indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; - lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; - keys(): IterableIterator; - values(): IterableIterator; -} - -/*----------------------------------------------* -* * -* GLOBAL INTERFACES * -* * -*-----------------------------------------------*/ -declare namespace NodeJS { - interface InspectOptions { - /** - * If set to `true`, getters are going to be - * inspected as well. If set to `'get'` only getters without setter are going - * to be inspected. If set to `'set'` only getters having a corresponding - * setter are going to be inspected. This might cause side effects depending on - * the getter function. - * @default `false` - */ - getters?: 'get' | 'set' | boolean; - showHidden?: boolean; - /** - * @default 2 - */ - depth?: number | null; - colors?: boolean; - customInspect?: boolean; - showProxy?: boolean; - maxArrayLength?: number | null; - /** - * Specifies the maximum number of characters to - * include when formatting. Set to `null` or `Infinity` to show all elements. - * Set to `0` or negative to show no characters. - * @default Infinity - */ - maxStringLength?: number | null; - breakLength?: number; - /** - * Setting this to `false` causes each object key - * to be displayed on a new line. It will also add new lines to text that is - * longer than `breakLength`. If set to a number, the most `n` inner elements - * are united on a single line as long as all properties fit into - * `breakLength`. Short array elements are also grouped together. Note that no - * text will be reduced below 16 characters, no matter the `breakLength` size. - * For more information, see the example below. - * @default `true` - */ - compact?: boolean | number; - sorted?: boolean | ((a: string, b: string) => number); - } - - interface ConsoleConstructorOptions { - stdout: WritableStream; - stderr?: WritableStream; - ignoreErrors?: boolean; - colorMode?: boolean | 'auto'; - inspectOptions?: InspectOptions; - } - - interface ConsoleConstructor { - prototype: Console; - new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; - new(options: ConsoleConstructorOptions): Console; - } - - interface CallSite { - /** - * Value of "this" - */ - getThis(): any; - - /** - * Type of "this" as a string. - * This is the name of the function stored in the constructor field of - * "this", if available. Otherwise the object's [[Class]] internal - * property. - */ - getTypeName(): string | null; - - /** - * Current function - */ - getFunction(): Function | undefined; - - /** - * Name of the current function, typically its name property. - * If a name property is not available an attempt will be made to try - * to infer a name from the function's context. - */ - getFunctionName(): string | null; - - /** - * Name of the property [of "this" or one of its prototypes] that holds - * the current function - */ - getMethodName(): string | null; - - /** - * Name of the script [if this function was defined in a script] - */ - getFileName(): string | null; - - /** - * Current line number [if this function was defined in a script] - */ - getLineNumber(): number | null; - - /** - * Current column number [if this function was defined in a script] - */ - getColumnNumber(): number | null; - - /** - * A call site object representing the location where eval was called - * [if this function was created using a call to eval] - */ - getEvalOrigin(): string | undefined; - - /** - * Is this a toplevel invocation, that is, is "this" the global object? - */ - isToplevel(): boolean; - - /** - * Does this call take place in code defined by a call to eval? - */ - isEval(): boolean; - - /** - * Is this call in native V8 code? - */ - isNative(): boolean; - - /** - * Is this a constructor call? - */ - isConstructor(): boolean; - } - - interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } - - interface EventEmitter { - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - rawListeners(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: (...args: any[]) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - eventNames(): Array; - } - - interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: WritableStream): this; - unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; - wrap(oldStream: ReadableStream): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - interface WritableStream extends EventEmitter { - writable: boolean; - write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; - write(str: string, encoding?: string, cb?: (err?: Error | null) => void): boolean; - end(cb?: () => void): void; - end(data: string | Uint8Array, cb?: () => void): void; - end(str: string, encoding?: string, cb?: () => void): void; - } - - interface ReadWriteStream extends ReadableStream, WritableStream { } - - interface Domain extends EventEmitter { - run(fn: (...args: any[]) => T, ...args: any[]): T; - add(emitter: EventEmitter | Timer): void; - remove(emitter: EventEmitter | Timer): void; - bind(cb: T): T; - intercept(cb: T): T; - - addListener(event: string, listener: (...args: any[]) => void): this; - on(event: string, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - removeListener(event: string, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string): this; - } - - interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - external: number; - arrayBuffers: number; - } - - interface CpuUsage { - user: number; - system: number; - } - - interface ProcessRelease { - name: string; - sourceUrl?: string; - headersUrl?: string; - libUrl?: string; - lts?: string; - } - - interface ProcessVersions { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } - - type Platform = 'aix' - | 'android' - | 'darwin' - | 'freebsd' - | 'linux' - | 'openbsd' - | 'sunos' - | 'win32' - | 'cygwin' - | 'netbsd'; - - type Signals = - "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | - "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | - "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | - "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; - - type MultipleResolveType = 'resolve' | 'reject'; - - type BeforeExitListener = (code: number) => void; - type DisconnectListener = () => void; - type ExitListener = (code: number) => void; - type RejectionHandledListener = (promise: Promise) => void; - type UncaughtExceptionListener = (error: Error) => void; - type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; - type WarningListener = (warning: Error) => void; - type MessageListener = (message: any, sendHandle: any) => void; - type SignalsListener = (signal: Signals) => void; - type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; - - interface Socket extends ReadWriteStream { - isTTY?: true; - } - - // Alias for compatibility - interface ProcessEnv extends Dict {} - - interface HRTime { - (time?: [number, number]): [number, number]; - } - - interface ProcessReport { - /** - * Directory where the report is written. - * working directory of the Node.js process. - * @default '' indicating that reports are written to the current - */ - directory: string; - - /** - * Filename where the report is written. - * The default value is the empty string. - * @default '' the output filename will be comprised of a timestamp, - * PID, and sequence number. - */ - filename: string; - - /** - * Returns a JSON-formatted diagnostic report for the running process. - * The report's JavaScript stack trace is taken from err, if present. - */ - getReport(err?: Error): string; - - /** - * If true, a diagnostic report is generated on fatal errors, - * such as out of memory errors or failed C++ assertions. - * @default false - */ - reportOnFatalError: boolean; - - /** - * If true, a diagnostic report is generated when the process - * receives the signal specified by process.report.signal. - * @defaul false - */ - reportOnSignal: boolean; - - /** - * If true, a diagnostic report is generated on uncaught exception. - * @default false - */ - reportOnUncaughtException: boolean; - - /** - * The signal used to trigger the creation of a diagnostic report. - * @default 'SIGUSR2' - */ - signal: Signals; - - /** - * Writes a diagnostic report to a file. If filename is not provided, the default filename - * includes the date, time, PID, and a sequence number. - * The report's JavaScript stack trace is taken from err, if present. - * - * @param fileName Name of the file where the report is written. - * This should be a relative path, that will be appended to the directory specified in - * `process.report.directory`, or the current working directory of the Node.js process, - * if unspecified. - * @param error A custom error used for reporting the JavaScript stack. - * @return Filename of the generated report. - */ - writeReport(fileName?: string): string; - writeReport(error?: Error): string; - writeReport(fileName?: string, err?: Error): string; - } - - interface ResourceUsage { - fsRead: number; - fsWrite: number; - involuntaryContextSwitches: number; - ipcReceived: number; - ipcSent: number; - majorPageFault: number; - maxRSS: number; - minorPageFault: number; - sharedMemorySize: number; - signalsCount: number; - swappedOut: number; - systemCPUTime: number; - unsharedDataSize: number; - unsharedStackSize: number; - userCPUTime: number; - voluntaryContextSwitches: number; - } - - interface Process extends EventEmitter { - /** - * Can also be a tty.WriteStream, not typed due to limitation.s - */ - stdout: WriteStream; - /** - * Can also be a tty.WriteStream, not typed due to limitation.s - */ - stderr: WriteStream; - stdin: ReadStream; - openStdin(): Socket; - argv: string[]; - argv0: string; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - debugPort: number; - emitWarning(warning: string | Error, name?: string, ctor?: Function): void; - env: ProcessEnv; - exit(code?: number): never; - exitCode?: number; - getgid(): number; - setgid(id: number | string): void; - getuid(): number; - setuid(id: number | string): void; - geteuid(): number; - seteuid(id: number | string): void; - getegid(): number; - setegid(id: number | string): void; - getgroups(): number[]; - setgroups(groups: Array): void; - setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; - hasUncaughtExceptionCaptureCallback(): boolean; - 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; - ppid: number; - title: string; - arch: string; - platform: Platform; - mainModule?: Module; - memoryUsage(): MemoryUsage; - cpuUsage(previousValue?: CpuUsage): CpuUsage; - nextTick(callback: Function, ...args: any[]): void; - release: ProcessRelease; - features: { - inspector: boolean; - debug: boolean; - uv: boolean; - ipv6: boolean; - tls_alpn: boolean; - tls_sni: boolean; - tls_ocsp: boolean; - tls: boolean; - }; - /** - * Can only be set if not in worker thread. - */ - umask(mask?: number): number; - uptime(): number; - hrtime: HRTime; - domain: Domain; - - // Worker - send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; - disconnect(): void; - connected: boolean; - - /** - * The `process.allowedNodeEnvironmentFlags` property is a special, - * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] - * environment variable. - */ - allowedNodeEnvironmentFlags: ReadonlySet; - - /** - * Only available with `--experimental-report` - */ - report?: ProcessReport; - - resourceUsage(): ResourceUsage; - - /* EventEmitter */ - addListener(event: "beforeExit", listener: BeforeExitListener): this; - addListener(event: "disconnect", listener: DisconnectListener): this; - addListener(event: "exit", listener: ExitListener): this; - addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - addListener(event: "warning", listener: WarningListener): this; - addListener(event: "message", listener: MessageListener): this; - addListener(event: Signals, listener: SignalsListener): this; - addListener(event: "newListener", listener: NewListenerListener): this; - addListener(event: "removeListener", listener: RemoveListenerListener): this; - addListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - emit(event: "beforeExit", code: number): boolean; - emit(event: "disconnect"): boolean; - emit(event: "exit", code: number): boolean; - emit(event: "rejectionHandled", promise: Promise): boolean; - emit(event: "uncaughtException", error: Error): boolean; - emit(event: "uncaughtExceptionMonitor", error: Error): boolean; - emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; - emit(event: "warning", warning: Error): boolean; - emit(event: "message", message: any, sendHandle: any): this; - emit(event: Signals, signal: Signals): boolean; - emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; - emit(event: "multipleResolves", listener: MultipleResolveListener): this; - - on(event: "beforeExit", listener: BeforeExitListener): this; - on(event: "disconnect", listener: DisconnectListener): this; - on(event: "exit", listener: ExitListener): this; - on(event: "rejectionHandled", listener: RejectionHandledListener): this; - on(event: "uncaughtException", listener: UncaughtExceptionListener): this; - on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - on(event: "warning", listener: WarningListener): this; - on(event: "message", listener: MessageListener): this; - on(event: Signals, listener: SignalsListener): this; - on(event: "newListener", listener: NewListenerListener): this; - on(event: "removeListener", listener: RemoveListenerListener): this; - on(event: "multipleResolves", listener: MultipleResolveListener): this; - - once(event: "beforeExit", listener: BeforeExitListener): this; - once(event: "disconnect", listener: DisconnectListener): this; - once(event: "exit", listener: ExitListener): this; - once(event: "rejectionHandled", listener: RejectionHandledListener): this; - once(event: "uncaughtException", listener: UncaughtExceptionListener): this; - once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - once(event: "warning", listener: WarningListener): this; - once(event: "message", listener: MessageListener): this; - once(event: Signals, listener: SignalsListener): this; - once(event: "newListener", listener: NewListenerListener): this; - once(event: "removeListener", listener: RemoveListenerListener): this; - once(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependListener(event: "beforeExit", listener: BeforeExitListener): this; - prependListener(event: "disconnect", listener: DisconnectListener): this; - prependListener(event: "exit", listener: ExitListener): this; - prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependListener(event: "warning", listener: WarningListener): this; - prependListener(event: "message", listener: MessageListener): this; - prependListener(event: Signals, listener: SignalsListener): this; - prependListener(event: "newListener", listener: NewListenerListener): this; - prependListener(event: "removeListener", listener: RemoveListenerListener): this; - prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; - prependOnceListener(event: "disconnect", listener: DisconnectListener): this; - prependOnceListener(event: "exit", listener: ExitListener): this; - prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependOnceListener(event: "warning", listener: WarningListener): this; - prependOnceListener(event: "message", listener: MessageListener): this; - prependOnceListener(event: Signals, listener: SignalsListener): this; - prependOnceListener(event: "newListener", listener: NewListenerListener): this; - prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; - prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - listeners(event: "beforeExit"): BeforeExitListener[]; - listeners(event: "disconnect"): DisconnectListener[]; - listeners(event: "exit"): ExitListener[]; - listeners(event: "rejectionHandled"): RejectionHandledListener[]; - listeners(event: "uncaughtException"): UncaughtExceptionListener[]; - listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; - listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; - listeners(event: "warning"): WarningListener[]; - listeners(event: "message"): MessageListener[]; - listeners(event: Signals): SignalsListener[]; - listeners(event: "newListener"): NewListenerListener[]; - listeners(event: "removeListener"): RemoveListenerListener[]; - listeners(event: "multipleResolves"): MultipleResolveListener[]; - } - - 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: typeof Promise; - 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: typeof Uint8ClampedArray; - WeakMap: WeakMapConstructor; - WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: Immediate) => void; - clearInterval: (intervalId: Timeout) => void; - clearTimeout: (timeoutId: Timeout) => 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; - /** - * @deprecated Use `global`. - */ - root: Global; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - queueMicrotask: typeof queueMicrotask; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } - - interface RefCounted { - ref(): this; - unref(): this; - } - - // compatibility with older typings - interface Timer extends RefCounted { - hasRef(): boolean; - refresh(): this; - } - - interface Immediate extends RefCounted { - hasRef(): boolean; - _onImmediate: Function; // to distinguish it from the Timeout class - } - - interface Timeout extends Timer { - hasRef(): boolean; - refresh(): this; - } - - type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; - type ArrayBufferView = TypedArray | DataView; - - interface Require { - /* tslint:disable-next-line:callable-types */ - (id: string): any; - resolve: RequireResolve; - cache: Dict; - /** - * @deprecated - */ - extensions: RequireExtensions; - main: Module | undefined; - } - - interface RequireResolve { - (id: string, options?: { paths?: string[]; }): string; - paths(request: string): string[] | null; - } - - interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { - '.js': (m: Module, filename: string) => any; - '.json': (m: Module, filename: string) => any; - '.node': (m: Module, filename: string) => any; - } - interface Module { - exports: any; - require: Require; - id: string; - filename: string; - loaded: boolean; - /** - * @since 11.14.0 - * - * The directory name of the module. This is usually the same as the path.dirname() of the module.id. - */ - path: string; - parent: Module | null; - children: Module[]; - paths: string[]; - } - - interface Dict { - [key: string]: T | undefined; - } - - interface ReadOnlyDict { - readonly [key: string]: T | undefined; - } -} diff --git a/types/node/v13/ts3.1/index.d.ts b/types/node/v13/ts3.1/index.d.ts deleted file mode 100644 index f5d7c1e36d..0000000000 --- a/types/node/v13/ts3.1/index.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.5. - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.8 -// - ~/ts3.5/index.d.ts - Definitions specific to TypeScript 3.5 - -// NOTE: Augmentations for TypeScript 3.5 and later should use individual files for overrides -// within the respective ~/ts3.5 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.5, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -/// - -// We can't include globals.global.d.ts in globals.d.ts, as it'll cause duplication errors in TypeScript 3.5+ -/// - -// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in TypeScript 3.7+ -/// - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files -// just to ensure the names are known and node typings can be used without importing these libs. -// if someone really needs these types the libs need to be added via --lib or in tsconfig.json -interface AsyncIterable { } -interface IterableIterator { } -interface AsyncIterableIterator {} -interface SymbolConstructor { - readonly asyncIterator: symbol; -} -declare var Symbol: SymbolConstructor; -// even this is just a forward declaration some properties are added otherwise -// it would be allowed to pass anything to e.g. Buffer.from() -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; -} - -declare module "util" { - namespace types { - function isBigInt64Array(value: any): boolean; - function isBigUint64Array(value: any): boolean; - } -} diff --git a/types/node/v13/ts3.1/node-tests.ts b/types/node/v13/ts3.1/node-tests.ts deleted file mode 100644 index 518b0af255..0000000000 --- a/types/node/v13/ts3.1/node-tests.ts +++ /dev/null @@ -1,349 +0,0 @@ -import * as fs from "fs"; -import * as url from "url"; -import * as util from "util"; -import * as http from "http"; -import * as https from "https"; -import * as console2 from "console"; -import * as timers from "timers"; -import * as inspector from "inspector"; -import * as trace_events from "trace_events"; - -////////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html /// -////////////////////////////////////////////////////// - -{ - let agent: https.Agent = new https.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256, - maxCachedSessions: 100, - timeout: 15000 - }); - - agent = https.globalAgent; - - https.request({ - agent: false - }); - https.request({ - agent - }); - https.request({ - agent: undefined - }); - - https.get('http://www.example.com/xyz'); - https.request('http://www.example.com/xyz'); - - https.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - https.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - - https.get(new url.URL('http://www.example.com/xyz')); - https.request(new url.URL('http://www.example.com/xyz')); - - https.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - https.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - - const opts: https.RequestOptions = { - path: '/some/path' - }; - https.get(new url.URL('http://www.example.com'), opts); - https.request(new url.URL('http://www.example.com'), opts); - https.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - https.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - - https.globalAgent.options.ca = []; - - { - function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} - - class MyIncomingMessage extends http.IncomingMessage { - foo: number; - } - - class MyServerResponse extends http.ServerResponse { - foo: string; - } - - let server: https.Server; - - server = new https.Server(); - server = new https.Server(reqListener); - server = new https.Server({ IncomingMessage: MyIncomingMessage}); - - server = new https.Server({ - IncomingMessage: MyIncomingMessage, - ServerResponse: MyServerResponse - }, reqListener); - - server = https.createServer(); - server = https.createServer(reqListener); - server = https.createServer({ IncomingMessage: MyIncomingMessage }); - server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); - - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - const maxHeadersCount: number | null = server.maxHeadersCount; - const headersTimeout: number = server.headersTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } -} - -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - -{ - { - const immediate = timers - .setImmediate(() => { - console.log('immediate'); - }) - .unref() - .ref(); - const b: boolean = immediate.hasRef(); - timers.clearImmediate(immediate); - } - { - const timeout = timers - .setInterval(() => { - console.log('interval'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearInterval(timeout); - } - { - const timeout = timers - .setTimeout(() => { - console.log('timeout'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearTimeout(timeout); - } - async function testPromisify(doSomething: { - (foo: any, onSuccessCallback: (result: string) => void, onErrorCallback: (reason: any) => void): void; - [util.promisify.custom](foo: any): Promise; - }) { - const setTimeout = util.promisify(timers.setTimeout); - let v: void = await setTimeout(100); // tslint:disable-line no-void-expression void-return - let s: string = await setTimeout(100, ""); - - const setImmediate = util.promisify(timers.setImmediate); - v = await setImmediate(); // tslint:disable-line no-void-expression - s = await setImmediate(""); - - // $ExpectType (foo: any) => Promise - const doSomethingPromise = util.promisify(doSomething); - - // $ExpectType string - s = await doSomethingPromise('foo'); - } -} - -///////////////////////////////////////////////////////// -/// Errors Tests : https://nodejs.org/api/errors.html /// -///////////////////////////////////////////////////////// - -{ - { - Error.stackTraceLimit = Infinity; - } - { - const myObject = {}; - Error.captureStackTrace(myObject); - } - { - const frames: NodeJS.CallSite[] = []; - Error.prepareStackTrace!(new Error(), frames); - } - { - const frame: NodeJS.CallSite = null!; - const frameThis: any = frame.getThis(); - const typeName: string | null = frame.getTypeName(); - const func: Function | undefined = frame.getFunction(); - const funcName: string | null = frame.getFunctionName(); - const meth: string | null = frame.getMethodName(); - const fname: string | null = frame.getFileName(); - const lineno: number | null = frame.getLineNumber(); - const colno: number | null = frame.getColumnNumber(); - const evalOrigin: string | undefined = frame.getEvalOrigin(); - const isTop: boolean = frame.isToplevel(); - const isEval: boolean = frame.isEval(); - const isNative: boolean = frame.isNative(); - const isConstr: boolean = frame.isConstructor(); - } -} - -/////////////////////////////////////////////////////////// -/// Console Tests : https://nodejs.org/api/console.html /// -/////////////////////////////////////////////////////////// - -{ - { - let _c: Console = console; - _c = console2; - } - { - const writeStream = fs.createWriteStream('./index.d.ts'); - let consoleInstance: Console = new console.Console(writeStream); - - consoleInstance = new console.Console(writeStream, writeStream); - consoleInstance = new console.Console(writeStream, writeStream, true); - consoleInstance = new console.Console({ - stdout: writeStream, - stderr: writeStream, - colorMode: 'auto', - ignoreErrors: true - }); - consoleInstance = new console.Console({ - stdout: writeStream, - colorMode: false - }); - consoleInstance = new console.Console({ - stdout: writeStream - }); - } - { - console.assert('value'); - console.assert('value', 'message'); - console.assert('value', 'message', 'foo', 'bar'); - console.clear(); - console.count(); - console.count('label'); - console.countReset(); - console.countReset('label'); - console.debug(); - console.debug('message'); - console.debug('message', 'foo', 'bar'); - console.dir('obj'); - console.dir('obj', { depth: 1 }); - console.error(); - console.error('message'); - console.error('message', 'foo', 'bar'); - console.group(); - console.group('label'); - console.group('label1', 'label2'); - console.groupCollapsed(); - console.groupEnd(); - console.info(); - console.info('message'); - console.info('message', 'foo', 'bar'); - console.log(); - console.log('message'); - console.log('message', 'foo', 'bar'); - console.table({ foo: 'bar' }); - console.table([{ foo: 'bar' }]); - console.table([{ foo: 'bar' }], ['foo']); - console.time(); - console.time('label'); - console.timeEnd(); - console.timeEnd('label'); - console.timeLog(); - console.timeLog('label'); - console.timeLog('label', 'foo', 'bar'); - console.trace(); - console.trace('message'); - console.trace('message', 'foo', 'bar'); - console.warn(); - console.warn('message'); - console.warn('message', 'foo', 'bar'); - - // --- Inspector mode only --- - console.profile(); - console.profile('label'); - console.profileEnd(); - console.profileEnd('label'); - console.timeStamp(); - console.timeStamp('label'); - } -} - -/***************************************************************************** - * * - * The following tests are the modules not mentioned in document but existed * - * * - *****************************************************************************/ - -/////////////////////////////////////////////////////////// -/// Inspector Tests /// -/////////////////////////////////////////////////////////// - -{ - { - const b: inspector.Console.ConsoleMessage = {source: 'test', text: 'test', level: 'error' }; - inspector.open(); - inspector.open(0); - inspector.open(0, 'localhost'); - inspector.open(0, 'localhost', true); - inspector.close(); - const inspectorUrl: string | undefined = inspector.url(); - - const session = new inspector.Session(); - session.connect(); - session.disconnect(); - - // Unknown post method - session.post('A.b', { key: 'value' }, (err, params) => {}); - // TODO: parameters are implicitly 'any' and need type annotation - session.post('A.b', (err: Error | null, params?: {}) => {}); - session.post('A.b'); - // Known post method - const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; - session.post('Runtime.evaluate', parameter, - (err: Error | null, params: inspector.Runtime.EvaluateReturnType) => {}); - session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { - const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails!; - const resultClassName: string = params.result.className!; - }); - session.post('Runtime.evaluate'); - - // General event - session.on('inspectorNotification', message => { - message; // $ExpectType InspectorNotification<{}> - }); - // Known events - session.on('Debugger.paused', (message: inspector.InspectorNotification) => { - const method: string = message.method; - const pauseReason: string = message.params.reason; - }); - session.on('Debugger.resumed', () => {}); - // Node Inspector events - session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification) => { - const value: Array<{}> = message.params.value; - }); - } -} - -/////////////////////////////////////////////////////////// -/// Trace Events Tests /// -/////////////////////////////////////////////////////////// - -{ - const enabledCategories: string | undefined = trace_events.getEnabledCategories(); - const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] }); - const categories: string = tracing.categories; - const enabled: boolean = tracing.enabled; - tracing.enable(); - tracing.disable(); -} - -//////////////////////////////////////////////////// -/// Node.js ESNEXT Support -//////////////////////////////////////////////////// - -{ - const s = 'foo'; - const s1: string = s.trimLeft(); - const s2: string = s.trimRight(); - const s3: string = s.trimStart(); - const s4: string = s.trimEnd(); -} diff --git a/types/node/v13/ts3.1/tsconfig.json b/types/node/v13/ts3.1/tsconfig.json deleted file mode 100644 index e2e30153f8..0000000000 --- a/types/node/v13/ts3.1/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "files": [ - "index.d.ts", - "node-tests.ts" - ], - "compilerOptions": { - "module": "commonjs", - "target": "esnext", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../../../", - "typeRoots": [ - "../../../" - ], - "paths": { - "node": [ - "node/v13" - ] - }, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - } -} diff --git a/types/node/v13/ts3.1/tslint.json b/types/node/v13/ts3.1/tslint.json deleted file mode 100644 index 65e8b18d2a..0000000000 --- a/types/node/v13/ts3.1/tslint.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "no-bad-reference": false, - "no-empty-interface": false, - "no-single-declare-module": false, - "unified-signatures": false - } -} diff --git a/types/node/v13/ts3.1/util.d.ts b/types/node/v13/ts3.1/util.d.ts deleted file mode 100644 index 542ad76524..0000000000 --- a/types/node/v13/ts3.1/util.d.ts +++ /dev/null @@ -1,194 +0,0 @@ -declare module "util" { - interface InspectOptions extends NodeJS.InspectOptions { } - type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; - type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; - interface InspectOptionsStylized extends InspectOptions { - stylize(text: string, styleType: Style): string; - } - function format(format: any, ...param: any[]): string; - function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; - /** @deprecated since v0.11.3 - use a third party module instead. */ - function log(string: string): void; - function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - function inspect(object: any, options: InspectOptions): string; - namespace inspect { - let colors: NodeJS.Dict<[number, number]>; - let styles: { - [K in Style]: string - }; - let defaultOptions: InspectOptions; - /** - * Allows changing inspect settings from the repl. - */ - let replDefaults: InspectOptions; - const custom: unique symbol; - } - /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ - function isArray(object: any): object is any[]; - /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ - function isRegExp(object: any): object is RegExp; - /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ - function isDate(object: any): object is Date; - /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ - function isError(object: any): object is Error; - function inherits(constructor: any, superConstructor: any): void; - function debuglog(key: string): (msg: string, ...param: any[]) => void; - /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ - function isBoolean(object: any): object is boolean; - /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ - function isBuffer(object: any): object is Buffer; - /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ - function isFunction(object: any): boolean; - /** @deprecated since v4.0.0 - use `value === null` instead. */ - function isNull(object: any): object is null; - /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ - function isNullOrUndefined(object: any): object is null | undefined; - /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ - function isNumber(object: any): object is number; - /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ - function isObject(object: any): boolean; - /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ - function isPrimitive(object: any): boolean; - /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ - function isString(object: any): object is string; - /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ - function isSymbol(object: any): object is symbol; - /** @deprecated since v4.0.0 - use `value === undefined` instead. */ - function isUndefined(object: any): object is undefined; - function deprecate(fn: T, message: string, code?: string): T; - function isDeepStrictEqual(val1: any, val2: any): boolean; - - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - - interface CustomPromisifyLegacy extends Function { - __promisify__: TCustom; - } - - interface CustomPromisifySymbol extends Function { - [promisify.custom]: TCustom; - } - - type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; - - function promisify(fn: CustomPromisify): TCustom; - function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; - function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; - function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): - (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): - (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify(fn: Function): Function; - namespace promisify { - const custom: unique symbol; - } - - namespace types { - function isAnyArrayBuffer(object: any): boolean; - function isArgumentsObject(object: any): object is IArguments; - function isArrayBuffer(object: any): object is ArrayBuffer; - function isArrayBufferView(object: any): object is ArrayBufferView; - function isAsyncFunction(object: any): boolean; - function isBooleanObject(object: any): object is Boolean; - function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); - function isDataView(object: any): object is DataView; - function isDate(object: any): object is Date; - function isExternal(object: any): boolean; - function isFloat32Array(object: any): object is Float32Array; - function isFloat64Array(object: any): object is Float64Array; - function isGeneratorFunction(object: any): boolean; - function isGeneratorObject(object: any): boolean; - function isInt8Array(object: any): object is Int8Array; - function isInt16Array(object: any): object is Int16Array; - function isInt32Array(object: any): object is Int32Array; - function isMap(object: any): boolean; - function isMapIterator(object: any): boolean; - function isModuleNamespaceObject(value: any): boolean; - function isNativeError(object: any): object is Error; - function isNumberObject(object: any): object is Number; - function isPromise(object: any): boolean; - function isProxy(object: any): boolean; - function isRegExp(object: any): object is RegExp; - function isSet(object: any): boolean; - function isSetIterator(object: any): boolean; - function isSharedArrayBuffer(object: any): boolean; - function isStringObject(object: any): boolean; - function isSymbolObject(object: any): boolean; - function isTypedArray(object: any): object is NodeJS.TypedArray; - function isUint8Array(object: any): object is Uint8Array; - function isUint8ClampedArray(object: any): object is Uint8ClampedArray; - function isUint16Array(object: any): object is Uint16Array; - function isUint32Array(object: any): object is Uint32Array; - function isWeakMap(object: any): boolean; - function isWeakSet(object: any): boolean; - function isWebAssemblyCompiledModule(object: any): boolean; - } - - class TextDecoder { - readonly encoding: string; - readonly fatal: boolean; - readonly ignoreBOM: boolean; - constructor( - encoding?: string, - options?: { fatal?: boolean; ignoreBOM?: boolean } - ); - decode( - input?: NodeJS.ArrayBufferView | ArrayBuffer | null, - options?: { stream?: boolean } - ): string; - } - - interface EncodeIntoResult { - /** - * The read Unicode code units of input. - */ - - read: number; - /** - * The written UTF-8 bytes of output. - */ - written: number; - } - - class TextEncoder { - readonly encoding: string; - encode(input?: string): Uint8Array; - encodeInto(input: string, output: Uint8Array): EncodeIntoResult; - } -} diff --git a/types/node/v13/ts3.1/assert.d.ts b/types/node/v13/ts3.4/assert.d.ts similarity index 100% rename from types/node/v13/ts3.1/assert.d.ts rename to types/node/v13/ts3.4/assert.d.ts diff --git a/types/node/v13/ts3.4/base.d.ts b/types/node/v13/ts3.4/base.d.ts index ae43027b06..b0b20075e7 100644 --- a/types/node/v13/ts3.4/base.d.ts +++ b/types/node/v13/ts3.4/base.d.ts @@ -12,11 +12,43 @@ /// /// -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -// tslint:disable-next-line:no-bad-reference -/// - -// TypeScript 3.2-specific augmentations: -/// -/// +// base definitions for all NodeJS modules that are not specific to any version of TypeScript /// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/node/v13/ts3.1/globals.global.d.ts b/types/node/v13/ts3.4/globals.global.d.ts similarity index 100% rename from types/node/v13/ts3.1/globals.global.d.ts rename to types/node/v13/ts3.4/globals.global.d.ts diff --git a/types/node/v13/ts3.4/index.d.ts b/types/node/v13/ts3.4/index.d.ts index 75ea7bda8d..f0691708b5 100644 --- a/types/node/v13/ts3.4/index.d.ts +++ b/types/node/v13/ts3.4/index.d.ts @@ -4,9 +4,5 @@ // Typically type modifiations should be made in base.d.ts instead of here /// - -// tslint:disable-next-line:no-bad-reference -/// - -// tslint:disable-next-line:no-bad-reference -/// +/// +/// diff --git a/types/node/v13/ts3.4/node-tests.ts b/types/node/v13/ts3.4/node-tests.ts index 56f949002e..8729614199 100644 --- a/types/node/v13/ts3.4/node-tests.ts +++ b/types/node/v13/ts3.4/node-tests.ts @@ -1,31 +1,352 @@ -// tslint:disable-next-line:no-bad-reference -import '../ts3.1/node-tests'; -import '../ts3.1/assert'; -import '../ts3.1/buffer'; -import '../ts3.1/child_process'; -import '../ts3.1/cluster'; -import '../ts3.1/crypto'; -import '../ts3.1/dgram'; -import '../ts3.1/global'; -import '../ts3.1/http'; -import '../ts3.1/http2'; -import '../ts3.1/net'; -import '../ts3.1/os'; -import '../ts3.1/path'; -import '../ts3.1/perf_hooks'; -import '../ts3.1/process'; -import '../ts3.1/querystring'; -import '../ts3.1/readline'; -import '../ts3.1/repl'; -import '../ts3.1/stream'; -import '../ts3.1/tls'; -import '../ts3.1/tty'; -import '../ts3.1/util'; -import '../ts3.1/worker_threads'; -import '../ts3.1/zlib'; +import * as fs from "fs"; +import * as url from "url"; +import * as util from "util"; +import * as http from "http"; +import * as https from "https"; +import * as console2 from "console"; +import * as timers from "timers"; +import * as inspector from "inspector"; +import * as trace_events from "trace_events"; -import { types, promisify } from 'util'; -import { BigIntStats, statSync, Stats } from 'fs'; +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + +{ + let agent: https.Agent = new https.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256, + maxCachedSessions: 100, + timeout: 15000 + }); + + agent = https.globalAgent; + + https.request({ + agent: false + }); + https.request({ + agent + }); + https.request({ + agent: undefined + }); + + https.get('http://www.example.com/xyz'); + https.request('http://www.example.com/xyz'); + + https.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + https.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + + https.get(new url.URL('http://www.example.com/xyz')); + https.request(new url.URL('http://www.example.com/xyz')); + + https.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + https.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + + const opts: https.RequestOptions = { + path: '/some/path' + }; + https.get(new url.URL('http://www.example.com'), opts); + https.request(new url.URL('http://www.example.com'), opts); + https.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + https.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + + https.globalAgent.options.ca = []; + + { + function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} + + class MyIncomingMessage extends http.IncomingMessage { + foo: number; + } + + class MyServerResponse extends http.ServerResponse { + foo: string; + } + + let server: https.Server; + + server = new https.Server(); + server = new https.Server(reqListener); + server = new https.Server({ IncomingMessage: MyIncomingMessage}); + + server = new https.Server({ + IncomingMessage: MyIncomingMessage, + ServerResponse: MyServerResponse + }, reqListener); + + server = https.createServer(); + server = https.createServer(reqListener); + server = https.createServer({ IncomingMessage: MyIncomingMessage }); + server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); + + const timeout: number = server.timeout; + const listening: boolean = server.listening; + const keepAliveTimeout: number = server.keepAliveTimeout; + const maxHeadersCount: number | null = server.maxHeadersCount; + const headersTimeout: number = server.headersTimeout; + server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); + } +} + +///////////////////////////////////////////////////// +/// Timers tests : https://nodejs.org/api/timers.html +///////////////////////////////////////////////////// + +{ + { + const immediate = timers + .setImmediate(() => { + console.log('immediate'); + }) + .unref() + .ref(); + const b: boolean = immediate.hasRef(); + timers.clearImmediate(immediate); + } + { + const timeout = timers + .setInterval(() => { + console.log('interval'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearInterval(timeout); + } + { + const timeout = timers + .setTimeout(() => { + console.log('timeout'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearTimeout(timeout); + } + async function testPromisify(doSomething: { + (foo: any, onSuccessCallback: (result: string) => void, onErrorCallback: (reason: any) => void): void; + [util.promisify.custom](foo: any): Promise; + }) { + const setTimeout = util.promisify(timers.setTimeout); + let v: void = await setTimeout(100); // tslint:disable-line no-void-expression void-return + let s: string = await setTimeout(100, ""); + + const setImmediate = util.promisify(timers.setImmediate); + v = await setImmediate(); // tslint:disable-line no-void-expression + s = await setImmediate(""); + + // $ExpectType (foo: any) => Promise + const doSomethingPromise = util.promisify(doSomething); + + // $ExpectType string + s = await doSomethingPromise('foo'); + } +} + +///////////////////////////////////////////////////////// +/// Errors Tests : https://nodejs.org/api/errors.html /// +///////////////////////////////////////////////////////// + +{ + { + Error.stackTraceLimit = Infinity; + } + { + const myObject = {}; + Error.captureStackTrace(myObject); + } + { + const frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace!(new Error(), frames); + } + { + const frame: NodeJS.CallSite = null!; + const frameThis: any = frame.getThis(); + const typeName: string | null = frame.getTypeName(); + const func: Function | undefined = frame.getFunction(); + const funcName: string | null = frame.getFunctionName(); + const meth: string | null = frame.getMethodName(); + const fname: string | null = frame.getFileName(); + const lineno: number | null = frame.getLineNumber(); + const colno: number | null = frame.getColumnNumber(); + const evalOrigin: string | undefined = frame.getEvalOrigin(); + const isTop: boolean = frame.isToplevel(); + const isEval: boolean = frame.isEval(); + const isNative: boolean = frame.isNative(); + const isConstr: boolean = frame.isConstructor(); + } +} + +/////////////////////////////////////////////////////////// +/// Console Tests : https://nodejs.org/api/console.html /// +/////////////////////////////////////////////////////////// + +{ + { + let _c: Console = console; + _c = console2; + } + { + const writeStream = fs.createWriteStream('./index.d.ts'); + let consoleInstance: Console = new console.Console(writeStream); + + consoleInstance = new console.Console(writeStream, writeStream); + consoleInstance = new console.Console(writeStream, writeStream, true); + consoleInstance = new console.Console({ + stdout: writeStream, + stderr: writeStream, + colorMode: 'auto', + ignoreErrors: true + }); + consoleInstance = new console.Console({ + stdout: writeStream, + colorMode: false + }); + consoleInstance = new console.Console({ + stdout: writeStream + }); + } + { + console.assert('value'); + console.assert('value', 'message'); + console.assert('value', 'message', 'foo', 'bar'); + console.clear(); + console.count(); + console.count('label'); + console.countReset(); + console.countReset('label'); + console.debug(); + console.debug('message'); + console.debug('message', 'foo', 'bar'); + console.dir('obj'); + console.dir('obj', { depth: 1 }); + console.error(); + console.error('message'); + console.error('message', 'foo', 'bar'); + console.group(); + console.group('label'); + console.group('label1', 'label2'); + console.groupCollapsed(); + console.groupEnd(); + console.info(); + console.info('message'); + console.info('message', 'foo', 'bar'); + console.log(); + console.log('message'); + console.log('message', 'foo', 'bar'); + console.table({ foo: 'bar' }); + console.table([{ foo: 'bar' }]); + console.table([{ foo: 'bar' }], ['foo']); + console.time(); + console.time('label'); + console.timeEnd(); + console.timeEnd('label'); + console.timeLog(); + console.timeLog('label'); + console.timeLog('label', 'foo', 'bar'); + console.trace(); + console.trace('message'); + console.trace('message', 'foo', 'bar'); + console.warn(); + console.warn('message'); + console.warn('message', 'foo', 'bar'); + + // --- Inspector mode only --- + console.profile(); + console.profile('label'); + console.profileEnd(); + console.profileEnd('label'); + console.timeStamp(); + console.timeStamp('label'); + } +} + +/***************************************************************************** + * * + * The following tests are the modules not mentioned in document but existed * + * * + *****************************************************************************/ + +/////////////////////////////////////////////////////////// +/// Inspector Tests /// +/////////////////////////////////////////////////////////// + +{ + { + const b: inspector.Console.ConsoleMessage = {source: 'test', text: 'test', level: 'error' }; + inspector.open(); + inspector.open(0); + inspector.open(0, 'localhost'); + inspector.open(0, 'localhost', true); + inspector.close(); + const inspectorUrl: string | undefined = inspector.url(); + + const session = new inspector.Session(); + session.connect(); + session.disconnect(); + + // Unknown post method + session.post('A.b', { key: 'value' }, (err, params) => {}); + // TODO: parameters are implicitly 'any' and need type annotation + session.post('A.b', (err: Error | null, params?: {}) => {}); + session.post('A.b'); + // Known post method + const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; + session.post('Runtime.evaluate', parameter, + (err: Error | null, params: inspector.Runtime.EvaluateReturnType) => {}); + session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { + const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails!; + const resultClassName: string = params.result.className!; + }); + session.post('Runtime.evaluate'); + + // General event + session.on('inspectorNotification', message => { + message; // $ExpectType InspectorNotification<{}> + }); + // Known events + session.on('Debugger.paused', (message: inspector.InspectorNotification) => { + const method: string = message.method; + const pauseReason: string = message.params.reason; + }); + session.on('Debugger.resumed', () => {}); + // Node Inspector events + session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification) => { + const value: Array<{}> = message.params.value; + }); + } +} + +/////////////////////////////////////////////////////////// +/// Trace Events Tests /// +/////////////////////////////////////////////////////////// + +{ + const enabledCategories: string | undefined = trace_events.getEnabledCategories(); + const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] }); + const categories: string = tracing.categories; + const enabled: boolean = tracing.enabled; + tracing.enable(); + tracing.disable(); +} + +//////////////////////////////////////////////////// +/// Node.js ESNEXT Support +//////////////////////////////////////////////////// + +{ + const s = 'foo'; + const s1: string = s.trimLeft(); + const s2: string = s.trimRight(); + const s3: string = s.trimStart(); + const s4: string = s.trimEnd(); +} ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -39,10 +360,10 @@ import { BigIntStats, statSync, Stats } from 'fs'; // Util Tests { const value: BigInt64Array | BigUint64Array | number = [] as any; - if (types.isBigInt64Array(value)) { + if (util.types.isBigInt64Array(value)) { // $ExpectType BigInt64Array const b = value; - } else if (types.isBigUint64Array(value)) { + } else if (util.types.isBigUint64Array(value)) { // $ExpectType BigUint64Array const b = value; } else { @@ -50,15 +371,15 @@ import { BigIntStats, statSync, Stats } from 'fs'; const b = value; } - const arg1UnknownError: (arg: string) => Promise = promisify((arg: string, cb: (err: unknown, result: number) => void): void => { }); - const arg1AnyError: (arg: string) => Promise = promisify((arg: string, cb: (err: any, result: number) => void): void => { }); + const arg1UnknownError: (arg: string) => Promise = util.promisify((arg: string, cb: (err: unknown, result: number) => void): void => { }); + const arg1AnyError: (arg: string) => Promise = util.promisify((arg: string, cb: (err: any, result: number) => void): void => { }); } // FS Tests { - const bigStats: BigIntStats = statSync('.', { bigint: true }); + const bigStats: fs.BigIntStats = fs.statSync('.', { bigint: true }); const bigIntStat: bigint = bigStats.atimeNs; - const anyStats: Stats | BigIntStats = statSync('.', { bigint: Math.random() > 0.5 }); + const anyStats: fs.Stats | fs.BigIntStats = fs.statSync('.', { bigint: Math.random() > 0.5 }); } // Global Tests diff --git a/types/node/v13/ts3.4/tslint.json b/types/node/v13/ts3.4/tslint.json index 9061fbd0e3..65e8b18d2a 100644 --- a/types/node/v13/ts3.4/tslint.json +++ b/types/node/v13/ts3.4/tslint.json @@ -1,6 +1,10 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-bad-reference": false - } + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "no-bad-reference": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "unified-signatures": false + } } diff --git a/types/node/v13/ts3.6/index.d.ts b/types/node/v13/ts3.6/index.d.ts index 68d40ba156..ae05a5da44 100644 --- a/types/node/v13/ts3.6/index.d.ts +++ b/types/node/v13/ts3.6/index.d.ts @@ -5,4 +5,4 @@ /// // tslint:disable-next-line:no-bad-reference -/// +/// diff --git a/types/node/v13/ts3.6/node-tests.ts b/types/node/v13/ts3.6/node-tests.ts index 9875d958a2..b341061ae0 100644 --- a/types/node/v13/ts3.6/node-tests.ts +++ b/types/node/v13/ts3.6/node-tests.ts @@ -1,29 +1,5 @@ // tslint:disable-next-line:no-bad-reference import '../ts3.4/node-tests'; -import '../ts3.1/assert'; -import '../ts3.1/buffer'; -import '../ts3.1/child_process'; -import '../ts3.1/cluster'; -import '../ts3.1/crypto'; -import '../ts3.1/dgram'; -import '../ts3.1/ts3.2/fs'; -import '../ts3.1/ts3.2/global'; -import '../ts3.1/http'; -import '../ts3.1/http2'; -import '../ts3.1/net'; -import '../ts3.1/os'; -import '../ts3.1/path'; -import '../ts3.1/perf_hooks'; -import '../ts3.1/process'; -import '../ts3.1/querystring'; -import '../ts3.1/readline'; -import '../ts3.1/repl'; -import '../ts3.1/stream'; -import '../ts3.1/tls'; -import '../ts3.1/tty'; -import '../ts3.1/ts3.2/util'; -import '../ts3.1/worker_threads'; -import '../ts3.1/zlib'; ///////////////////////////////////////////////////// /// WASI tests : https://nodejs.org/api/wasi.html /// diff --git a/types/node/v13/util.d.ts b/types/node/v13/util.d.ts index 84d7ae2c0b..f4d1bda167 100644 --- a/types/node/v13/util.d.ts +++ b/types/node/v13/util.d.ts @@ -1,9 +1,196 @@ -// tslint:disable-next-line:no-bad-reference -/// - declare module "util" { + interface InspectOptions extends NodeJS.InspectOptions { } + type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; + type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; + interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + function format(format: any, ...param: any[]): string; + function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; + /** @deprecated since v0.11.3 - use a third party module instead. */ + function log(string: string): void; + function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + function inspect(object: any, options: InspectOptions): string; + namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + const custom: unique symbol; + } + /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ + function isArray(object: any): object is any[]; + /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ + function isRegExp(object: any): object is RegExp; + /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ + function isDate(object: any): object is Date; + /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ + function isError(object: any): object is Error; + function inherits(constructor: any, superConstructor: any): void; + function debuglog(key: string): (msg: string, ...param: any[]) => void; + /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ + function isBoolean(object: any): object is boolean; + /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ + function isBuffer(object: any): object is Buffer; + /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ + function isFunction(object: any): boolean; + /** @deprecated since v4.0.0 - use `value === null` instead. */ + function isNull(object: any): object is null; + /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ + function isNullOrUndefined(object: any): object is null | undefined; + /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ + function isNumber(object: any): object is number; + /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ + function isObject(object: any): boolean; + /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ + function isPrimitive(object: any): boolean; + /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ + function isString(object: any): object is string; + /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ + function isSymbol(object: any): object is symbol; + /** @deprecated since v4.0.0 - use `value === undefined` instead. */ + function isUndefined(object: any): object is undefined; + function deprecate(fn: T, message: string, code?: string): T; + function isDeepStrictEqual(val1: any, val2: any): boolean; + + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + + interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + + interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + + type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; + + function promisify(fn: CustomPromisify): TCustom; + function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; + function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): + (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): + (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify(fn: Function): Function; + namespace promisify { + const custom: unique symbol; + } + namespace types { + function isAnyArrayBuffer(object: any): boolean; + function isArgumentsObject(object: any): object is IArguments; + function isArrayBuffer(object: any): object is ArrayBuffer; + function isArrayBufferView(object: any): object is ArrayBufferView; + function isAsyncFunction(object: any): boolean; function isBigInt64Array(value: any): value is BigInt64Array; function isBigUint64Array(value: any): value is BigUint64Array; + function isBooleanObject(object: any): object is Boolean; + function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); + function isDataView(object: any): object is DataView; + function isDate(object: any): object is Date; + function isExternal(object: any): boolean; + function isFloat32Array(object: any): object is Float32Array; + function isFloat64Array(object: any): object is Float64Array; + function isGeneratorFunction(object: any): boolean; + function isGeneratorObject(object: any): boolean; + function isInt8Array(object: any): object is Int8Array; + function isInt16Array(object: any): object is Int16Array; + function isInt32Array(object: any): object is Int32Array; + function isMap(object: any): boolean; + function isMapIterator(object: any): boolean; + function isModuleNamespaceObject(value: any): boolean; + function isNativeError(object: any): object is Error; + function isNumberObject(object: any): object is Number; + function isPromise(object: any): boolean; + function isProxy(object: any): boolean; + function isRegExp(object: any): object is RegExp; + function isSet(object: any): boolean; + function isSetIterator(object: any): boolean; + function isSharedArrayBuffer(object: any): boolean; + function isStringObject(object: any): boolean; + function isSymbolObject(object: any): boolean; + function isTypedArray(object: any): object is NodeJS.TypedArray; + function isUint8Array(object: any): object is Uint8Array; + function isUint8ClampedArray(object: any): object is Uint8ClampedArray; + function isUint16Array(object: any): object is Uint16Array; + function isUint32Array(object: any): object is Uint32Array; + function isWeakMap(object: any): boolean; + function isWeakSet(object: any): boolean; + function isWebAssemblyCompiledModule(object: any): boolean; + } + + class TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { fatal?: boolean; ignoreBOM?: boolean } + ); + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { stream?: boolean } + ): string; + } + + interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + + class TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; + encodeInto(input: string, output: Uint8Array): EncodeIntoResult; } } diff --git a/types/node/v6/package.json b/types/node/v6/package.json deleted file mode 100644 index 54d5b8743e..0000000000 --- a/types/node/v6/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "private": true, - "types": "index", - "typesVersions": { - "<=3.1": { - "*": [ - "ts3.1/*" - ] - } - } -} diff --git a/types/node/v6/ts3.1/index.d.ts b/types/node/v6/ts3.1/index.d.ts deleted file mode 100644 index 91a8d6576d..0000000000 --- a/types/node/v6/ts3.1/index.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -/************************************************ -* * -* Node.js v6.x API * -* * -************************************************/ -// NOTE: These definitions support NodeJS and TypeScript 3.1. - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 - -// NOTE: Augmentations for TypeScript 3.1 and later should use individual files for overrides -// within the respective ~/ts3.1 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.1, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -// tslint:disable-next-line:no-bad-reference -/// - -// TypeScript 2.1-specific augmentations: - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } -interface Iterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IterableIterator { } -interface IteratorResult { } -interface AsyncIterableIterator {} -interface SymbolConstructor { - readonly iterator: symbol; -} -declare var Symbol: SymbolConstructor; diff --git a/types/node/v6/ts3.1/node-tests.ts b/types/node/v6/ts3.1/node-tests.ts deleted file mode 100644 index 5ca32d660c..0000000000 --- a/types/node/v6/ts3.1/node-tests.ts +++ /dev/null @@ -1,2606 +0,0 @@ -import assert = require("assert"); -import * as fs from "fs"; -import * as events from "events"; -import events2 = require("events"); -import * as zlib from "zlib"; -import * as url from "url"; -import * as util from "util"; -import * as crypto from "crypto"; -import * as tls from "tls"; -import * as http from "http"; -import * as https from "https"; -import * as net from "net"; -import * as tty from "tty"; -import * as dgram from "dgram"; -import * as querystring from "querystring"; -import * as path from "path"; -import * as readline from "readline"; -import * as childProcess from "child_process"; -import * as cluster from "cluster"; -import * as os from "os"; -import * as vm from "vm"; -import * as console2 from "console"; -import * as string_decoder from "string_decoder"; -import * as stream from "stream"; -import * as timers from "timers"; -import * as repl from "repl"; -import * as dns from "dns"; - -// Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; - -////////////////////////////////////////////////////////// -/// Global Tests : https://nodejs.org/api/global.html /// -////////////////////////////////////////////////////////// -namespace global_tests { - { - let x: NodeModule; - let y: NodeModule; - x.children.push(y); - x.parent = require.main; - require.main = y; - } -} - -////////////////////////////////////////////////////////// -/// Assert Tests : https://nodejs.org/api/assert.html /// -////////////////////////////////////////////////////////// - -namespace assert_tests { - { - assert(1 + 1 - 2 === 0, "The universe isn't how it should."); - - assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - - assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); - - assert.doesNotThrow(() => { - const b = false; - if (b) { throw "a hammer at your face"; } - }, undefined, "What the...*crunch*"); - - assert.equal(3, "3", "uses == comparator"); - - assert.fail("actual", "expected", "message"); - - assert.fail(1, 2, undefined, '>'); - - assert.ifError(0); - - assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - - assert.notEqual(1, 2, "uses != comparator"); - - assert.notStrictEqual(2, "2", "uses === comparator"); - - assert.ok(true); - assert.ok(1); - - assert.strictEqual(1, 1, "uses === comparator"); - - assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); - } -} - -//////////////////////////////////////////////////// -/// Events tests : http://nodejs.org/api/events.html -//////////////////////////////////////////////////// - -namespace events_tests { - let emitter: events.EventEmitter; - let event: string | symbol; - let listener: Function; - let any: any; - - { - let result: events.EventEmitter; - - result = emitter.addListener(event, listener); - result = emitter.on(event, listener); - result = emitter.once(event, listener); - result = emitter.prependListener(event, listener); - result = emitter.prependOnceListener(event, listener); - result = emitter.removeListener(event, listener); - result = emitter.removeAllListeners(); - result = emitter.removeAllListeners(event); - result = emitter.setMaxListeners(42); - } - - { - let result: number; - - result = events.EventEmitter.defaultMaxListeners; - result = events.EventEmitter.listenerCount(emitter, event); // deprecated - - result = emitter.getMaxListeners(); - result = emitter.listenerCount(event); - } - - { - let result: Function[]; - - result = emitter.listeners(event); - } - - { - let result: boolean; - - result = emitter.emit(event); - result = emitter.emit(event, any); - result = emitter.emit(event, any, any); - result = emitter.emit(event, any, any, any); - } - - { - let result: (string | symbol)[]; - - result = emitter.eventNames(); - } - - { - class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } - } - } - - { - new events2(); - } -} - -//////////////////////////////////////////////////// -/// File system tests : http://nodejs.org/api/fs.html -//////////////////////////////////////////////////// - -namespace fs_tests { - { - fs.writeFile("thebible.txt", - "Do unto others as you would have them do unto you.", - assert.ifError); - - fs.write(1234, "test"); - - fs.writeFile("Harry Potter", - "\"You be wizzing, Harry,\" jived Dumbledore.", - { - encoding: "ascii" - }, - assert.ifError); - - fs.writeFile("testfile", "content", "utf8", assert.ifError); - - fs.writeFileSync("testfile", "content", "utf8"); - fs.writeFileSync("testfile", "content", { encoding: "utf8" }); - } - - { - fs.appendFile("testfile", "foobar", "utf8", assert.ifError); - fs.appendFile("testfile", "foobar", { encoding: "utf8" }, assert.ifError); - fs.appendFileSync("testfile", "foobar", "utf8"); - fs.appendFileSync("testfile", "foobar", { encoding: "utf8" }); - } - - { - var content: string; - var buffer: Buffer; - var stringOrBuffer: string | Buffer; - var nullEncoding: string | null = null; - var stringEncoding: string | null = 'utf8'; - - content = fs.readFileSync('testfile', 'utf8'); - content = fs.readFileSync('testfile', { encoding: 'utf8' }); - stringOrBuffer = fs.readFileSync('testfile', stringEncoding); - stringOrBuffer = fs.readFileSync('testfile', { encoding: stringEncoding }); - - buffer = fs.readFileSync('testfile'); - buffer = fs.readFileSync('testfile', null); - buffer = fs.readFileSync('testfile', { encoding: null }); - stringOrBuffer = fs.readFileSync('testfile', nullEncoding); - stringOrBuffer = fs.readFileSync('testfile', { encoding: nullEncoding }); - - buffer = fs.readFileSync('testfile', { flag: 'r' }); - - fs.readFile('testfile', 'utf8', (err, data) => content = data); - fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); - fs.readFile('testfile', stringEncoding, (err, data) => stringOrBuffer = data); - fs.readFile('testfile', { encoding: stringEncoding }, (err, data) => stringOrBuffer = data); - - fs.readFile('testfile', (err, data) => buffer = data); - fs.readFile('testfile', null, (err, data) => buffer = data); - fs.readFile('testfile', { encoding: null }, (err, data) => buffer = data); - fs.readFile('testfile', nullEncoding, (err, data) => stringOrBuffer = data); - fs.readFile('testfile', { encoding: nullEncoding }, (err, data) => stringOrBuffer = data); - - fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); - } - - { - fs.readdir('foo', (err: any, files: string[]) => {}) - fs.readdir('foo', 'utf8', (err: any, files: string[]) => {}); - fs.readdir('foo', {encoding: 'utf8'}, (err: any, files: string[]) => {}); - fs.readdir('foo', 'buffer', (err: any, files: Buffer[]) => {}); - fs.readdir('foo', {encoding: 'buffer'}, (err: any, files: Buffer[]) => {}); - - let fsStringOut: string[] = fs.readdirSync('utf8'); - fsStringOut = fs.readdirSync('foo', 'utf8'); - fsStringOut = fs.readdirSync('foo', {encoding: 'utf8'}); - - let fsBufferOut: Buffer[] = fs.readdirSync('utf8', 'buffer'); - fsBufferOut = fs.readdirSync('foo', {encoding: 'buffer'}); - - let enc = 'buffer'; - fs.readdirSync('path', { encoding: enc }); // $ExpectType string[] | Buffer[] - fs.readdirSync('path', { }); // $ExpectType string[] | Buffer[] - } - - { - var errno: number; - fs.readFile('testfile', (err, data) => { - if (err && err.errno) { - errno = err.errno; - } - }); - } - - { - fs.mkdtemp('/tmp/foo-', (err, folder) => { - console.log(folder); - // Prints: /tmp/foo-itXde2 - }); - } - - { - var tempDir: string; - tempDir = fs.mkdtempSync('/tmp/foo-'); - } - - { - fs.watch('/tmp/foo-', (event, filename) => { - console.log(event, filename); - }); - - fs.watch('/tmp/foo-', 'utf8', (event, filename) => { - console.log(event, filename); - }); - - fs.watch('/tmp/foo-', { - recursive: true, - persistent: true, - encoding: 'utf8' - }, (event, filename) => { - console.log(event, filename); - }); - } - - { - fs.access('/path/to/folder', (err) => { }); - - fs.access(Buffer.from(''), (err) => { }); - - fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - - fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - - fs.accessSync('/path/to/folder'); - - fs.accessSync(Buffer.from('')); - - fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); - - fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); - } -} - -/////////////////////////////////////////////////////// -/// Buffer tests : https://nodejs.org/api/buffer.html -/////////////////////////////////////////////////////// - -function bufferTests() { - var utf8Buffer = new Buffer('test'); - var base64Buffer = new Buffer('', 'base64'); - var octets: Uint8Array = null; - var octetBuffer = new Buffer(octets); - var sharedBuffer = new Buffer(octets.buffer); - var copiedBuffer = new Buffer(utf8Buffer); - console.log(Buffer.isBuffer(octetBuffer)); - console.log(Buffer.isEncoding('utf8')); - console.log(Buffer.byteLength('xyz123')); - console.log(Buffer.byteLength('xyz123', 'ascii')); - var result1 = Buffer.concat([utf8Buffer, base64Buffer]); - var result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999); - - // Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64() - { - const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); - buf.swap16(); - buf.swap32(); - buf.swap64(); - } - - // Class Method: Buffer.from(data) - { - // Array - const buf1: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); - // Buffer - const buf2: Buffer = Buffer.from(buf1); - // String - const buf3: Buffer = Buffer.from('this is a tést'); - // ArrayBuffer - const arr: Uint16Array = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; - const buf4: Buffer = Buffer.from(arr.buffer); - } - - // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) - { - const arr: Uint16Array = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; - - let buf: Buffer; - buf = Buffer.from(arr.buffer, 1); - buf = Buffer.from(arr.buffer, 0, 1); - } - - // Class Method: Buffer.from(str[, encoding]) - { - const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); - } - - // Class Method: Buffer.alloc(size[, fill[, encoding]]) - { - const buf1: Buffer = Buffer.alloc(5); - const buf2: Buffer = Buffer.alloc(5, 'a'); - const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); - } - // Class Method: Buffer.allocUnsafe(size) - { - const buf: Buffer = Buffer.allocUnsafe(5); - } - // Class Method: Buffer.allocUnsafeSlow(size) - { - const buf: Buffer = Buffer.allocUnsafeSlow(10); - } - - // Test that TS 1.6 works with the 'as Buffer' annotation - // on isBuffer. - var a: Buffer | number; - a = new Buffer(10); - if (Buffer.isBuffer(a)) { - a.writeUInt8(3, 4); - } - - // write* methods return offsets. - var b = new Buffer(16); - var result: number = b.writeUInt32LE(0, 0); - result = b.writeUInt16LE(0, 4); - result = b.writeUInt8(0, 6); - result = b.writeInt8(0, 7); - result = b.writeDoubleLE(0, 8); - - // fill returns the input buffer. - b.fill('a').fill('b'); - - { - let buffer = new Buffer('123'); - let index: number; - index = buffer.indexOf("23"); - index = buffer.indexOf("23", 1); - index = buffer.indexOf("23", 1, "utf8"); - index = buffer.indexOf(23); - index = buffer.indexOf(buffer); - } - - { - let buffer = new Buffer('123'); - let index: number; - index = buffer.lastIndexOf("23"); - index = buffer.lastIndexOf("23", 1); - index = buffer.lastIndexOf("23", 1, "utf8"); - index = buffer.lastIndexOf(23); - index = buffer.lastIndexOf(buffer); - } - - { - let buffer = new Buffer('123'); - let val: [number, number]; - - /* comment out for --target es5 - for (let entry of buffer.entries()) { - val = entry; - } - */ - } - - { - let buffer = new Buffer('123'); - let includes: boolean; - includes = buffer.includes("23"); - includes = buffer.includes("23", 1); - includes = buffer.includes("23", 1, "utf8"); - includes = buffer.includes(23); - includes = buffer.includes(23, 1); - includes = buffer.includes(23, 1, "utf8"); - includes = buffer.includes(buffer); - includes = buffer.includes(buffer, 1); - includes = buffer.includes(buffer, 1, "utf8"); - } - - { - let buffer = new Buffer('123'); - let val: number; - - /* comment out for --target es5 - for (let key of buffer.keys()) { - val = key; - } - */ - } - - { - let buffer = new Buffer('123'); - let val: number; - - /* comment out for --target es5 - for (let value of buffer.values()) { - val = value; - } - */ - } - - // Imported Buffer from buffer module works properly - { - let b = new ImportedBuffer('123'); - b.writeUInt8(0, 6); - let sb = new ImportedSlowBuffer(43); - b.writeUInt8(0, 6); - } - - // Buffer has Uint8Array's buffer field (an ArrayBuffer). - { - let buffer = new Buffer('123'); - let octets = new Uint8Array(buffer.buffer); - } -} - - -//////////////////////////////////////////////////// -/// Url tests : http://nodejs.org/api/url.html -//////////////////////////////////////////////////// - -namespace url_tests { - { - url.format(url.parse('http://www.example.com/xyz')); - - url.format('http://www.example.com/xyz'); - - // https://google.com/search?q=you're%20a%20lizard%2C%20gary - url.format({ - protocol: 'https', - host: "google.com", - pathname: 'search', - query: { q: "you're a lizard, gary" } - }); - - const myURL = new url.URL('https://a:b@你好你好?abc#foo'); - url.format(myURL, { fragment: false, unicode: true, auth: false }); - } - - { - var helloUrl = url.parse('http://example.com/?hello=world', true) - assert.equal(helloUrl.query.hello, 'world'); - } - - { - const ascii: string = url.domainToASCII('español.com'); - const unicode: string = url.domainToUnicode('xn--espaol-zwa.com'); - } - - { - let myURL = new url.URL('https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.hash, '#bar'); - assert.equal(myURL.host, 'example.org:81'); - assert.equal(myURL.hostname, 'example.org'); - assert.equal(myURL.href, 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.origin, 'https://example.org:81'); - assert.equal(myURL.password, 'thepwd'); - assert.equal(myURL.username, 'theuser'); - assert.equal(myURL.pathname, '/foo/path'); - assert.equal(myURL.port, "81"); - assert.equal(myURL.protocol, "https:"); - assert.equal(myURL.search, "?query=string"); - assert.equal(myURL.toString(), 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert(myURL.searchParams instanceof url.URLSearchParams); - - myURL.host = 'example.org:82'; - myURL.hostname = 'example.com'; - myURL.href = 'http://other.com'; - myURL.hash = 'baz'; - myURL.password = "otherpwd"; - myURL.username = "otheruser"; - myURL.pathname = "/otherPath"; - myURL.port = "82"; - myURL.protocol = "http"; - myURL.search = "a=b"; - assert.equal(myURL.href, 'http://otheruser:otherpwd@other.com:82/otherPath?a=b#baz'); - - myURL = new url.URL('/foo', 'https://example.org/'); - assert.equal(myURL.href, 'https://example.org/foo'); - assert.equal(myURL.toJSON(), myURL.href); - } - - { - const searchParams = new url.URLSearchParams('abc=123'); - - assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { - assert.equal(name, 'abc'); - assert.equal(value, '123'); - assert.equal(me, searchParams); - }); - - assert.equal(searchParams.get('abc'), '123'); - - searchParams.append('abc', 'xyz'); - - assert.deepEqual(searchParams.getAll('abc'), ['123', 'xyz']); - - const entries = searchParams.entries(); - assert.deepEqual(entries.next(), { value: ["abc", "123"], done: false}); - assert.deepEqual(entries.next(), { value: ["abc", "xyz"], done: false}); - assert.deepEqual(entries.next(), { value: undefined, done: true}); - - const keys = searchParams.keys(); - assert.deepEqual(keys.next(), { value: "abc", done: false}); - assert.deepEqual(keys.next(), { value: "abc", done: false}); - assert.deepEqual(keys.next(), { value: undefined, done: true}); - - const values = searchParams.values(); - assert.deepEqual(values.next(), { value: "123", done: false}); - assert.deepEqual(values.next(), { value: "xyz", done: false}); - assert.deepEqual(values.next(), { value: undefined, done: true}); - - searchParams.set('abc', 'b'); - assert.deepEqual(searchParams.getAll('abc'), ['b']); - - searchParams.delete('a'); - assert(!searchParams.has('a')); - assert.equal(searchParams.get('a'), null); - - searchParams.sort(); - } - - { - const searchParams = new url.URLSearchParams({ - user: 'abc', - query: ['first', 'second'] - }); - - assert.equal(searchParams.toString(), 'user=abc&query=first%2Csecond'); - assert.deepEqual(searchParams.getAll('query'), ['first,second']); - } - - { - // Using an array - let params = new url.URLSearchParams([ - ['user', 'abc'], - ['query', 'first'], - ['query', 'second'] - ]); - assert.equal(params.toString(), 'user=abc&query=first&query=second'); - } -} - -///////////////////////////////////////////////////// -/// util tests : https://nodejs.org/api/util.html /// -///////////////////////////////////////////////////// - -namespace util_tests { - { - // Old and new util.inspect APIs - util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], false, null); - util.inspect(["This is nice"], { - colors: true, - depth: 5, - customInspect: false, - showProxy: true, - maxArrayLength: 10, - breakLength: 20 - }); - util.inspect(["This is nice"], { - colors: true, - depth: null, - customInspect: false, - showProxy: true, - maxArrayLength: null, - breakLength: Infinity - }); - // util.deprecate - const foo = () => {}; - // $ExpectType () => void - util.deprecate(foo, 'foo() is deprecated, use bar() instead'); - // $ExpectType (fn: T, message: string) => T - util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); - } -} - -//////////////////////////////////////////////////// -/// Stream tests : http://nodejs.org/api/stream.html -//////////////////////////////////////////////////// - -// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options -function stream_readable_pipe_test() { - var rs = fs.createReadStream(Buffer.from('file.txt')); - var r = fs.createReadStream('file.txt'); - var z = zlib.createGzip({ finishFlush: zlib.Z_FINISH }); - var w = fs.createWriteStream('file.txt.gz'); - - assert(typeof r.bytesRead === 'number'); - assert(typeof r.path === 'string'); - assert(rs.path instanceof Buffer); - - r.pipe(z).pipe(w); - - r.close(); - rs.close(); -} - -// helpers -const compressMe = new Buffer("some data"); -const compressMeString = "compress me!"; - -zlib.deflate(compressMe, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMeString, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); -const inflated = zlib.inflateSync(zlib.deflateSync(compressMe)); -const inflatedString = zlib.inflateSync(zlib.deflateSync(compressMeString)); - -zlib.deflateRaw(compressMe, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); -zlib.deflateRaw(compressMeString, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); -const inflatedRaw: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMe)); -const inflatedRawString: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMeString)); - -zlib.gzip(compressMe, (err: Error, result: Buffer) => zlib.gunzip(result, (err: Error, result: Buffer) => result)); -const gunzipped: Buffer = zlib.gunzipSync(zlib.gzipSync(compressMe)); - -zlib.unzip(compressMe, (err: Error, result: Buffer) => result); -const unzipped: Buffer = zlib.unzipSync(compressMe); - -// Simplified constructors -function simplified_stream_ctor_test() { - new stream.Readable({ - read: function(size) { - size.toFixed(); - } - }); - - new stream.Writable({ - write: function(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb() - }, - writev: function(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); - } - }); - - new stream.Duplex({ - read: function(size) { - size.toFixed(); - }, - write: function(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb() - }, - writev: function(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); - }, - readableObjectMode: true, - writableObjectMode: true - }); - - new stream.Transform({ - transform: function(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); - }, - flush: function(cb) { - cb() - }, - read: function(size) { - size.toFixed(); - }, - write: function(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb() - }, - writev: function(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); - }, - allowHalfOpen: true, - readableObjectMode: true, - writableObjectMode: true - }) -} - -// Subclassing stream classes -{ - class SubclassedReadable extends stream.Readable {}; - - let subclassedReadable: SubclassedReadable = new SubclassedReadable(); - subclassedReadable = subclassedReadable.pause(); - subclassedReadable = subclassedReadable.resume(); - - class SubclassedTransform extends stream.Transform {}; - - let subclassedTransform: SubclassedTransform = new SubclassedTransform(); - subclassedTransform = subclassedTransform.pause(); - subclassedTransform = subclassedTransform.resume(); - - class SubclassedDuplex extends stream.Duplex {}; - - let subclassedDuplex: SubclassedDuplex = new SubclassedDuplex(); - subclassedDuplex = subclassedDuplex.pause(); - subclassedDuplex = subclassedDuplex.resume(); - - // assignability - let readable: stream.Readable = subclassedDuplex; - readable = subclassedTransform; - let duplex: stream.Duplex = subclassedTransform; -} - -//////////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html /// -//////////////////////////////////////////////////////// - -namespace crypto_tests { - { - var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); - } - - { - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer | string = hmac.read(); - }); - } - - { - //crypto_cipher_decipher_string_test - let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - let clearText: string = "This is the clear text."; - let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - let cipherText: string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); - - let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - let clearText2: string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); - - assert.equal(clearText2, clearText); - } - - { - //crypto_cipher_decipher_buffer_test - let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - let cipherBuffers: Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); - - let cipherText: Buffer = Buffer.concat(cipherBuffers); - - let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - let decipherBuffers: Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - let clearText2: Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); - } - - { - let buffer1: Buffer = new Buffer([1, 2, 3, 4, 5]); - let buffer2: Buffer = new Buffer([1, 2, 3, 4, 5]); - let buffer3: Buffer = new Buffer([5, 4, 3, 2, 1]); - - assert(crypto.timingSafeEqual(buffer1, buffer2)) - assert(!crypto.timingSafeEqual(buffer1, buffer3)) - } -} - -////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html /// -////////////////////////////////////////////////// - -namespace tls_tests { - { - var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", - }); - var blah = ctx.context; - - var connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 - }; - var tlsSocket = tls.connect(connOpts); - } - - { - let _server: tls.Server; - let _boolean: boolean; - let _func1 = function(err: Error, resp: Buffer){}; - let _func2 = function(err: Error, sessionData: any){}; - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - **/ - - _server = _server.addListener("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - _server = _server.addListener("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }) - _server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }) - _server = _server.addListener("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }) - _server = _server.addListener("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - - let _err: Error; - let _tlsSocket: tls.TLSSocket; - let _any: any; - let _func: Function; - let _buffer: Buffer; - _boolean = _server.emit("tlsClientError", _err, _tlsSocket); - _boolean = _server.emit("newSession", _any, _any, _func1); - _boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func); - _boolean = _server.emit("resumeSession", _any, _func2); - _boolean = _server.emit("secureConnection", _tlsSocket); - - _server = _server.on("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - _server = _server.on("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }) - _server = _server.on("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }) - _server = _server.on("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }) - _server = _server.on("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - - _server = _server.once("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - _server = _server.once("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }) - _server = _server.once("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }) - _server = _server.once("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }) - _server = _server.once("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - - _server = _server.prependListener("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - _server = _server.prependListener("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }) - _server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }) - _server = _server.prependListener("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }) - _server = _server.prependListener("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - - _server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - _server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }) - _server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }) - _server = _server.prependOnceListener("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }) - _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - - // close callback parameter is optional - _server = _server.close(); - - // close callback parameter doesn't specify any arguments, so any - // function is acceptable - _server = _server.close(() => {}); - _server = _server.close((...args:any[]) => {}); - } - - { - let _TLSSocket: tls.TLSSocket; - let _boolean: boolean; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - **/ - - _TLSSocket = _TLSSocket.addListener("OCSPResponse", (response) => { - let _response: Buffer = response; - }) - _TLSSocket = _TLSSocket.addListener("secureConnect", () => { }); - - let _buffer: Buffer; - _boolean = _TLSSocket.emit("OCSPResponse", _buffer); - _boolean = _TLSSocket.emit("secureConnect"); - - _TLSSocket = _TLSSocket.on("OCSPResponse", (response) => { - let _response: Buffer = response; - }) - _TLSSocket = _TLSSocket.on("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.once("OCSPResponse", (response) => { - let _response: Buffer = response; - }) - _TLSSocket = _TLSSocket.once("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependListener("OCSPResponse", (response) => { - let _response: Buffer = response; - }) - _TLSSocket = _TLSSocket.prependListener("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependOnceListener("OCSPResponse", (response) => { - let _response: Buffer = response; - }) - _TLSSocket = _TLSSocket.prependOnceListener("secureConnect", () => { }); - } -} - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html /// -//////////////////////////////////////////////////// - -namespace http_tests { - { - // Status codes - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; - } - - { - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); - - var agent: http.Agent = http.globalAgent; - - http.request({ agent: false }); - http.request({ agent: agent }); - http.request({ agent: undefined }); - } - - { - http.request('http://www.example.com/xyz'); - } - - { - // Make sure .listen() and .close() retuern a Server instance - http.createServer().listen(0).close().address(); - net.createServer().listen(0).close().address(); - } - - { - var request = http.request({ path: 'http://0.0.0.0' }); - request.once('error', function() { }); - request.setNoDelay(true); - request.abort(); - } - - // http request options - { - const requestOpts: http.RequestOptions = { - timeout: 30000 - }; - - const clientArgs: http.ClientRequestArgs = { - timeout: 30000 - }; - } - - // http headers - { - const headers: http.IncomingHttpHeaders = { - 'content-type': 'application/json', - 'set-cookie': [ 'type=ninja', 'language=javascript' ] - }; - } -} - -////////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html /// -////////////////////////////////////////////////////// - -namespace https_tests { - var agent: https.Agent = new https.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256, - maxCachedSessions: 100 - }); - - var agent: https.Agent = https.globalAgent; - - https.request({ - agent: false - }); - https.request({ - agent: agent - }); - https.request({ - agent: undefined - }); - - https.request('http://www.example.com/xyz'); - - https.globalAgent.options.ca = []; -} - -//////////////////////////////////////////////////// -/// TTY tests : http://nodejs.org/api/tty.html -//////////////////////////////////////////////////// - -namespace tty_tests { - let rs: tty.ReadStream; - let ws: tty.WriteStream; - - let rsIsRaw: boolean = rs.isRaw; - rs.setRawMode(true); - - let wsColumns: number = ws.columns; - let wsRows: number = ws.rows; - - let isTTY: boolean = tty.isatty(1); -} - -//////////////////////////////////////////////////// -/// Dgram tests : http://nodejs.org/api/dgram.html -//////////////////////////////////////////////////// - -namespace dgram_tests { - { - var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { - }); - ds.bind(); - ds.bind(41234); - var ai: dgram.AddressInfo = ds.address(); - ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { - }); - ds.send(new Buffer("hello"), 5000, "127.0.0.1"); - } - - { - let _socket: dgram.Socket; - let _boolean: boolean; - let _err: Error; - let _str: string; - let _rinfo: dgram.AddressInfo; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - **/ - - _socket = _socket.addListener("close", () => {}); - _socket = _socket.addListener("error", (err) => { - let _err: Error = err; - }) - _socket = _socket.addListener("listening", () => {}); - _socket = _socket.addListener("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }) - - _boolean = _socket.emit("close") - _boolean = _socket.emit("error", _err); - _boolean = _socket.emit("listening"); - _boolean = _socket.emit("message", _str, _rinfo); - - _socket = _socket.on("close", () => {}); - _socket = _socket.on("error", (err) => { - let _err: Error = err; - }) - _socket = _socket.on("listening", () => {}); - _socket = _socket.on("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }) - - _socket = _socket.once("close", () => {}); - _socket = _socket.once("error", (err) => { - let _err: Error = err; - }) - _socket = _socket.once("listening", () => {}); - _socket = _socket.once("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }) - - _socket = _socket.prependListener("close", () => {}); - _socket = _socket.prependListener("error", (err) => { - let _err: Error = err; - }) - _socket = _socket.prependListener("listening", () => {}); - _socket = _socket.prependListener("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }) - - _socket = _socket.prependOnceListener("close", () => {}); - _socket = _socket.prependOnceListener("error", (err) => { - let _err: Error = err; - }) - _socket = _socket.prependOnceListener("listening", () => {}); - _socket = _socket.prependOnceListener("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }) - } -} - -//////////////////////////////////////////////////// -///Querystring tests : https://nodejs.org/api/querystring.html -//////////////////////////////////////////////////// - -namespace querystring_tests { - type SampleObject = { a: string; b: number; } - - { - let obj: SampleObject; - let sep: string; - let eq: string; - let options: querystring.StringifyOptions; - let result: string; - - result = querystring.stringify(obj); - result = querystring.stringify(obj, sep); - result = querystring.stringify(obj, sep, eq); - result = querystring.stringify(obj, sep, eq); - result = querystring.stringify(obj, sep, eq, options); - } - - { - let str: string; - let sep: string; - let eq: string; - let options: querystring.ParseOptions; - let result: SampleObject; - - result = querystring.parse(str); - result = querystring.parse(str, sep); - result = querystring.parse(str, sep, eq); - result = querystring.parse(str, sep, eq, options); - } - - { - let str: string; - let result: string; - - result = querystring.escape(str); - result = querystring.unescape(str); - } -} - -//////////////////////////////////////////////////// -/// path tests : http://nodejs.org/api/path.html -//////////////////////////////////////////////////// - -namespace path_tests { - - path.normalize('/foo/bar//baz/asdf/quux/..'); - - path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); - // returns - //'/foo/bar/baz/asdf' - - try { - path.join('foo', 'bar'); - } - catch (error) { - - } - - path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile'); - //Is similar to: - // - //cd foo/bar - //cd /tmp/file/ - //cd .. - // cd a/../subfile - //pwd - - path.resolve('/foo/bar', './baz') - // returns - // '/foo/bar/baz' - - path.resolve('/foo/bar', '/tmp/file/') - // returns - // '/tmp/file' - - path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif') - // if currently in /home/myself/node, it returns - // '/home/myself/node/wwwroot/static_files/gif/image.gif' - - path.isAbsolute('/foo/bar') // true - path.isAbsolute('/baz/..') // true - path.isAbsolute('qux/') // false - path.isAbsolute('.') // false - - path.isAbsolute('//server') // true - path.isAbsolute('C:/foo/..') // true - path.isAbsolute('bar\\baz') // false - path.isAbsolute('.') // false - - path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb') - // returns - // '..\\..\\impl\\bbb' - - path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') - // returns - // '../../impl/bbb' - - path.dirname('/foo/bar/baz/asdf/quux') - // returns - // '/foo/bar/baz/asdf' - - path.basename('/foo/bar/baz/asdf/quux.html') - // returns - // 'quux.html' - - path.basename('/foo/bar/baz/asdf/quux.html', '.html') - // returns - // 'quux' - - path.extname('index.html') - // returns - // '.html' - - path.extname('index.coffee.md') - // returns - // '.md' - - path.extname('index.') - // returns - // '.' - - path.extname('index') - // returns - // '' - - 'foo/bar/baz'.split(path.sep) - // returns - // ['foo', 'bar', 'baz'] - - 'foo\\bar\\baz'.split(path.sep) - // returns - // ['foo', 'bar', 'baz'] - - process.env["PATH"]; // $ExpectType string - - path.parse('/home/user/dir/file.txt') - // returns - // { - // root : "/", - // dir : "/home/user/dir", - // base : "file.txt", - // ext : ".txt", - // name : "file" - // } - - path.parse('C:\\path\\dir\\index.html') - // returns - // { - // root : "C:\", - // dir : "C:\path\dir", - // base : "index.html", - // ext : ".html", - // name : "index" - // } - - path.format({ - root: "/", - dir: "/home/user/dir", - base: "file.txt", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - - path.format({ - dir: "/home/user/dir", - base: "file.txt" - }); - // returns - // '/home/user/dir/file.txt' - - path.posix.format({ - root: "/", - dir: "/home/user/dir", - base: "file.txt", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - path.posix.format({ - dir: "/home/user/dir", - base: "file.txt" - }); - // returns - // '/home/user/dir/file.txt' - - path.win32.format({ - root: "C:\\", - dir: "C:\\home\\user\\dir", - ext: ".txt", - name: "file" - }); - // returns - // 'C:\home\user\dir\file.txt' - - path.win32.format({ - dir: "C:\\home\\user\\dir", - base: "file.txt" - }); - // returns - // 'C:\home\user\dir\file.txt' -} - -//////////////////////////////////////////////////// -/// readline tests : https://nodejs.org/api/readline.html -//////////////////////////////////////////////////// - -namespace readline_tests { - let rl: readline.ReadLine; - - { - let options: readline.ReadLineOptions; - let input: NodeJS.ReadableStream; - let output: NodeJS.WritableStream; - let completer: readline.Completer; - let terminal: boolean; - - let result: readline.ReadLine; - - result = readline.createInterface(options); - result = readline.createInterface(input); - result = readline.createInterface(input, output); - result = readline.createInterface(input, output, completer); - result = readline.createInterface(input, output, completer, terminal); - result = readline.createInterface({ - input: input, - completer: function(str: string): readline.CompleterResult { - return [['test'], 'test']; - } - }); - } - - { - let prompt: string; - - rl.setPrompt(prompt); - } - - { - let preserveCursor: boolean; - - rl.prompt(); - rl.prompt(preserveCursor); - } - - { - let query: string; - let callback: (answer: string) => void; - - rl.question(query, callback); - } - - { - let result: readline.ReadLine; - - result = rl.pause(); - } - - { - let result: readline.ReadLine; - - result = rl.resume(); - } - - { - rl.close(); - } - - { - let data: string | Buffer; - let key: readline.Key; - - rl.write(data); - rl.write(null, key); - } - - { - let stream: NodeJS.WritableStream; - let x: number; - let y: number; - - readline.cursorTo(stream, x, y); - } - - { - let stream: NodeJS.WritableStream; - let dx: number | string; - let dy: number | string; - - readline.moveCursor(stream, dx, dy); - } - - { - let stream: NodeJS.WritableStream; - let dir: number; - - readline.clearLine(stream, dir); - } - - { - let stream: NodeJS.WritableStream; - - readline.clearScreenDown(stream); - } - - { - let _rl: readline.ReadLine; - let _boolean: boolean; - - _rl = _rl.addListener("close", () => { }); - _rl = _rl.addListener("line", (input) => { - let _input: any = input; - }) - _rl = _rl.addListener("pause", () => { }); - _rl = _rl.addListener("resume", () => { }); - _rl = _rl.addListener("SIGCONT", () => { }); - _rl = _rl.addListener("SIGINT", () => { }); - _rl = _rl.addListener("SIGTSTP", () => { }); - - _boolean = _rl.emit("close", () => { }); - _boolean = _rl.emit("line", () => { }); - _boolean = _rl.emit("pause", () => { }); - _boolean = _rl.emit("resume", () => { }); - _boolean = _rl.emit("SIGCONT", () => { }); - _boolean = _rl.emit("SIGINT", () => { }); - _boolean = _rl.emit("SIGTSTP", () => { }); - - _rl = _rl.on("close", () => { }); - _rl = _rl.on("line", (input) => { - let _input: any = input; - }) - _rl = _rl.on("pause", () => { }); - _rl = _rl.on("resume", () => { }); - _rl = _rl.on("SIGCONT", () => { }); - _rl = _rl.on("SIGINT", () => { }); - _rl = _rl.on("SIGTSTP", () => { }); - - _rl = _rl.once("close", () => { }); - _rl = _rl.once("line", (input) => { - let _input: any = input; - }) - _rl = _rl.once("pause", () => { }); - _rl = _rl.once("resume", () => { }); - _rl = _rl.once("SIGCONT", () => { }); - _rl = _rl.once("SIGINT", () => { }); - _rl = _rl.once("SIGTSTP", () => { }); - - _rl = _rl.prependListener("close", () => { }); - _rl = _rl.prependListener("line", (input) => { - let _input: any = input; - }) - _rl = _rl.prependListener("pause", () => { }); - _rl = _rl.prependListener("resume", () => { }); - _rl = _rl.prependListener("SIGCONT", () => { }); - _rl = _rl.prependListener("SIGINT", () => { }); - _rl = _rl.prependListener("SIGTSTP", () => { }); - - _rl = _rl.prependOnceListener("close", () => { }); - _rl = _rl.prependOnceListener("line", (input) => { - let _input: any = input; - }) - _rl = _rl.prependOnceListener("pause", () => { }); - _rl = _rl.prependOnceListener("resume", () => { }); - _rl = _rl.prependOnceListener("SIGCONT", () => { }); - _rl = _rl.prependOnceListener("SIGINT", () => { }); - _rl = _rl.prependOnceListener("SIGTSTP", () => { }); - } -} - -//////////////////////////////////////////////////// -/// string_decoder tests : https://nodejs.org/api/string_decoder.html -//////////////////////////////////////////////////// - -namespace string_decoder_tests { - const StringDecoder = string_decoder.StringDecoder; - const buffer = new Buffer('test'); - const decoder1 = new StringDecoder(); - const decoder2 = new StringDecoder('utf8'); - const part1: string = decoder1.write(new Buffer('test')); - const end1: string = decoder1.end(); - const part2: string = decoder2.write(new Buffer('test')); - const end2: string = decoder1.end(new Buffer('test')); -} - -////////////////////////////////////////////////////////////////////// -/// Child Process tests: https://nodejs.org/api/child_process.html /// -////////////////////////////////////////////////////////////////////// - -namespace child_process_tests { - { - childProcess.exec("echo test"); - childProcess.spawnSync("echo test"); - } - - { - let _cp: childProcess.ChildProcess; - let _boolean: boolean; - - _cp = _cp.addListener("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.addListener("disconnect", () => { }); - _cp = _cp.addListener("error", (err) => { - let _err: Error = err; - }) - _cp = _cp.addListener("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.addListener("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }) - - _boolean = _cp.emit("close", () => { }); - _boolean = _cp.emit("disconnect", () => { }); - _boolean = _cp.emit("error", () => { }); - _boolean = _cp.emit("exit", () => { }); - _boolean = _cp.emit("message", () => { }); - - _cp = _cp.on("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.on("disconnect", () => { }); - _cp = _cp.on("error", (err) => { - let _err: Error = err; - }) - _cp = _cp.on("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.on("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }) - - _cp = _cp.once("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.once("disconnect", () => { }); - _cp = _cp.once("error", (err) => { - let _err: Error = err; - }) - _cp = _cp.once("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.once("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }) - - _cp = _cp.prependListener("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.prependListener("disconnect", () => { }); - _cp = _cp.prependListener("error", (err) => { - let _err: Error = err; - }) - _cp = _cp.prependListener("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.prependListener("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }) - - _cp = _cp.prependOnceListener("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.prependOnceListener("disconnect", () => { }); - _cp = _cp.prependOnceListener("error", (err) => { - let _err: Error = err; - }) - _cp = _cp.prependOnceListener("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.prependOnceListener("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }) - } -} - -////////////////////////////////////////////////////////////////////// -/// cluster tests: https://nodejs.org/api/cluster.html /// -////////////////////////////////////////////////////////////////////// - -namespace cluster_tests { - { - cluster.fork(); - Object.keys(cluster.workers).forEach(key => { - const worker = cluster.workers[key]; - if (worker.isDead()) { - console.log('worker %d is dead', worker.process.pid); - } - }); - } -} - -//////////////////////////////////////////////////// -/// os tests : https://nodejs.org/api/os.html -//////////////////////////////////////////////////// - -namespace os_tests { - { - let result: string; - - result = os.tmpdir(); - result = os.homedir(); - result = os.endianness(); - result = os.hostname(); - result = os.type(); - result = os.platform(); - result = os.arch(); - result = os.release(); - result = os.EOL; - } - - { - let result: number; - - result = os.uptime(); - result = os.totalmem(); - result = os.freemem(); - } - - { - let result: number[]; - - result = os.loadavg(); - } - - { - let result: os.CpuInfo[]; - - result = os.cpus(); - } - - { - let result: { [index: string]: os.NetworkInterfaceInfo[] }; - - result = os.networkInterfaces(); - } - - { - let result: number; - - result = os.constants.signals.SIGHUP; - result = os.constants.signals.SIGINT; - result = os.constants.signals.SIGQUIT; - result = os.constants.signals.SIGILL; - result = os.constants.signals.SIGTRAP; - result = os.constants.signals.SIGABRT; - result = os.constants.signals.SIGIOT; - result = os.constants.signals.SIGBUS; - result = os.constants.signals.SIGFPE; - result = os.constants.signals.SIGKILL; - result = os.constants.signals.SIGUSR1; - result = os.constants.signals.SIGSEGV; - result = os.constants.signals.SIGUSR2; - result = os.constants.signals.SIGPIPE; - result = os.constants.signals.SIGALRM; - result = os.constants.signals.SIGTERM; - result = os.constants.signals.SIGCHLD; - result = os.constants.signals.SIGSTKFLT; - result = os.constants.signals.SIGCONT; - result = os.constants.signals.SIGSTOP; - result = os.constants.signals.SIGTSTP; - result = os.constants.signals.SIGTTIN; - result = os.constants.signals.SIGTTOU; - result = os.constants.signals.SIGURG; - result = os.constants.signals.SIGXCPU; - result = os.constants.signals.SIGXFSZ; - result = os.constants.signals.SIGVTALRM; - result = os.constants.signals.SIGPROF; - result = os.constants.signals.SIGWINCH; - result = os.constants.signals.SIGIO; - result = os.constants.signals.SIGPOLL; - result = os.constants.signals.SIGPWR; - result = os.constants.signals.SIGSYS; - result = os.constants.signals.SIGUNUSED; - } - - { - let result: number; - - result = os.constants.errno.E2BIG; - result = os.constants.errno.EACCES; - result = os.constants.errno.EADDRINUSE; - result = os.constants.errno.EADDRNOTAVAIL; - result = os.constants.errno.EAFNOSUPPORT; - result = os.constants.errno.EAGAIN; - result = os.constants.errno.EALREADY; - result = os.constants.errno.EBADF; - result = os.constants.errno.EBADMSG; - result = os.constants.errno.EBUSY; - result = os.constants.errno.ECANCELED; - result = os.constants.errno.ECHILD; - result = os.constants.errno.ECONNABORTED; - result = os.constants.errno.ECONNREFUSED; - result = os.constants.errno.ECONNRESET; - result = os.constants.errno.EDEADLK; - result = os.constants.errno.EDESTADDRREQ; - result = os.constants.errno.EDOM; - result = os.constants.errno.EDQUOT; - result = os.constants.errno.EEXIST; - result = os.constants.errno.EFAULT; - result = os.constants.errno.EFBIG; - result = os.constants.errno.EHOSTUNREACH; - result = os.constants.errno.EIDRM; - result = os.constants.errno.EILSEQ; - result = os.constants.errno.EINPROGRESS; - result = os.constants.errno.EINTR; - result = os.constants.errno.EINVAL; - result = os.constants.errno.EIO; - result = os.constants.errno.EISCONN; - result = os.constants.errno.EISDIR; - result = os.constants.errno.ELOOP; - result = os.constants.errno.EMFILE; - result = os.constants.errno.EMLINK; - result = os.constants.errno.EMSGSIZE; - result = os.constants.errno.EMULTIHOP; - result = os.constants.errno.ENAMETOOLONG; - result = os.constants.errno.ENETDOWN; - result = os.constants.errno.ENETRESET; - result = os.constants.errno.ENETUNREACH; - result = os.constants.errno.ENFILE; - result = os.constants.errno.ENOBUFS; - result = os.constants.errno.ENODATA; - result = os.constants.errno.ENODEV; - result = os.constants.errno.ENOENT; - result = os.constants.errno.ENOEXEC; - result = os.constants.errno.ENOLCK; - result = os.constants.errno.ENOLINK; - result = os.constants.errno.ENOMEM; - result = os.constants.errno.ENOMSG; - result = os.constants.errno.ENOPROTOOPT; - result = os.constants.errno.ENOSPC; - result = os.constants.errno.ENOSR; - result = os.constants.errno.ENOSTR; - result = os.constants.errno.ENOSYS; - result = os.constants.errno.ENOTCONN; - result = os.constants.errno.ENOTDIR; - result = os.constants.errno.ENOTEMPTY; - result = os.constants.errno.ENOTSOCK; - result = os.constants.errno.ENOTSUP; - result = os.constants.errno.ENOTTY; - result = os.constants.errno.ENXIO; - result = os.constants.errno.EOPNOTSUPP; - result = os.constants.errno.EOVERFLOW; - result = os.constants.errno.EPERM; - result = os.constants.errno.EPIPE; - result = os.constants.errno.EPROTO; - result = os.constants.errno.EPROTONOSUPPORT; - result = os.constants.errno.EPROTOTYPE; - result = os.constants.errno.ERANGE; - result = os.constants.errno.EROFS; - result = os.constants.errno.ESPIPE; - result = os.constants.errno.ESRCH; - result = os.constants.errno.ESTALE; - result = os.constants.errno.ETIME; - result = os.constants.errno.ETIMEDOUT; - result = os.constants.errno.ETXTBSY; - result = os.constants.errno.EWOULDBLOCK; - result = os.constants.errno.EXDEV; - } -} - -//////////////////////////////////////////////////// -/// vm tests : https://nodejs.org/api/vm.html -//////////////////////////////////////////////////// - -namespace vm_tests { - { - const sandbox = { - animal: 'cat', - count: 2 - }; - - const context = vm.createContext(sandbox); - console.log(vm.isContext(context)); - const script = new vm.Script('count += 1; name = "kitty"'); - - for (let i = 0; i < 10; ++i) { - script.runInContext(context); - } - - console.log(util.inspect(sandbox)); - - vm.runInNewContext('count += 1; name = "kitty"', sandbox); - console.log(util.inspect(sandbox)); - } - - { - const sandboxes = [{}, {}, {}]; - - const script = new vm.Script('globalVar = "set"'); - - sandboxes.forEach((sandbox) => { - script.runInNewContext(sandbox); - script.runInThisContext(); - }); - - console.log(util.inspect(sandboxes)); - - var localVar = 'initial value'; - vm.runInThisContext('localVar = "vm";'); - - console.log(localVar); - } - - { - const Debug = vm.runInDebugContext('Debug'); - Debug.scripts().forEach(function(script: any) { console.log(script.name); }); - } -} - -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - -namespace timers_tests { - { - let immediateId = timers.setImmediate(function() { console.log("immediate"); }); - timers.clearImmediate(immediateId); - } - { - let counter = 0; - let timeout = timers.setInterval(function() { console.log("interval"); }, 20); - timeout.unref(); - timeout.ref(); - timers.clearInterval(timeout); - } - { - let counter = 0; - let timeout = timers.setTimeout(function() { console.log("timeout"); }, 20); - timeout.unref(); - timeout.ref(); - timers.clearTimeout(timeout); - } -} - -///////////////////////////////////////////////////////// -/// Errors Tests : https://nodejs.org/api/errors.html /// -///////////////////////////////////////////////////////// - -namespace errors_tests { - { - Error.stackTraceLimit = Infinity; - } - { - const myObject = {}; - Error.captureStackTrace(myObject); - } - { - let frames: NodeJS.CallSite[] = []; - Error.prepareStackTrace(new Error(), frames); - } - { - let frame: NodeJS.CallSite = null; - let frameThis: any = frame.getThis(); - let typeName: string = frame.getTypeName(); - let func: Function = frame.getFunction(); - let funcName: string = frame.getFunctionName(); - let meth: string = frame.getMethodName(); - let fname: string = frame.getFileName(); - let lineno: number = frame.getLineNumber(); - let colno: number = frame.getColumnNumber(); - let evalOrigin: string = frame.getEvalOrigin(); - let isTop: boolean = frame.isToplevel(); - let isEval: boolean = frame.isEval(); - let isNative: boolean = frame.isNative(); - let isConstr: boolean = frame.isConstructor(); - } -} - -/////////////////////////////////////////////////////////// -/// Process Tests : https://nodejs.org/api/process.html /// -/////////////////////////////////////////////////////////// - -import * as p from "process"; -namespace process_tests { - { - var eventEmitter: events.EventEmitter; - eventEmitter = process; // Test that process implements EventEmitter... - - var _p: NodeJS.Process = process; - _p = p; - } - { - assert(process.argv[0] === process.argv0); - } - { - var module: NodeModule | undefined; - module = process.mainModule; - } -} - -/////////////////////////////////////////////////////////// -/// Console Tests : https://nodejs.org/api/console.html /// -/////////////////////////////////////////////////////////// - -import * as c from "console"; -namespace console_tests { - { - var _c: Console = console; - _c = c; - } -} - -/////////////////////////////////////////////////// -/// Net Tests : https://nodejs.org/api/net.html /// -/////////////////////////////////////////////////// - -namespace net_tests { - { - let server = net.createServer(); - // Check methods which return server instances by chaining calls - server = server.listen(0) - .close() - .ref() - .unref(); - - // close has an optional callback function. No callback parameters are - // specified, so any callback function is permissible. - server = server.close((...args: any[]) => {}); - - // test the types of the address object fields - let address = server.address(); - address.port = 1234; - address.family = "ipv4"; - address.address = "127.0.0.1"; - } - - { - /** - * net.Socket - events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout - */ - let _socket: net.Socket = new net.Socket({ - fd: 1, - allowHalfOpen: false, - readable: false, - writable: false - }); - - let bool: boolean; - let buffer: Buffer; - let error: Error; - let str: string; - let num: number; - - /// addListener - - _socket = _socket.addListener("close", had_error => { - bool = had_error; - }) - _socket = _socket.addListener("connect", () => { }) - _socket = _socket.addListener("data", data => { - buffer = data; - }) - _socket = _socket.addListener("drain", () => { }) - _socket = _socket.addListener("end", () => { }) - _socket = _socket.addListener("error", err => { - error = err; - }) - _socket = _socket.addListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }) - _socket = _socket.addListener("timeout", () => { }) - - /// emit - bool = _socket.emit("close", bool); - bool = _socket.emit("connect"); - bool = _socket.emit("data", buffer); - bool = _socket.emit("drain"); - bool = _socket.emit("end"); - bool = _socket.emit("error", error); - bool = _socket.emit("lookup", error, str, str, str); - bool = _socket.emit("lookup", error, str, num, str); - bool = _socket.emit("timeout"); - - /// on - _socket = _socket.on("close", had_error => { - bool = had_error; - }) - _socket = _socket.on("connect", () => { }) - _socket = _socket.on("data", data => { - buffer = data; - }) - _socket = _socket.on("drain", () => { }) - _socket = _socket.on("end", () => { }) - _socket = _socket.on("error", err => { - error = err; - }) - _socket = _socket.on("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }) - _socket = _socket.on("timeout", () => { }) - - /// once - _socket = _socket.once("close", had_error => { - bool = had_error; - }) - _socket = _socket.once("connect", () => { }) - _socket = _socket.once("data", data => { - buffer = data; - }) - _socket = _socket.once("drain", () => { }) - _socket = _socket.once("end", () => { }) - _socket = _socket.once("error", err => { - error = err; - }) - _socket = _socket.once("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }) - _socket = _socket.once("timeout", () => { }) - - /// prependListener - _socket = _socket.prependListener("close", had_error => { - bool = had_error; - }) - _socket = _socket.prependListener("connect", () => { }) - _socket = _socket.prependListener("data", data => { - buffer = data; - }) - _socket = _socket.prependListener("drain", () => { }) - _socket = _socket.prependListener("end", () => { }) - _socket = _socket.prependListener("error", err => { - error = err; - }) - _socket = _socket.prependListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }) - _socket = _socket.prependListener("timeout", () => { }) - - /// prependOnceListener - _socket = _socket.prependOnceListener("close", had_error => { - bool = had_error; - }) - _socket = _socket.prependOnceListener("connect", () => { }) - _socket = _socket.prependOnceListener("data", data => { - buffer = data; - }) - _socket = _socket.prependOnceListener("drain", () => { }) - _socket = _socket.prependOnceListener("end", () => { }) - _socket = _socket.prependOnceListener("error", err => { - error = err; - }) - _socket = _socket.prependOnceListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }) - _socket = _socket.prependOnceListener("timeout", () => { }) - - bool = _socket.connecting; - bool = _socket.destroyed; - _socket.destroy(); - } - - { - /** - * net.Server - events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - */ - let _server: net.Server; - - let _socket: net.Socket; - let bool: boolean; - let error: Error; - - /// addListener - _server = _server.addListener("close", () => { }) - _server = _server.addListener("connection", socket => { - _socket = socket - }) - _server = _server.addListener("error", err => { - error = err; - }) - _server = _server.addListener("listening", () => { }) - - /// emit - bool = _server.emit("close") - bool = _server.emit("connection", _socket) - bool = _server.emit("error", error) - bool = _server.emit("listening") - - /// once - _server = _server.once("close", () => { }) - _server = _server.once("connection", socket => { - _socket = socket - }) - _server = _server.once("error", err => { - error = err; - }) - _server = _server.once("listening", () => { }) - - /// prependListener - _server = _server.prependListener("close", () => { }) - _server = _server.prependListener("connection", socket => { - _socket = socket - }) - _server = _server.prependListener("error", err => { - error = err; - }) - _server = _server.prependListener("listening", () => { }) - - /// prependOnceListener - _server = _server.prependOnceListener("close", () => { }) - _server = _server.prependOnceListener("connection", socket => { - _socket = socket - }) - _server = _server.prependOnceListener("error", err => { - error = err; - }) - _server = _server.prependOnceListener("listening", () => { }) - - } - -} - -///////////////////////////////////////////////////// -/// repl Tests : https://nodejs.org/api/repl.html /// -///////////////////////////////////////////////////// - -namespace repl_tests { - { - let _server: repl.REPLServer; - let _boolean: boolean; - let _ctx: any; - - _server = _server.addListener("exit", () => { }); - _server = _server.addListener("reset", () => { }); - - _boolean = _server.emit("exit", () => { }); - _boolean = _server.emit("reset", _ctx); - - _server = _server.on("exit", () => { }); - _server = _server.on("reset", () => { }); - - _server = _server.once("exit", () => { }); - _server = _server.once("reset", () => { }); - - _server = _server.prependListener("exit", () => { }); - _server = _server.prependListener("reset", () => { }); - - _server = _server.prependOnceListener("exit", () => { }); - _server = _server.prependOnceListener("reset", () => { }); - } -} - -/////////////////////////////////////////////////// -/// DNS Tests : https://nodejs.org/api/dns.html /// -/////////////////////////////////////////////////// - -namespace dns_tests { - dns.lookup("nodejs.org", (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 4, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 6, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", {}, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup( - "nodejs.org", - { - family: 4, - hints: dns.ADDRCONFIG | dns.V4MAPPED, - all: false - }, - (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - } - ); - dns.lookup("nodejs.org", {all: true}, (err, addresses) => { - const _err: NodeJS.ErrnoException = err; - const _address: dns.LookupAddress[] = addresses; - }); - - function trueOrFalse(): boolean { - return Math.random() > 0.5 ? true : false; - } - dns.lookup("nodejs.org", {all: trueOrFalse()}, (err, addresses, family) => { - const _err: NodeJS.ErrnoException = err; - const _addresses: string | dns.LookupAddress[] = addresses; - const _family: number | undefined = family; - }); - - dns.lookupService("127.0.0.1", 0, (err, hostname, service) => { - const _err: NodeJS.ErrnoException = err; - const _hostname: string = hostname; - const _service: string = service; - }); - - dns.resolve("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "A", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "AAAA", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "MX", (err, addresses) => { - const _addresses: dns.MxRecord[] = addresses; - }); - - dns.resolve4("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - - dns.resolve6("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); -} - -/***************************************************************************** - * * - * The following tests are the modules not mentioned in document but existed * - * * - *****************************************************************************/ - -/////////////////////////////////////////////////////////// -/// Constants Tests /// -/////////////////////////////////////////////////////////// - -import * as constants from 'constants'; -namespace constants_tests { - var str: string; - var num: number; - num = constants.SIGHUP - num = constants.SIGINT - num = constants.SIGQUIT - num = constants.SIGILL - num = constants.SIGTRAP - num = constants.SIGABRT - num = constants.SIGIOT - num = constants.SIGBUS - num = constants.SIGFPE - num = constants.SIGKILL - num = constants.SIGUSR1 - num = constants.SIGSEGV - num = constants.SIGUSR2 - num = constants.SIGPIPE - num = constants.SIGALRM - num = constants.SIGTERM - num = constants.SIGCHLD - num = constants.SIGSTKFLT - num = constants.SIGCONT - num = constants.SIGSTOP - num = constants.SIGTSTP - num = constants.SIGTTIN - num = constants.SIGTTOU - num = constants.SIGURG - num = constants.SIGXCPU - num = constants.SIGXFSZ - num = constants.SIGVTALRM - num = constants.SIGPROF - num = constants.SIGWINCH - num = constants.SIGIO - num = constants.SIGPOLL - num = constants.SIGPWR - num = constants.SIGSYS - num = constants.SIGUNUSED - num = constants.O_RDONLY - num = constants.O_WRONLY - num = constants.O_RDWR - num = constants.S_IFMT - num = constants.S_IFREG - num = constants.S_IFDIR - num = constants.S_IFCHR - num = constants.S_IFBLK - num = constants.S_IFIFO - num = constants.S_IFLNK - num = constants.S_IFSOCK - num = constants.O_CREAT - num = constants.O_EXCL - num = constants.O_NOCTTY - num = constants.O_TRUNC - num = constants.O_APPEND - num = constants.O_DIRECTORY - num = constants.O_NOATIME - num = constants.O_NOFOLLOW - num = constants.O_SYNC - num = constants.O_DIRECT - num = constants.O_NONBLOCK - num = constants.S_IRWXU - num = constants.S_IRUSR - num = constants.S_IWUSR - num = constants.S_IXUSR - num = constants.S_IRWXG - num = constants.S_IRGRP - num = constants.S_IWGRP - num = constants.S_IXGRP - num = constants.S_IRWXO - num = constants.S_IROTH - num = constants.S_IWOTH - num = constants.S_IXOTH - num = constants.F_OK - num = constants.R_OK - num = constants.W_OK - num = constants.X_OK - num = constants.SSL_OP_ALL - num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION - num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE - num = constants.SSL_OP_CISCO_ANYCONNECT - num = constants.SSL_OP_COOKIE_EXCHANGE - num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG - num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS - num = constants.SSL_OP_EPHEMERAL_RSA - num = constants.SSL_OP_LEGACY_SERVER_CONNECT - num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER - num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG - num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING - num = constants.SSL_OP_NETSCAPE_CA_DN_BUG - num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG - num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG - num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG - num = constants.SSL_OP_NO_COMPRESSION - num = constants.SSL_OP_NO_QUERY_MTU - num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION - num = constants.SSL_OP_NO_SSLv2 - num = constants.SSL_OP_NO_SSLv3 - num = constants.SSL_OP_NO_TICKET - num = constants.SSL_OP_NO_TLSv1 - num = constants.SSL_OP_NO_TLSv1_1 - num = constants.SSL_OP_NO_TLSv1_2 - num = constants.SSL_OP_PKCS1_CHECK_1 - num = constants.SSL_OP_PKCS1_CHECK_2 - num = constants.SSL_OP_SINGLE_DH_USE - num = constants.SSL_OP_SINGLE_ECDH_USE - num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG - num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG - num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG - num = constants.SSL_OP_TLS_D5_BUG - num = constants.SSL_OP_TLS_ROLLBACK_BUG - num = constants.ENGINE_METHOD_RSA - num = constants.ENGINE_METHOD_DSA - num = constants.ENGINE_METHOD_DH - num = constants.ENGINE_METHOD_RAND - num = constants.ENGINE_METHOD_ECDH - num = constants.ENGINE_METHOD_ECDSA - num = constants.ENGINE_METHOD_CIPHERS - num = constants.ENGINE_METHOD_DIGESTS - num = constants.ENGINE_METHOD_STORE - num = constants.ENGINE_METHOD_PKEY_METHS - num = constants.ENGINE_METHOD_PKEY_ASN1_METHS - num = constants.ENGINE_METHOD_ALL - num = constants.ENGINE_METHOD_NONE - num = constants.DH_CHECK_P_NOT_SAFE_PRIME - num = constants.DH_CHECK_P_NOT_PRIME - num = constants.DH_UNABLE_TO_CHECK_GENERATOR - num = constants.DH_NOT_SUITABLE_GENERATOR - num = constants.NPN_ENABLED - num = constants.ALPN_ENABLED - num = constants.RSA_PKCS1_PADDING - num = constants.RSA_SSLV23_PADDING - num = constants.RSA_NO_PADDING - num = constants.RSA_PKCS1_OAEP_PADDING - num = constants.RSA_X931_PADDING - num = constants.RSA_PKCS1_PSS_PADDING - num = constants.POINT_CONVERSION_COMPRESSED - num = constants.POINT_CONVERSION_UNCOMPRESSED - num = constants.POINT_CONVERSION_HYBRID - str = constants.defaultCoreCipherList - str = constants.defaultCipherList -} - -/////////////////////////////////////////////////////////// -/// Debugger Tests /// -/////////////////////////////////////////////////////////// - -import { Client } from "_debugger"; - -var client = new Client(); - -client.connect(8888, 'localhost'); -client.listbreakpoints((err, body, packet) => { - -}); - -//////////////////////////////////////////////////// -/// zlib tests : http://nodejs.org/api/zlib.html /// -//////////////////////////////////////////////////// - -namespace zlib_tests { - { - const gzipped = zlib.gzipSync('test'); - const unzipped = zlib.gunzipSync(gzipped.toString()); - } - - { - const deflate = zlib.deflateSync('test'); - const inflate = zlib.inflateSync(deflate.toString()); - } -} diff --git a/types/node/v6/ts3.1/tsconfig.json b/types/node/v6/ts3.1/tsconfig.json deleted file mode 100644 index d904ce0a51..0000000000 --- a/types/node/v6/ts3.1/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "files": [ - "index.d.ts", - "node-tests.ts" - ], - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": true, - "baseUrl": "../../../", - "typeRoots": [ - "../../../" - ], - "paths": { - "node": [ - "node/v6" - ] - }, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - } -} diff --git a/types/node/v6/ts3.1/tslint.json b/types/node/v6/ts3.1/tslint.json deleted file mode 100644 index f862895f2b..0000000000 --- a/types/node/v6/ts3.1/tslint.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "align": false, - "array-type": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "import-spacing": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "no-consecutive-blank-lines": false, - "no-const-enum": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-namespace": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-string-throw": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-var-keyword": false, - "object-literal-shorthand": false, - "one-line": false, - "only-arrow-functions": false, - "prefer-const": false, - "prefer-method-signature": false, - "semicolon": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "typedef-whitespace": false, - "unified-signatures": false, - "whitespace": false - } -} diff --git a/types/node/v7/package.json b/types/node/v7/package.json deleted file mode 100644 index 54d5b8743e..0000000000 --- a/types/node/v7/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "private": true, - "types": "index", - "typesVersions": { - "<=3.1": { - "*": [ - "ts3.1/*" - ] - } - } -} diff --git a/types/node/v7/ts3.1/index.d.ts b/types/node/v7/ts3.1/index.d.ts deleted file mode 100644 index 69e58e726b..0000000000 --- a/types/node/v7/ts3.1/index.d.ts +++ /dev/null @@ -1,37 +0,0 @@ -/************************************************ -* * -* Node.js v7.x API * -* * -************************************************/ -// NOTE: These definitions support NodeJS and TypeScript 3.1. - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 - -// NOTE: Augmentations for TypeScript 3.1 and later should use individual files for overrides -// within the respective ~/ts3.1 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.1, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -// tslint:disable-next-line:no-bad-reference -/// - -// TypeScript 2.1-specific augmentations: - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } -interface IteratorResult {} -interface Iterable {} -interface Iterator { - next(value?: any): IteratorResult; -} -interface IterableIterator { } -interface SymbolConstructor { - readonly iterator: symbol; -} -declare var Symbol: SymbolConstructor; diff --git a/types/node/v7/ts3.1/node-tests.ts b/types/node/v7/ts3.1/node-tests.ts deleted file mode 100644 index 81c33d9658..0000000000 --- a/types/node/v7/ts3.1/node-tests.ts +++ /dev/null @@ -1,2639 +0,0 @@ -import assert = require("assert"); -import * as fs from "fs"; -import * as events from "events"; -import events2 = require("events"); -import * as zlib from "zlib"; -import * as url from "url"; -import * as util from "util"; -import * as crypto from "crypto"; -import * as tls from "tls"; -import * as http from "http"; -import * as https from "https"; -import * as net from "net"; -import * as tty from "tty"; -import * as dgram from "dgram"; -import * as querystring from "querystring"; -import * as path from "path"; -import * as readline from "readline"; -import * as childProcess from "child_process"; -import * as cluster from "cluster"; -import * as os from "os"; -import * as vm from "vm"; -import * as console2 from "console"; -import * as string_decoder from "string_decoder"; -import * as stream from "stream"; -import * as timers from "timers"; -import * as repl from "repl"; -import * as v8 from "v8"; -import * as dns from "dns"; - -// Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; - -////////////////////////////////////////////////////////// -/// Global Tests : https://nodejs.org/api/global.html /// -////////////////////////////////////////////////////////// -namespace global_tests { - { - let x: NodeModule; - let y: NodeModule; - x.children.push(y); - x.parent = require.main; - require.main = y; - } -} - -////////////////////////////////////////////////////////// -/// Assert Tests : https://nodejs.org/api/assert.html /// -////////////////////////////////////////////////////////// - -namespace assert_tests { - { - assert(1 + 1 - 2 === 0, "The universe isn't how it should."); - - assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - - assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); - - assert.doesNotThrow(() => { - const b = false; - if (b) { throw "a hammer at your face"; } - }, undefined, "What the...*crunch*"); - - assert.equal(3, "3", "uses == comparator"); - - assert.fail("actual", "expected", "message"); - - assert.fail(1, 2, undefined, '>'); - - assert.ifError(0); - - assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - - assert.notEqual(1, 2, "uses != comparator"); - - assert.notStrictEqual(2, "2", "uses === comparator"); - - assert.ok(true); - assert.ok(1); - - assert.strictEqual(1, 1, "uses === comparator"); - - assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); - } -} - -//////////////////////////////////////////////////// -/// Events tests : http://nodejs.org/api/events.html -//////////////////////////////////////////////////// - -namespace events_tests { - let emitter: events.EventEmitter; - let event: string | symbol; - let listener: Function; - let any: any; - - { - let result: events.EventEmitter; - - result = emitter.addListener(event, listener); - result = emitter.on(event, listener); - result = emitter.once(event, listener); - result = emitter.prependListener(event, listener); - result = emitter.prependOnceListener(event, listener); - result = emitter.removeListener(event, listener); - result = emitter.removeAllListeners(); - result = emitter.removeAllListeners(event); - result = emitter.setMaxListeners(42); - } - - { - let result: number; - - result = events.EventEmitter.defaultMaxListeners; - result = events.EventEmitter.listenerCount(emitter, event); // deprecated - - result = emitter.getMaxListeners(); - result = emitter.listenerCount(event); - } - - { - let result: Function[]; - - result = emitter.listeners(event); - } - - { - let result: boolean; - - result = emitter.emit(event); - result = emitter.emit(event, any); - result = emitter.emit(event, any, any); - result = emitter.emit(event, any, any, any); - } - - { - let result: (string | symbol)[]; - - result = emitter.eventNames(); - } - - { - class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } - } - } - - { - new events2(); - } -} - -//////////////////////////////////////////////////// -/// File system tests : http://nodejs.org/api/fs.html -//////////////////////////////////////////////////// - -namespace fs_tests { - { - fs.writeFile("thebible.txt", - "Do unto others as you would have them do unto you.", - assert.ifError); - - fs.write(1234, "test"); - - fs.writeFile("Harry Potter", - "\"You be wizzing, Harry,\" jived Dumbledore.", - { - encoding: "ascii" - }, - assert.ifError); - - fs.writeFile("testfile", "content", "utf8", assert.ifError); - - fs.writeFileSync("testfile", "content", "utf8"); - fs.writeFileSync("testfile", "content", { encoding: "utf8" }); - } - - { - fs.appendFile("testfile", "foobar", "utf8", assert.ifError); - fs.appendFile("testfile", "foobar", { encoding: "utf8" }, assert.ifError); - fs.appendFileSync("testfile", "foobar", "utf8"); - fs.appendFileSync("testfile", "foobar", { encoding: "utf8" }); - } - - { - var content: string; - var buffer: Buffer; - var stringOrBuffer: string | Buffer; - var nullEncoding: string | null = null; - var stringEncoding: string | null = 'utf8'; - - content = fs.readFileSync('testfile', 'utf8'); - content = fs.readFileSync('testfile', { encoding: 'utf8' }); - stringOrBuffer = fs.readFileSync('testfile', stringEncoding); - stringOrBuffer = fs.readFileSync('testfile', { encoding: stringEncoding }); - - buffer = fs.readFileSync('testfile'); - buffer = fs.readFileSync('testfile', null); - buffer = fs.readFileSync('testfile', { encoding: null }); - stringOrBuffer = fs.readFileSync('testfile', nullEncoding); - stringOrBuffer = fs.readFileSync('testfile', { encoding: nullEncoding }); - - buffer = fs.readFileSync('testfile', { flag: 'r' }); - - fs.readFile('testfile', 'utf8', (err, data) => content = data); - fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); - fs.readFile('testfile', stringEncoding, (err, data) => stringOrBuffer = data); - fs.readFile('testfile', { encoding: stringEncoding }, (err, data) => stringOrBuffer = data); - - fs.readFile('testfile', (err, data) => buffer = data); - fs.readFile('testfile', null, (err, data) => buffer = data); - fs.readFile('testfile', { encoding: null }, (err, data) => buffer = data); - fs.readFile('testfile', nullEncoding, (err, data) => stringOrBuffer = data); - fs.readFile('testfile', { encoding: nullEncoding }, (err, data) => stringOrBuffer = data); - - fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); - } - - { - var errno: number; - fs.readFile('testfile', (err, data) => { - if (err && err.errno) { - errno = err.errno; - } - }); - } - - { - fs.mkdtemp('/tmp/foo-', (err, folder) => { - console.log(folder); - // Prints: /tmp/foo-itXde2 - }); - } - - { - var tempDir: string; - tempDir = fs.mkdtempSync('/tmp/foo-'); - } - - { - fs.watch('/tmp/foo-', (event, filename) => { - console.log(event, filename); - }); - - fs.watch('/tmp/foo-', 'utf8', (event, filename) => { - console.log(event, filename); - }); - - fs.watch('/tmp/foo-', { - recursive: true, - persistent: true, - encoding: 'utf8' - }, (event, filename) => { - console.log(event, filename); - }); - } - - { - fs.access('/path/to/folder', (err) => { }); - - fs.access(Buffer.from(''), (err) => { }); - - fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - - fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - - fs.accessSync('/path/to/folder'); - - fs.accessSync(Buffer.from('')); - - fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); - - fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); - } -} - -/////////////////////////////////////////////////////// -/// Buffer tests : https://nodejs.org/api/buffer.html -/////////////////////////////////////////////////////// - -function bufferTests() { - var utf8Buffer = new Buffer('test'); - var base64Buffer = new Buffer('', 'base64'); - var octets: Uint8Array = null; - var octetBuffer = new Buffer(octets); - var sharedBuffer = new Buffer(octets.buffer); - var copiedBuffer = new Buffer(utf8Buffer); - console.log(Buffer.isBuffer(octetBuffer)); - console.log(Buffer.isEncoding('utf8')); - console.log(Buffer.byteLength('xyz123')); - console.log(Buffer.byteLength('xyz123', 'ascii')); - var result1 = Buffer.concat([utf8Buffer, base64Buffer]); - var result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999); - - // Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64() - { - const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); - buf.swap16(); - buf.swap32(); - buf.swap64(); - } - - // Class Method: Buffer.from(data) - { - // Array - const buf1: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); - // Buffer - const buf2: Buffer = Buffer.from(buf1); - // String - const buf3: Buffer = Buffer.from('this is a tést'); - // ArrayBuffer - const arr: Uint16Array = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; - const buf4: Buffer = Buffer.from(arr.buffer); - } - - // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) - { - const arr: Uint16Array = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; - - let buf: Buffer; - buf = Buffer.from(arr.buffer, 1); - buf = Buffer.from(arr.buffer, 0, 1); - } - - // Class Method: Buffer.from(str[, encoding]) - { - const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); - } - - // Class Method: Buffer.alloc(size[, fill[, encoding]]) - { - const buf1: Buffer = Buffer.alloc(5); - const buf2: Buffer = Buffer.alloc(5, 'a'); - const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); - } - // Class Method: Buffer.allocUnsafe(size) - { - const buf: Buffer = Buffer.allocUnsafe(5); - } - // Class Method: Buffer.allocUnsafeSlow(size) - { - const buf: Buffer = Buffer.allocUnsafeSlow(10); - } - - // Test that TS 1.6 works with the 'as Buffer' annotation - // on isBuffer. - var a: Buffer | number; - a = new Buffer(10); - if (Buffer.isBuffer(a)) { - a.writeUInt8(3, 4); - } - - // write* methods return offsets. - var b = new Buffer(16); - var result: number = b.writeUInt32LE(0, 0); - result = b.writeUInt16LE(0, 4); - result = b.writeUInt8(0, 6); - result = b.writeInt8(0, 7); - result = b.writeDoubleLE(0, 8); - - // fill returns the input buffer. - b.fill('a').fill('b'); - - { - let buffer = new Buffer('123'); - let index: number; - index = buffer.indexOf("23"); - index = buffer.indexOf("23", 1); - index = buffer.indexOf("23", 1, "utf8"); - index = buffer.indexOf(23); - index = buffer.indexOf(buffer); - } - - { - let buffer = new Buffer('123'); - let index: number; - index = buffer.lastIndexOf("23"); - index = buffer.lastIndexOf("23", 1); - index = buffer.lastIndexOf("23", 1, "utf8"); - index = buffer.lastIndexOf(23); - index = buffer.lastIndexOf(buffer); - } - - { - let buffer = new Buffer('123'); - let val: [number, number]; - - /* comment out for --target es5 - for (let entry of buffer.entries()) { - val = entry; - } - */ - } - - { - let buffer = new Buffer('123'); - let includes: boolean; - includes = buffer.includes("23"); - includes = buffer.includes("23", 1); - includes = buffer.includes("23", 1, "utf8"); - includes = buffer.includes(23); - includes = buffer.includes(23, 1); - includes = buffer.includes(23, 1, "utf8"); - includes = buffer.includes(buffer); - includes = buffer.includes(buffer, 1); - includes = buffer.includes(buffer, 1, "utf8"); - } - - { - let buffer = new Buffer('123'); - let val: number; - - /* comment out for --target es5 - for (let key of buffer.keys()) { - val = key; - } - */ - } - - { - let buffer = new Buffer('123'); - let val: number; - - /* comment out for --target es5 - for (let value of buffer.values()) { - val = value; - } - */ - } - - // Imported Buffer from buffer module works properly - { - let b = new ImportedBuffer('123'); - b.writeUInt8(0, 6); - let sb = new ImportedSlowBuffer(43); - b.writeUInt8(0, 6); - } - - // Buffer has Uint8Array's buffer field (an ArrayBuffer). - { - let buffer = new Buffer('123'); - let octets = new Uint8Array(buffer.buffer); - } - - // Buffer module, transcode function - { - transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer - - const source: TranscodeEncoding = 'utf8'; - const target: TranscodeEncoding = 'ascii'; - transcode(Buffer.from('€'), source, target); // $ExpectType Buffer - } -} - - -//////////////////////////////////////////////////// -/// Url tests : http://nodejs.org/api/url.html -//////////////////////////////////////////////////// - -namespace url_tests { - { - url.format(url.parse('http://www.example.com/xyz')); - - url.format('http://www.example.com/xyz'); - - // https://google.com/search?q=you're%20a%20lizard%2C%20gary - url.format({ - protocol: 'https', - host: "google.com", - pathname: 'search', - query: { q: "you're a lizard, gary" } - }); - - const myURL = new url.URL('https://a:b@你好你好?abc#foo'); - url.format(myURL, { fragment: false, unicode: true, auth: false }); - } - - { - var helloUrl = url.parse('http://example.com/?hello=world', true) - assert.equal(helloUrl.query.hello, 'world'); - } - - { - const ascii: string = url.domainToASCII('español.com'); - const unicode: string = url.domainToUnicode('xn--espaol-zwa.com'); - } - - { - let myURL = new url.URL('https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.hash, '#bar'); - assert.equal(myURL.host, 'example.org:81'); - assert.equal(myURL.hostname, 'example.org'); - assert.equal(myURL.href, 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.origin, 'https://example.org:81'); - assert.equal(myURL.password, 'thepwd'); - assert.equal(myURL.username, 'theuser'); - assert.equal(myURL.pathname, '/foo/path'); - assert.equal(myURL.port, "81"); - assert.equal(myURL.protocol, "https:"); - assert.equal(myURL.search, "?query=string"); - assert.equal(myURL.toString(), 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert(myURL.searchParams instanceof url.URLSearchParams); - - myURL.host = 'example.org:82'; - myURL.hostname = 'example.com'; - myURL.href = 'http://other.com'; - myURL.hash = 'baz'; - myURL.password = "otherpwd"; - myURL.username = "otheruser"; - myURL.pathname = "/otherPath"; - myURL.port = "82"; - myURL.protocol = "http"; - myURL.search = "a=b"; - assert.equal(myURL.href, 'http://otheruser:otherpwd@other.com:82/otherPath?a=b#baz'); - - myURL = new url.URL('/foo', 'https://example.org/'); - assert.equal(myURL.href, 'https://example.org/foo'); - assert.equal(myURL.toJSON(), myURL.href); - } - - { - const searchParams = new url.URLSearchParams('abc=123'); - - assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { - assert.equal(name, 'abc'); - assert.equal(value, '123'); - assert.equal(me, searchParams); - }); - - assert.equal(searchParams.get('abc'), '123'); - - searchParams.append('abc', 'xyz'); - - assert.deepEqual(searchParams.getAll('abc'), ['123', 'xyz']); - - const entries = searchParams.entries(); - assert.deepEqual(entries.next(), { value: ["abc", "123"], done: false}); - assert.deepEqual(entries.next(), { value: ["abc", "xyz"], done: false}); - assert.deepEqual(entries.next(), { value: undefined, done: true}); - - const keys = searchParams.keys(); - assert.deepEqual(keys.next(), { value: "abc", done: false}); - assert.deepEqual(keys.next(), { value: "abc", done: false}); - assert.deepEqual(keys.next(), { value: undefined, done: true}); - - const values = searchParams.values(); - assert.deepEqual(values.next(), { value: "123", done: false}); - assert.deepEqual(values.next(), { value: "xyz", done: false}); - assert.deepEqual(values.next(), { value: undefined, done: true}); - - searchParams.set('abc', 'b'); - assert.deepEqual(searchParams.getAll('abc'), ['b']); - - searchParams.delete('a'); - assert(!searchParams.has('a')); - assert.equal(searchParams.get('a'), null); - - searchParams.sort(); - } - - { - const searchParams = new url.URLSearchParams({ - user: 'abc', - query: ['first', 'second'] - }); - - assert.equal(searchParams.toString(), 'user=abc&query=first%2Csecond'); - assert.deepEqual(searchParams.getAll('query'), ['first,second']); - } - - { - // Using an array - let params = new url.URLSearchParams([ - ['user', 'abc'], - ['query', 'first'], - ['query', 'second'] - ]); - assert.equal(params.toString(), 'user=abc&query=first&query=second'); - } -} - -///////////////////////////////////////////////////// -/// util tests : https://nodejs.org/api/util.html /// -///////////////////////////////////////////////////// - -namespace util_tests { - { - // Old and new util.inspect APIs - util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], false, null); - util.inspect(["This is nice"], { - colors: true, - depth: 5, - customInspect: false, - showProxy: true, - maxArrayLength: 10, - breakLength: 20 - }); - util.inspect(["This is nice"], { - colors: true, - depth: null, - customInspect: false, - showProxy: true, - maxArrayLength: null, - breakLength: Infinity - }); - // util.deprecate - const foo = () => {}; - // $ExpectType () => void - util.deprecate(foo, 'foo() is deprecated, use bar() instead'); - // $ExpectType (fn: T, message: string) => T - util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); - } -} - -//////////////////////////////////////////////////// -/// Stream tests : http://nodejs.org/api/stream.html -//////////////////////////////////////////////////// - -// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options -function stream_readable_pipe_test() { - var rs = fs.createReadStream(Buffer.from('file.txt')); - var r = fs.createReadStream('file.txt'); - var z = zlib.createGzip({ finishFlush: zlib.constants.Z_FINISH }); - var w = fs.createWriteStream('file.txt.gz'); - - assert(typeof r.bytesRead === 'number'); - assert(typeof r.path === 'string'); - assert(rs.path instanceof Buffer); - - r.pipe(z).pipe(w); - - r.close(); - rs.close(); -} - -// helpers -const compressMe = new Buffer("some data"); -const compressMeString = "compress me!"; - -zlib.deflate(compressMe, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflate(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMeString, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMeString, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflate(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -const inflated = zlib.inflateSync(zlib.deflateSync(compressMe)); -const inflatedString = zlib.inflateSync(zlib.deflateSync(compressMeString)); - -zlib.deflateRaw(compressMe, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); -zlib.deflateRaw(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -zlib.deflateRaw(compressMeString, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); -zlib.deflateRaw(compressMeString, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -const inflatedRaw: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMe)); -const inflatedRawString: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMeString)); - -zlib.gzip(compressMe, (err: Error, result: Buffer) => zlib.gunzip(result, (err: Error, result: Buffer) => result)); -zlib.gzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.gunzip(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -const gunzipped: Buffer = zlib.gunzipSync(zlib.gzipSync(compressMe)); - -zlib.unzip(compressMe, (err: Error, result: Buffer) => result); -zlib.unzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result); -const unzipped: Buffer = zlib.unzipSync(compressMe); - -// Simplified constructors -function simplified_stream_ctor_test() { - new stream.Readable({ - read: function(size) { - size.toFixed(); - } - }); - - new stream.Writable({ - write: function(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb() - }, - writev: function(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); - } - }); - - new stream.Duplex({ - read: function(size) { - size.toFixed(); - }, - write: function(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb() - }, - writev: function(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); - }, - readableObjectMode: true, - writableObjectMode: true - }); - - new stream.Transform({ - transform: function(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); - }, - flush: function(cb) { - cb() - }, - read: function(size) { - size.toFixed(); - }, - write: function(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb() - }, - writev: function(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); - }, - allowHalfOpen: true, - readableObjectMode: true, - writableObjectMode: true - }) -} - -//////////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html /// -//////////////////////////////////////////////////////// - -namespace crypto_tests { - { - var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); - } - - { - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer | string = hmac.read(); - }); - } - - { - //crypto_cipher_decipher_string_test - let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - let clearText: string = "This is the clear text."; - let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - let cipherText: string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); - - let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - let clearText2: string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); - - assert.equal(clearText2, clearText); - } - - { - //crypto_cipher_decipher_buffer_test - let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - let cipherBuffers: Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); - - let cipherText: Buffer = Buffer.concat(cipherBuffers); - - let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - let decipherBuffers: Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - let clearText2: Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); - } - - { - let buffer1: Buffer = new Buffer([1, 2, 3, 4, 5]); - let buffer2: Buffer = new Buffer([1, 2, 3, 4, 5]); - let buffer3: Buffer = new Buffer([5, 4, 3, 2, 1]); - - assert(crypto.timingSafeEqual(buffer1, buffer2)) - assert(!crypto.timingSafeEqual(buffer1, buffer3)) - } - - { - let buffer: Buffer = new Buffer(10); - crypto.randomFillSync(buffer); - crypto.randomFillSync(buffer, 2); - crypto.randomFillSync(buffer, 2, 3); - - crypto.randomFill(buffer, (err: Error, buf: Buffer) => void {}); - crypto.randomFill(buffer, 2, (err: Error, buf: Buffer) => void {}); - crypto.randomFill(buffer, 2, 3, (err: Error, buf: Buffer) => void {}); - - let arr: Uint8Array = new Uint8Array(10); - crypto.randomFillSync(arr); - crypto.randomFillSync(arr, 2); - crypto.randomFillSync(arr, 2, 3); - - crypto.randomFill(arr, (err: Error, buf: Uint8Array) => void {}); - crypto.randomFill(arr, 2, (err: Error, buf: Uint8Array) => void {}); - crypto.randomFill(arr, 2, 3, (err: Error, buf: Uint8Array) => void {}); - } -} - -////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html /// -////////////////////////////////////////////////// - -namespace tls_tests { - { - var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", - }); - var blah = ctx.context; - - var connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 - }; - var tlsSocket = tls.connect(connOpts); - } - - { - let _server: tls.Server; - let _boolean: boolean; - let _func1 = function(err: Error, resp: Buffer){}; - let _func2 = function(err: Error, sessionData: any){}; - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - **/ - - _server = _server.addListener("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - _server = _server.addListener("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }) - _server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }) - _server = _server.addListener("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }) - _server = _server.addListener("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - - let _err: Error; - let _tlsSocket: tls.TLSSocket; - let _any: any; - let _func: Function; - let _buffer: Buffer; - _boolean = _server.emit("tlsClientError", _err, _tlsSocket); - _boolean = _server.emit("newSession", _any, _any, _func1); - _boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func); - _boolean = _server.emit("resumeSession", _any, _func2); - _boolean = _server.emit("secureConnection", _tlsSocket); - - _server = _server.on("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - _server = _server.on("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }) - _server = _server.on("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }) - _server = _server.on("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }) - _server = _server.on("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - - _server = _server.once("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - _server = _server.once("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }) - _server = _server.once("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }) - _server = _server.once("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }) - _server = _server.once("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - - _server = _server.prependListener("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - _server = _server.prependListener("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }) - _server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }) - _server = _server.prependListener("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }) - _server = _server.prependListener("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - - _server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - _server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }) - _server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }) - _server = _server.prependOnceListener("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }) - _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }) - - // close callback parameter is optional - _server = _server.close(); - - // close callback parameter doesn't specify any arguments, so any - // function is acceptable - _server = _server.close(() => {}); - _server = _server.close((...args:any[]) => {}); - } - - { - let _TLSSocket: tls.TLSSocket; - let _boolean: boolean; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - **/ - - _TLSSocket = _TLSSocket.addListener("OCSPResponse", (response) => { - let _response: Buffer = response; - }) - _TLSSocket = _TLSSocket.addListener("secureConnect", () => { }); - - let _buffer: Buffer; - _boolean = _TLSSocket.emit("OCSPResponse", _buffer); - _boolean = _TLSSocket.emit("secureConnect"); - - _TLSSocket = _TLSSocket.on("OCSPResponse", (response) => { - let _response: Buffer = response; - }) - _TLSSocket = _TLSSocket.on("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.once("OCSPResponse", (response) => { - let _response: Buffer = response; - }) - _TLSSocket = _TLSSocket.once("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependListener("OCSPResponse", (response) => { - let _response: Buffer = response; - }) - _TLSSocket = _TLSSocket.prependListener("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependOnceListener("OCSPResponse", (response) => { - let _response: Buffer = response; - }) - _TLSSocket = _TLSSocket.prependOnceListener("secureConnect", () => { }); - } -} - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html /// -//////////////////////////////////////////////////// - -namespace http_tests { - { - // Status codes - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; - } - - { - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); - - var agent: http.Agent = http.globalAgent; - - http.request({ agent: false }); - http.request({ agent: agent }); - http.request({ agent: undefined }); - } - - { - http.request('http://www.example.com/xyz'); - } - - { - // Make sure .listen() and .close() retuern a Server instance - http.createServer().listen(0).close().address(); - net.createServer().listen(0).close().address(); - } - - { - var request = http.request({ path: 'http://0.0.0.0' }); - request.once('error', function() { }); - request.setNoDelay(true); - request.abort(); - } - - // http request options - { - const requestOpts: http.RequestOptions = { - timeout: 30000 - }; - - const clientArgs: http.ClientRequestArgs = { - timeout: 30000 - }; - } - - // http headers - { - const headers: http.IncomingHttpHeaders = { - 'content-type': 'application/json', - 'set-cookie': [ 'type=ninja', 'language=javascript' ] - }; - } -} - -////////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html /// -////////////////////////////////////////////////////// - -namespace https_tests { - var agent: https.Agent = new https.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256, - maxCachedSessions: 100 - }); - - var agent: https.Agent = https.globalAgent; - - https.request({ - agent: false - }); - https.request({ - agent: agent - }); - https.request({ - agent: undefined - }); - - https.request('http://www.example.com/xyz'); - - https.globalAgent.options.ca = []; -} - -//////////////////////////////////////////////////// -/// TTY tests : http://nodejs.org/api/tty.html -//////////////////////////////////////////////////// - -namespace tty_tests { - let rs: tty.ReadStream; - let ws: tty.WriteStream; - - let rsIsRaw: boolean = rs.isRaw; - rs.setRawMode(true); - - let wsColumns: number = ws.columns; - let wsRows: number = ws.rows; - - let isTTY: boolean = tty.isatty(1); -} - -//////////////////////////////////////////////////// -/// Dgram tests : http://nodejs.org/api/dgram.html -//////////////////////////////////////////////////// - -namespace dgram_tests { - { - var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { - }); - ds.bind(); - ds.bind(41234); - var ai: dgram.AddressInfo = ds.address(); - ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { - }); - ds.send(new Buffer("hello"), 5000, "127.0.0.1"); - } - - { - let _socket: dgram.Socket; - let _boolean: boolean; - let _err: Error; - let _str: string; - let _rinfo: dgram.AddressInfo; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - **/ - - _socket = _socket.addListener("close", () => {}); - _socket = _socket.addListener("error", (err) => { - let _err: Error = err; - }) - _socket = _socket.addListener("listening", () => {}); - _socket = _socket.addListener("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }) - - _boolean = _socket.emit("close") - _boolean = _socket.emit("error", _err); - _boolean = _socket.emit("listening"); - _boolean = _socket.emit("message", _str, _rinfo); - - _socket = _socket.on("close", () => {}); - _socket = _socket.on("error", (err) => { - let _err: Error = err; - }) - _socket = _socket.on("listening", () => {}); - _socket = _socket.on("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }) - - _socket = _socket.once("close", () => {}); - _socket = _socket.once("error", (err) => { - let _err: Error = err; - }) - _socket = _socket.once("listening", () => {}); - _socket = _socket.once("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }) - - _socket = _socket.prependListener("close", () => {}); - _socket = _socket.prependListener("error", (err) => { - let _err: Error = err; - }) - _socket = _socket.prependListener("listening", () => {}); - _socket = _socket.prependListener("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }) - - _socket = _socket.prependOnceListener("close", () => {}); - _socket = _socket.prependOnceListener("error", (err) => { - let _err: Error = err; - }) - _socket = _socket.prependOnceListener("listening", () => {}); - _socket = _socket.prependOnceListener("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }) - } -} - -//////////////////////////////////////////////////// -///Querystring tests : https://nodejs.org/api/querystring.html -//////////////////////////////////////////////////// - -namespace querystring_tests { - type SampleObject = { a: string; b: number; } - - { - let obj: SampleObject; - let sep: string; - let eq: string; - let options: querystring.StringifyOptions; - let result: string; - - result = querystring.stringify(obj); - result = querystring.stringify(obj, sep); - result = querystring.stringify(obj, sep, eq); - result = querystring.stringify(obj, sep, eq); - result = querystring.stringify(obj, sep, eq, options); - } - - { - let str: string; - let sep: string; - let eq: string; - let options: querystring.ParseOptions; - let result: SampleObject; - - result = querystring.parse(str); - result = querystring.parse(str, sep); - result = querystring.parse(str, sep, eq); - result = querystring.parse(str, sep, eq, options); - } - - { - let str: string; - let result: string; - - result = querystring.escape(str); - result = querystring.unescape(str); - } -} - -//////////////////////////////////////////////////// -/// path tests : http://nodejs.org/api/path.html -//////////////////////////////////////////////////// - -namespace path_tests { - - path.normalize('/foo/bar//baz/asdf/quux/..'); - - path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); - // returns - //'/foo/bar/baz/asdf' - - try { - path.join('foo', 'bar'); - } - catch (error) { - - } - - path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile'); - //Is similar to: - // - //cd foo/bar - //cd /tmp/file/ - //cd .. - // cd a/../subfile - //pwd - - path.resolve('/foo/bar', './baz') - // returns - // '/foo/bar/baz' - - path.resolve('/foo/bar', '/tmp/file/') - // returns - // '/tmp/file' - - path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif') - // if currently in /home/myself/node, it returns - // '/home/myself/node/wwwroot/static_files/gif/image.gif' - - path.isAbsolute('/foo/bar') // true - path.isAbsolute('/baz/..') // true - path.isAbsolute('qux/') // false - path.isAbsolute('.') // false - - path.isAbsolute('//server') // true - path.isAbsolute('C:/foo/..') // true - path.isAbsolute('bar\\baz') // false - path.isAbsolute('.') // false - - path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb') - // returns - // '..\\..\\impl\\bbb' - - path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') - // returns - // '../../impl/bbb' - - path.dirname('/foo/bar/baz/asdf/quux') - // returns - // '/foo/bar/baz/asdf' - - path.basename('/foo/bar/baz/asdf/quux.html') - // returns - // 'quux.html' - - path.basename('/foo/bar/baz/asdf/quux.html', '.html') - // returns - // 'quux' - - path.extname('index.html') - // returns - // '.html' - - path.extname('index.coffee.md') - // returns - // '.md' - - path.extname('index.') - // returns - // '.' - - path.extname('index') - // returns - // '' - - 'foo/bar/baz'.split(path.sep) - // returns - // ['foo', 'bar', 'baz'] - - 'foo\\bar\\baz'.split(path.sep) - // returns - // ['foo', 'bar', 'baz'] - - process.env["PATH"]; // $ExpectType string - - path.parse('/home/user/dir/file.txt') - // returns - // { - // root : "/", - // dir : "/home/user/dir", - // base : "file.txt", - // ext : ".txt", - // name : "file" - // } - - path.parse('C:\\path\\dir\\index.html') - // returns - // { - // root : "C:\", - // dir : "C:\path\dir", - // base : "index.html", - // ext : ".html", - // name : "index" - // } - - path.format({ - root: "/", - dir: "/home/user/dir", - base: "file.txt", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - path.format({ - dir: "/home/user/dir", - base: "file.txt" - }); - // returns - // '/home/user/dir/file.txt' - - path.posix.format({ - root: "/", - dir: "/home/user/dir", - base: "file.txt", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - path.posix.format({ - dir: "/home/user/dir", - base: "file.txt" - }); - // returns - // '/home/user/dir/file.txt' - - path.win32.format({ - root: "C:\\", - dir: "C:\\home\\user\\dir", - ext: ".txt", - name: "file" - }); - // returns - // 'C:\home\user\dir\file.txt' - - path.win32.format({ - dir: "C:\\home\\user\\dir", - base: "file.txt" - }); - // returns - // 'C:\home\user\dir\file.txt' -} - -//////////////////////////////////////////////////// -/// readline tests : https://nodejs.org/api/readline.html -//////////////////////////////////////////////////// - -namespace readline_tests { - let rl: readline.ReadLine; - - { - let options: readline.ReadLineOptions; - let input: NodeJS.ReadableStream; - let output: NodeJS.WritableStream; - let completer: readline.Completer; - let terminal: boolean; - - let result: readline.ReadLine; - - result = readline.createInterface(options); - result = readline.createInterface(input); - result = readline.createInterface(input, output); - result = readline.createInterface(input, output, completer); - result = readline.createInterface(input, output, completer, terminal); - result = readline.createInterface({ - input: input, - completer: function(str: string): readline.CompleterResult { - return [['test'], 'test']; - } - }); - result = readline.createInterface({ - input: input, - completer: function(str: string, callback: (err: any, result: readline.CompleterResult) => void): any { - callback(null, [['test'], 'test']); - } - }); - } - - { - let prompt: string; - - rl.setPrompt(prompt); - } - - { - let preserveCursor: boolean; - - rl.prompt(); - rl.prompt(preserveCursor); - } - - { - let query: string; - let callback: (answer: string) => void; - - rl.question(query, callback); - } - - { - let result: readline.ReadLine; - - result = rl.pause(); - } - - { - let result: readline.ReadLine; - - result = rl.resume(); - } - - { - rl.close(); - } - - { - let data: string | Buffer; - let key: readline.Key; - - rl.write(data); - rl.write(null, key); - } - - { - let stream: NodeJS.WritableStream; - let x: number; - let y: number; - - readline.cursorTo(stream, x, y); - } - - { - let stream: NodeJS.WritableStream; - let dx: number | string; - let dy: number | string; - - readline.moveCursor(stream, dx, dy); - } - - { - let stream: NodeJS.WritableStream; - let dir: number; - - readline.clearLine(stream, dir); - } - - { - let stream: NodeJS.WritableStream; - - readline.clearScreenDown(stream); - } - - { - let _rl: readline.ReadLine; - let _boolean: boolean; - - _rl = _rl.addListener("close", () => { }); - _rl = _rl.addListener("line", (input) => { - let _input: any = input; - }) - _rl = _rl.addListener("pause", () => { }); - _rl = _rl.addListener("resume", () => { }); - _rl = _rl.addListener("SIGCONT", () => { }); - _rl = _rl.addListener("SIGINT", () => { }); - _rl = _rl.addListener("SIGTSTP", () => { }); - - _boolean = _rl.emit("close", () => { }); - _boolean = _rl.emit("line", () => { }); - _boolean = _rl.emit("pause", () => { }); - _boolean = _rl.emit("resume", () => { }); - _boolean = _rl.emit("SIGCONT", () => { }); - _boolean = _rl.emit("SIGINT", () => { }); - _boolean = _rl.emit("SIGTSTP", () => { }); - - _rl = _rl.on("close", () => { }); - _rl = _rl.on("line", (input) => { - let _input: any = input; - }) - _rl = _rl.on("pause", () => { }); - _rl = _rl.on("resume", () => { }); - _rl = _rl.on("SIGCONT", () => { }); - _rl = _rl.on("SIGINT", () => { }); - _rl = _rl.on("SIGTSTP", () => { }); - - _rl = _rl.once("close", () => { }); - _rl = _rl.once("line", (input) => { - let _input: any = input; - }) - _rl = _rl.once("pause", () => { }); - _rl = _rl.once("resume", () => { }); - _rl = _rl.once("SIGCONT", () => { }); - _rl = _rl.once("SIGINT", () => { }); - _rl = _rl.once("SIGTSTP", () => { }); - - _rl = _rl.prependListener("close", () => { }); - _rl = _rl.prependListener("line", (input) => { - let _input: any = input; - }) - _rl = _rl.prependListener("pause", () => { }); - _rl = _rl.prependListener("resume", () => { }); - _rl = _rl.prependListener("SIGCONT", () => { }); - _rl = _rl.prependListener("SIGINT", () => { }); - _rl = _rl.prependListener("SIGTSTP", () => { }); - - _rl = _rl.prependOnceListener("close", () => { }); - _rl = _rl.prependOnceListener("line", (input) => { - let _input: any = input; - }) - _rl = _rl.prependOnceListener("pause", () => { }); - _rl = _rl.prependOnceListener("resume", () => { }); - _rl = _rl.prependOnceListener("SIGCONT", () => { }); - _rl = _rl.prependOnceListener("SIGINT", () => { }); - _rl = _rl.prependOnceListener("SIGTSTP", () => { }); - } -} - -//////////////////////////////////////////////////// -/// string_decoder tests : https://nodejs.org/api/string_decoder.html -//////////////////////////////////////////////////// - -namespace string_decoder_tests { - const StringDecoder = string_decoder.StringDecoder; - const buffer = new Buffer('test'); - const decoder1 = new StringDecoder(); - const decoder2 = new StringDecoder('utf8'); - const part1: string = decoder1.write(new Buffer('test')); - const end1: string = decoder1.end(); - const part2: string = decoder2.write(new Buffer('test')); - const end2: string = decoder1.end(new Buffer('test')); -} - -////////////////////////////////////////////////////////////////////// -/// Child Process tests: https://nodejs.org/api/child_process.html /// -////////////////////////////////////////////////////////////////////// - -namespace child_process_tests { - { - childProcess.exec("echo test"); - childProcess.spawnSync("echo test"); - } - - { - let _cp: childProcess.ChildProcess; - let _boolean: boolean; - - _cp = _cp.addListener("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.addListener("disconnect", () => { }); - _cp = _cp.addListener("error", (err) => { - let _err: Error = err; - }) - _cp = _cp.addListener("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.addListener("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }) - - _boolean = _cp.emit("close", () => { }); - _boolean = _cp.emit("disconnect", () => { }); - _boolean = _cp.emit("error", () => { }); - _boolean = _cp.emit("exit", () => { }); - _boolean = _cp.emit("message", () => { }); - - _cp = _cp.on("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.on("disconnect", () => { }); - _cp = _cp.on("error", (err) => { - let _err: Error = err; - }) - _cp = _cp.on("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.on("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }) - - _cp = _cp.once("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.once("disconnect", () => { }); - _cp = _cp.once("error", (err) => { - let _err: Error = err; - }) - _cp = _cp.once("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.once("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }) - - _cp = _cp.prependListener("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.prependListener("disconnect", () => { }); - _cp = _cp.prependListener("error", (err) => { - let _err: Error = err; - }) - _cp = _cp.prependListener("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.prependListener("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }) - - _cp = _cp.prependOnceListener("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.prependOnceListener("disconnect", () => { }); - _cp = _cp.prependOnceListener("error", (err) => { - let _err: Error = err; - }) - _cp = _cp.prependOnceListener("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }) - _cp = _cp.prependOnceListener("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }) - } -} - -////////////////////////////////////////////////////////////////////// -/// cluster tests: https://nodejs.org/api/cluster.html /// -////////////////////////////////////////////////////////////////////// - -namespace cluster_tests { - { - cluster.fork(); - Object.keys(cluster.workers).forEach(key => { - const worker = cluster.workers[key]; - if (worker.isDead()) { - console.log('worker %d is dead', worker.process.pid); - } - }); - } -} - -//////////////////////////////////////////////////// -/// os tests : https://nodejs.org/api/os.html -//////////////////////////////////////////////////// - -namespace os_tests { - { - let result: string; - - result = os.tmpdir(); - result = os.homedir(); - result = os.endianness(); - result = os.hostname(); - result = os.type(); - result = os.arch(); - result = os.release(); - result = os.EOL; - } - - { - let result: number; - - result = os.uptime(); - result = os.totalmem(); - result = os.freemem(); - } - - { - let result: number[]; - - result = os.loadavg(); - } - - { - let result: os.CpuInfo[]; - - result = os.cpus(); - } - - { - let result: { [index: string]: os.NetworkInterfaceInfo[] }; - - result = os.networkInterfaces(); - } - - { - let result: number; - - result = os.constants.signals.SIGHUP; - result = os.constants.signals.SIGINT; - result = os.constants.signals.SIGQUIT; - result = os.constants.signals.SIGILL; - result = os.constants.signals.SIGTRAP; - result = os.constants.signals.SIGABRT; - result = os.constants.signals.SIGIOT; - result = os.constants.signals.SIGBUS; - result = os.constants.signals.SIGFPE; - result = os.constants.signals.SIGKILL; - result = os.constants.signals.SIGUSR1; - result = os.constants.signals.SIGSEGV; - result = os.constants.signals.SIGUSR2; - result = os.constants.signals.SIGPIPE; - result = os.constants.signals.SIGALRM; - result = os.constants.signals.SIGTERM; - result = os.constants.signals.SIGCHLD; - result = os.constants.signals.SIGSTKFLT; - result = os.constants.signals.SIGCONT; - result = os.constants.signals.SIGSTOP; - result = os.constants.signals.SIGTSTP; - result = os.constants.signals.SIGTTIN; - result = os.constants.signals.SIGTTOU; - result = os.constants.signals.SIGURG; - result = os.constants.signals.SIGXCPU; - result = os.constants.signals.SIGXFSZ; - result = os.constants.signals.SIGVTALRM; - result = os.constants.signals.SIGPROF; - result = os.constants.signals.SIGWINCH; - result = os.constants.signals.SIGIO; - result = os.constants.signals.SIGPOLL; - result = os.constants.signals.SIGPWR; - result = os.constants.signals.SIGSYS; - result = os.constants.signals.SIGUNUSED; - } - - { - let result: number; - - result = os.constants.errno.E2BIG; - result = os.constants.errno.EACCES; - result = os.constants.errno.EADDRINUSE; - result = os.constants.errno.EADDRNOTAVAIL; - result = os.constants.errno.EAFNOSUPPORT; - result = os.constants.errno.EAGAIN; - result = os.constants.errno.EALREADY; - result = os.constants.errno.EBADF; - result = os.constants.errno.EBADMSG; - result = os.constants.errno.EBUSY; - result = os.constants.errno.ECANCELED; - result = os.constants.errno.ECHILD; - result = os.constants.errno.ECONNABORTED; - result = os.constants.errno.ECONNREFUSED; - result = os.constants.errno.ECONNRESET; - result = os.constants.errno.EDEADLK; - result = os.constants.errno.EDESTADDRREQ; - result = os.constants.errno.EDOM; - result = os.constants.errno.EDQUOT; - result = os.constants.errno.EEXIST; - result = os.constants.errno.EFAULT; - result = os.constants.errno.EFBIG; - result = os.constants.errno.EHOSTUNREACH; - result = os.constants.errno.EIDRM; - result = os.constants.errno.EILSEQ; - result = os.constants.errno.EINPROGRESS; - result = os.constants.errno.EINTR; - result = os.constants.errno.EINVAL; - result = os.constants.errno.EIO; - result = os.constants.errno.EISCONN; - result = os.constants.errno.EISDIR; - result = os.constants.errno.ELOOP; - result = os.constants.errno.EMFILE; - result = os.constants.errno.EMLINK; - result = os.constants.errno.EMSGSIZE; - result = os.constants.errno.EMULTIHOP; - result = os.constants.errno.ENAMETOOLONG; - result = os.constants.errno.ENETDOWN; - result = os.constants.errno.ENETRESET; - result = os.constants.errno.ENETUNREACH; - result = os.constants.errno.ENFILE; - result = os.constants.errno.ENOBUFS; - result = os.constants.errno.ENODATA; - result = os.constants.errno.ENODEV; - result = os.constants.errno.ENOENT; - result = os.constants.errno.ENOEXEC; - result = os.constants.errno.ENOLCK; - result = os.constants.errno.ENOLINK; - result = os.constants.errno.ENOMEM; - result = os.constants.errno.ENOMSG; - result = os.constants.errno.ENOPROTOOPT; - result = os.constants.errno.ENOSPC; - result = os.constants.errno.ENOSR; - result = os.constants.errno.ENOSTR; - result = os.constants.errno.ENOSYS; - result = os.constants.errno.ENOTCONN; - result = os.constants.errno.ENOTDIR; - result = os.constants.errno.ENOTEMPTY; - result = os.constants.errno.ENOTSOCK; - result = os.constants.errno.ENOTSUP; - result = os.constants.errno.ENOTTY; - result = os.constants.errno.ENXIO; - result = os.constants.errno.EOPNOTSUPP; - result = os.constants.errno.EOVERFLOW; - result = os.constants.errno.EPERM; - result = os.constants.errno.EPIPE; - result = os.constants.errno.EPROTO; - result = os.constants.errno.EPROTONOSUPPORT; - result = os.constants.errno.EPROTOTYPE; - result = os.constants.errno.ERANGE; - result = os.constants.errno.EROFS; - result = os.constants.errno.ESPIPE; - result = os.constants.errno.ESRCH; - result = os.constants.errno.ESTALE; - result = os.constants.errno.ETIME; - result = os.constants.errno.ETIMEDOUT; - result = os.constants.errno.ETXTBSY; - result = os.constants.errno.EWOULDBLOCK; - result = os.constants.errno.EXDEV; - } -} - -//////////////////////////////////////////////////// -/// vm tests : https://nodejs.org/api/vm.html -//////////////////////////////////////////////////// - -namespace vm_tests { - { - const sandbox = { - animal: 'cat', - count: 2 - }; - - const context = vm.createContext(sandbox); - console.log(vm.isContext(context)); - const script = new vm.Script('count += 1; name = "kitty"'); - - for (let i = 0; i < 10; ++i) { - script.runInContext(context); - } - - console.log(util.inspect(sandbox)); - - vm.runInNewContext('count += 1; name = "kitty"', sandbox); - console.log(util.inspect(sandbox)); - } - - { - const sandboxes = [{}, {}, {}]; - - const script = new vm.Script('globalVar = "set"'); - - sandboxes.forEach((sandbox) => { - script.runInNewContext(sandbox); - script.runInThisContext(); - }); - - console.log(util.inspect(sandboxes)); - - var localVar = 'initial value'; - vm.runInThisContext('localVar = "vm";'); - - console.log(localVar); - } - - { - const Debug = vm.runInDebugContext('Debug'); - Debug.scripts().forEach(function(script: any) { console.log(script.name); }); - } -} - -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - -namespace timers_tests { - { - let immediateId = timers.setImmediate(function() { console.log("immediate"); }); - timers.clearImmediate(immediateId); - } - { - let counter = 0; - let timeout = timers.setInterval(function() { console.log("interval"); }, 20); - timeout.unref(); - timeout.ref(); - timers.clearInterval(timeout); - } - { - let counter = 0; - let timeout = timers.setTimeout(function() { console.log("timeout"); }, 20); - timeout.unref(); - timeout.ref(); - timers.clearTimeout(timeout); - } -} - -///////////////////////////////////////////////////////// -/// Errors Tests : https://nodejs.org/api/errors.html /// -///////////////////////////////////////////////////////// - -namespace errors_tests { - { - Error.stackTraceLimit = Infinity; - } - { - const myObject = {}; - Error.captureStackTrace(myObject); - } - { - let frames: NodeJS.CallSite[] = []; - Error.prepareStackTrace(new Error(), frames); - } - { - let frame: NodeJS.CallSite = null; - let frameThis: any = frame.getThis(); - let typeName: string = frame.getTypeName(); - let func: Function = frame.getFunction(); - let funcName: string = frame.getFunctionName(); - let meth: string = frame.getMethodName(); - let fname: string = frame.getFileName(); - let lineno: number = frame.getLineNumber(); - let colno: number = frame.getColumnNumber(); - let evalOrigin: string = frame.getEvalOrigin(); - let isTop: boolean = frame.isToplevel(); - let isEval: boolean = frame.isEval(); - let isNative: boolean = frame.isNative(); - let isConstr: boolean = frame.isConstructor(); - } -} - -/////////////////////////////////////////////////////////// -/// Process Tests : https://nodejs.org/api/process.html /// -/////////////////////////////////////////////////////////// - -import * as p from "process"; -namespace process_tests { - { - var eventEmitter: events.EventEmitter; - eventEmitter = process; // Test that process implements EventEmitter... - - var _p: NodeJS.Process = process; - _p = p; - } - { - assert(process.argv[0] === process.argv0); - } - { - var module: NodeModule | undefined; - module = process.mainModule; - } -} - -/////////////////////////////////////////////////////////// -/// Console Tests : https://nodejs.org/api/console.html /// -/////////////////////////////////////////////////////////// - -import * as c from "console"; -namespace console_tests { - { - var _c: Console = console; - _c = c; - } - { - var writeStream = fs.createWriteStream('./index.d.ts'); - var consoleInstance = new console.Console(writeStream) - - } -} - -/////////////////////////////////////////////////// -/// Net Tests : https://nodejs.org/api/net.html /// -/////////////////////////////////////////////////// - -namespace net_tests { - { - let server = net.createServer(); - // Check methods which return server instances by chaining calls - server = server.listen(0) - .close() - .ref() - .unref(); - - // close has an optional callback function. No callback parameters are - // specified, so any callback function is permissible. - server = server.close((...args: any[]) => {}); - - // test the types of the address object fields - let address = server.address(); - address.port = 1234; - address.family = "ipv4"; - address.address = "127.0.0.1"; - } - - { - /** - * net.Socket - events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout - */ - let _socket: net.Socket = new net.Socket({ - fd: 1, - allowHalfOpen: false, - readable: false, - writable: false - }); - - let bool: boolean; - let buffer: Buffer; - let error: Error; - let str: string; - let num: number; - - /// addListener - - _socket = _socket.addListener("close", had_error => { - bool = had_error; - }) - _socket = _socket.addListener("connect", () => { }) - _socket = _socket.addListener("data", data => { - buffer = data; - }) - _socket = _socket.addListener("drain", () => { }) - _socket = _socket.addListener("end", () => { }) - _socket = _socket.addListener("error", err => { - error = err; - }) - _socket = _socket.addListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }) - _socket = _socket.addListener("timeout", () => { }) - - /// emit - bool = _socket.emit("close", bool); - bool = _socket.emit("connect"); - bool = _socket.emit("data", buffer); - bool = _socket.emit("drain"); - bool = _socket.emit("end"); - bool = _socket.emit("error", error); - bool = _socket.emit("lookup", error, str, str, str); - bool = _socket.emit("lookup", error, str, num, str); - bool = _socket.emit("timeout"); - - /// on - _socket = _socket.on("close", had_error => { - bool = had_error; - }) - _socket = _socket.on("connect", () => { }) - _socket = _socket.on("data", data => { - buffer = data; - }) - _socket = _socket.on("drain", () => { }) - _socket = _socket.on("end", () => { }) - _socket = _socket.on("error", err => { - error = err; - }) - _socket = _socket.on("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }) - _socket = _socket.on("timeout", () => { }) - - /// once - _socket = _socket.once("close", had_error => { - bool = had_error; - }) - _socket = _socket.once("connect", () => { }) - _socket = _socket.once("data", data => { - buffer = data; - }) - _socket = _socket.once("drain", () => { }) - _socket = _socket.once("end", () => { }) - _socket = _socket.once("error", err => { - error = err; - }) - _socket = _socket.once("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }) - _socket = _socket.once("timeout", () => { }) - - /// prependListener - _socket = _socket.prependListener("close", had_error => { - bool = had_error; - }) - _socket = _socket.prependListener("connect", () => { }) - _socket = _socket.prependListener("data", data => { - buffer = data; - }) - _socket = _socket.prependListener("drain", () => { }) - _socket = _socket.prependListener("end", () => { }) - _socket = _socket.prependListener("error", err => { - error = err; - }) - _socket = _socket.prependListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }) - _socket = _socket.prependListener("timeout", () => { }) - - /// prependOnceListener - _socket = _socket.prependOnceListener("close", had_error => { - bool = had_error; - }) - _socket = _socket.prependOnceListener("connect", () => { }) - _socket = _socket.prependOnceListener("data", data => { - buffer = data; - }) - _socket = _socket.prependOnceListener("drain", () => { }) - _socket = _socket.prependOnceListener("end", () => { }) - _socket = _socket.prependOnceListener("error", err => { - error = err; - }) - _socket = _socket.prependOnceListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }) - _socket = _socket.prependOnceListener("timeout", () => { }) - - bool = _socket.connecting; - bool = _socket.destroyed; - _socket.destroy(); - } - - { - /** - * net.Server - events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - */ - let _server: net.Server; - - let _socket: net.Socket; - let bool: boolean; - let error: Error; - - /// addListener - _server = _server.addListener("close", () => { }) - _server = _server.addListener("connection", socket => { - _socket = socket - }) - _server = _server.addListener("error", err => { - error = err; - }) - _server = _server.addListener("listening", () => { }) - - /// emit - bool = _server.emit("close") - bool = _server.emit("connection", _socket) - bool = _server.emit("error", error) - bool = _server.emit("listening") - - /// once - _server = _server.once("close", () => { }) - _server = _server.once("connection", socket => { - _socket = socket - }) - _server = _server.once("error", err => { - error = err; - }) - _server = _server.once("listening", () => { }) - - /// prependListener - _server = _server.prependListener("close", () => { }) - _server = _server.prependListener("connection", socket => { - _socket = socket - }) - _server = _server.prependListener("error", err => { - error = err; - }) - _server = _server.prependListener("listening", () => { }) - - /// prependOnceListener - _server = _server.prependOnceListener("close", () => { }) - _server = _server.prependOnceListener("connection", socket => { - _socket = socket - }) - _server = _server.prependOnceListener("error", err => { - error = err; - }) - _server = _server.prependOnceListener("listening", () => { }) - - } - -} - -///////////////////////////////////////////////////// -/// repl Tests : https://nodejs.org/api/repl.html /// -///////////////////////////////////////////////////// - -namespace repl_tests { - { - let _server: repl.REPLServer; - let _boolean: boolean; - let _ctx: any; - - _server = _server.addListener("exit", () => { }); - _server = _server.addListener("reset", () => { }); - - _boolean = _server.emit("exit", () => { }); - _boolean = _server.emit("reset", _ctx); - - _server = _server.on("exit", () => { }); - _server = _server.on("reset", () => { }); - - _server = _server.once("exit", () => { }); - _server = _server.once("reset", () => { }); - - _server = _server.prependListener("exit", () => { }); - _server = _server.prependListener("reset", () => { }); - - _server = _server.prependOnceListener("exit", () => { }); - _server = _server.prependOnceListener("reset", () => { }); - } -} - -/////////////////////////////////////////////////// -/// DNS Tests : https://nodejs.org/api/dns.html /// -/////////////////////////////////////////////////// - -namespace dns_tests { - dns.lookup("nodejs.org", (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 4, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 6, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", {}, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup( - "nodejs.org", - { - family: 4, - hints: dns.ADDRCONFIG | dns.V4MAPPED, - all: false - }, - (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - } - ); - dns.lookup("nodejs.org", {all: true}, (err, addresses) => { - const _err: NodeJS.ErrnoException = err; - const _address: dns.LookupAddress[] = addresses; - }); - - function trueOrFalse(): boolean { - return Math.random() > 0.5 ? true : false; - } - dns.lookup("nodejs.org", {all: trueOrFalse()}, (err, addresses, family) => { - const _err: NodeJS.ErrnoException = err; - const _addresses: string | dns.LookupAddress[] = addresses; - const _family: number | undefined = family; - }); - - dns.lookupService("127.0.0.1", 0, (err, hostname, service) => { - const _err: NodeJS.ErrnoException = err; - const _hostname: string = hostname; - const _service: string = service; - }); - - dns.resolve("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "A", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "AAAA", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "MX", (err, addresses) => { - const _addresses: dns.MxRecord[] = addresses; - }); - - dns.resolve4("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve4("nodejs.org", {ttl: true}, (err, addresses) => { - const _addresses: dns.RecordWithTtl[] = addresses; - }); - { - const ttl = false; - dns.resolve4("nodejs.org", {ttl: ttl}, (err, addresses) => { - const _addresses: string[] | dns.RecordWithTtl[] = addresses; - }); - } - - dns.resolve6("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve6("nodejs.org", {ttl: true}, (err, addresses) => { - const _addresses: dns.RecordWithTtl[] = addresses; - }); - { - const ttl = false; - dns.resolve6("nodejs.org", {ttl: ttl}, (err, addresses) => { - const _addresses: string[] | dns.RecordWithTtl[] = addresses; - }); - } -} - -/***************************************************************************** - * * - * The following tests are the modules not mentioned in document but existed * - * * - *****************************************************************************/ - -/////////////////////////////////////////////////////////// -/// Constants Tests /// -/////////////////////////////////////////////////////////// - -import * as constants from 'constants'; -namespace constants_tests { - var str: string; - var num: number; - num = constants.SIGHUP - num = constants.SIGINT - num = constants.SIGQUIT - num = constants.SIGILL - num = constants.SIGTRAP - num = constants.SIGABRT - num = constants.SIGIOT - num = constants.SIGBUS - num = constants.SIGFPE - num = constants.SIGKILL - num = constants.SIGUSR1 - num = constants.SIGSEGV - num = constants.SIGUSR2 - num = constants.SIGPIPE - num = constants.SIGALRM - num = constants.SIGTERM - num = constants.SIGCHLD - num = constants.SIGSTKFLT - num = constants.SIGCONT - num = constants.SIGSTOP - num = constants.SIGTSTP - num = constants.SIGTTIN - num = constants.SIGTTOU - num = constants.SIGURG - num = constants.SIGXCPU - num = constants.SIGXFSZ - num = constants.SIGVTALRM - num = constants.SIGPROF - num = constants.SIGWINCH - num = constants.SIGIO - num = constants.SIGPOLL - num = constants.SIGPWR - num = constants.SIGSYS - num = constants.SIGUNUSED - num = constants.O_RDONLY - num = constants.O_WRONLY - num = constants.O_RDWR - num = constants.S_IFMT - num = constants.S_IFREG - num = constants.S_IFDIR - num = constants.S_IFCHR - num = constants.S_IFBLK - num = constants.S_IFIFO - num = constants.S_IFLNK - num = constants.S_IFSOCK - num = constants.O_CREAT - num = constants.O_EXCL - num = constants.O_NOCTTY - num = constants.O_TRUNC - num = constants.O_APPEND - num = constants.O_DIRECTORY - num = constants.O_NOATIME - num = constants.O_NOFOLLOW - num = constants.O_SYNC - num = constants.O_DIRECT - num = constants.O_NONBLOCK - num = constants.S_IRWXU - num = constants.S_IRUSR - num = constants.S_IWUSR - num = constants.S_IXUSR - num = constants.S_IRWXG - num = constants.S_IRGRP - num = constants.S_IWGRP - num = constants.S_IXGRP - num = constants.S_IRWXO - num = constants.S_IROTH - num = constants.S_IWOTH - num = constants.S_IXOTH - num = constants.F_OK - num = constants.R_OK - num = constants.W_OK - num = constants.X_OK - num = constants.SSL_OP_ALL - num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION - num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE - num = constants.SSL_OP_CISCO_ANYCONNECT - num = constants.SSL_OP_COOKIE_EXCHANGE - num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG - num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS - num = constants.SSL_OP_EPHEMERAL_RSA - num = constants.SSL_OP_LEGACY_SERVER_CONNECT - num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER - num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG - num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING - num = constants.SSL_OP_NETSCAPE_CA_DN_BUG - num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG - num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG - num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG - num = constants.SSL_OP_NO_COMPRESSION - num = constants.SSL_OP_NO_QUERY_MTU - num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION - num = constants.SSL_OP_NO_SSLv2 - num = constants.SSL_OP_NO_SSLv3 - num = constants.SSL_OP_NO_TICKET - num = constants.SSL_OP_NO_TLSv1 - num = constants.SSL_OP_NO_TLSv1_1 - num = constants.SSL_OP_NO_TLSv1_2 - num = constants.SSL_OP_PKCS1_CHECK_1 - num = constants.SSL_OP_PKCS1_CHECK_2 - num = constants.SSL_OP_SINGLE_DH_USE - num = constants.SSL_OP_SINGLE_ECDH_USE - num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG - num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG - num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG - num = constants.SSL_OP_TLS_D5_BUG - num = constants.SSL_OP_TLS_ROLLBACK_BUG - num = constants.ENGINE_METHOD_RSA - num = constants.ENGINE_METHOD_DSA - num = constants.ENGINE_METHOD_DH - num = constants.ENGINE_METHOD_RAND - num = constants.ENGINE_METHOD_ECDH - num = constants.ENGINE_METHOD_ECDSA - num = constants.ENGINE_METHOD_CIPHERS - num = constants.ENGINE_METHOD_DIGESTS - num = constants.ENGINE_METHOD_STORE - num = constants.ENGINE_METHOD_PKEY_METHS - num = constants.ENGINE_METHOD_PKEY_ASN1_METHS - num = constants.ENGINE_METHOD_ALL - num = constants.ENGINE_METHOD_NONE - num = constants.DH_CHECK_P_NOT_SAFE_PRIME - num = constants.DH_CHECK_P_NOT_PRIME - num = constants.DH_UNABLE_TO_CHECK_GENERATOR - num = constants.DH_NOT_SUITABLE_GENERATOR - num = constants.NPN_ENABLED - num = constants.ALPN_ENABLED - num = constants.RSA_PKCS1_PADDING - num = constants.RSA_SSLV23_PADDING - num = constants.RSA_NO_PADDING - num = constants.RSA_PKCS1_OAEP_PADDING - num = constants.RSA_X931_PADDING - num = constants.RSA_PKCS1_PSS_PADDING - num = constants.POINT_CONVERSION_COMPRESSED - num = constants.POINT_CONVERSION_UNCOMPRESSED - num = constants.POINT_CONVERSION_HYBRID - str = constants.defaultCoreCipherList - str = constants.defaultCipherList -} - - -//////////////////////////////////////////////////// -/// v8 tests : https://nodejs.org/api/v8.html -//////////////////////////////////////////////////// - -namespace v8_tests { - - const heapStats = v8.getHeapStatistics(); - const heapSpaceStats = v8.getHeapSpaceStatistics(); - - const zapsGarbage: number = heapStats.does_zap_garbage; - - v8.setFlagsFromString('--collect_maps'); -} - -/////////////////////////////////////////////////////////// -/// Debugger Tests /// -/////////////////////////////////////////////////////////// - -import { Client } from "_debugger"; - -var client = new Client(); - -client.connect(8888, 'localhost'); -client.listbreakpoints((err, body, packet) => { - -}); - -//////////////////////////////////////////////////// -/// zlib tests : http://nodejs.org/api/zlib.html /// -//////////////////////////////////////////////////// - -namespace zlib_tests { - { - const gzipped = zlib.gzipSync('test'); - const unzipped = zlib.gunzipSync(gzipped.toString()); - } - - { - const deflate = zlib.deflateSync('test'); - const inflate = zlib.inflateSync(deflate.toString()); - } -} diff --git a/types/node/v7/ts3.1/tsconfig.json b/types/node/v7/ts3.1/tsconfig.json deleted file mode 100644 index d43afaa663..0000000000 --- a/types/node/v7/ts3.1/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "files": [ - "index.d.ts", - "node-tests.ts" - ], - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": true, - "baseUrl": "../../../", - "typeRoots": [ - "../../../" - ], - "paths": { - "node": [ - "node/v7" - ] - }, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - } -} diff --git a/types/node/v7/ts3.1/tslint.json b/types/node/v7/ts3.1/tslint.json deleted file mode 100644 index bfeeefc3d6..0000000000 --- a/types/node/v7/ts3.1/tslint.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "align": false, - "array-type": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "import-spacing": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "no-consecutive-blank-lines": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-namespace": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-string-throw": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-var-keyword": false, - "object-literal-shorthand": false, - "one-line": false, - "only-arrow-functions": false, - "prefer-const": false, - "prefer-method-signature": false, - "semicolon": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "typedef-whitespace": false, - "unified-signatures": false, - "whitespace": false - } -} diff --git a/types/node/v8/package.json b/types/node/v8/package.json deleted file mode 100644 index 54d5b8743e..0000000000 --- a/types/node/v8/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "private": true, - "types": "index", - "typesVersions": { - "<=3.1": { - "*": [ - "ts3.1/*" - ] - } - } -} diff --git a/types/node/v8/ts3.1/index.d.ts b/types/node/v8/ts3.1/index.d.ts deleted file mode 100644 index 11eeb49026..0000000000 --- a/types/node/v8/ts3.1/index.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.1. - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 - -// NOTE: Augmentations for TypeScript 3.1 and later should use individual files for overrides -// within the respective ~/ts3.1 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.1, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -// tslint:disable-next-line:no-bad-reference -/// - -// TypeScript 2.1-specific augmentations: - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } -interface IteratorResult { } -interface Iterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IterableIterator { } -interface SymbolConstructor { - readonly iterator: symbol; -} -declare var Symbol: SymbolConstructor; - -declare module "util" { - namespace inspect { - const custom: symbol; - } - namespace promisify { - const custom: symbol; - } -} diff --git a/types/node/v8/ts3.1/node-tests.ts b/types/node/v8/ts3.1/node-tests.ts deleted file mode 100644 index 95162307b5..0000000000 --- a/types/node/v8/ts3.1/node-tests.ts +++ /dev/null @@ -1,4136 +0,0 @@ -// NOTE: Disabled to preserve existing tests file: -// tslint:disable:no-namespace -// tslint:disable:no-duplicate-variable -// tslint:disable:no-duplicate-imports -// tslint:disable:no-var-keyword -// tslint:disable:no-inferrable-types -// tslint:disable:prefer-const -// tslint:disable:max-line-length -import assert = require("assert"); -import * as fs from "fs"; -import * as events from "events"; -import events2 = require("events"); -import * as zlib from "zlib"; -import * as url from "url"; -import * as util from "util"; -import * as crypto from "crypto"; -import * as tls from "tls"; -import * as http from "http"; -import * as https from "https"; -import * as net from "net"; -import * as tty from "tty"; -import * as dgram from "dgram"; -import * as querystring from "querystring"; -import * as path from "path"; -import * as readline from "readline"; -import * as childProcess from "child_process"; -import * as cluster from "cluster"; -import * as os from "os"; -import * as vm from "vm"; -import * as console2 from "console"; -import * as string_decoder from "string_decoder"; -import * as stream from "stream"; -import * as timers from "timers"; -import * as repl from "repl"; -import * as v8 from "v8"; -import * as dns from "dns"; -import * as async_hooks from "async_hooks"; -import * as http2 from "http2"; -import * as inspector from "inspector"; -import * as perf_hooks from "perf_hooks"; -import Module = require("module"); - -// Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; - -////////////////////////////////////////////////////////// -/// Global Tests : https://nodejs.org/api/global.html /// -////////////////////////////////////////////////////////// -namespace global_tests { - { - let x: NodeModule; - let y: NodeModule; - x.children.push(y); - x.parent = require.main; - require.main = y; - } -} - -////////////////////////////////////////////////////////// -/// Assert Tests : https://nodejs.org/api/assert.html /// -////////////////////////////////////////////////////////// - -namespace assert_tests { - { - assert(1 + 1 - 2 === 0, "The universe isn't how it should."); - - assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - - assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); - - assert.doesNotThrow(() => { - const b = false; - if (b) { throw new Error("a hammer at your face"); } - }, undefined, "What the...*crunch*"); - - assert.equal(3, "3", "uses == comparator"); - - assert.fail('stuff broke'); - - assert.fail('actual', 'expected', 'message'); - - assert.fail(1, 2, undefined, '>'); - - assert.ifError(0); - - assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - - assert.notEqual(1, 2, "uses != comparator"); - - assert.notStrictEqual(2, "2", "uses === comparator"); - - assert.ok(true); - assert.ok(1); - - assert.strictEqual(1, 1, "uses === comparator"); - - assert.throws(() => { throw new Error("a hammer at your face"); }, undefined, "DODGED IT"); - } -} - -//////////////////////////////////////////////////// -/// Events tests : http://nodejs.org/api/events.html -//////////////////////////////////////////////////// - -namespace events_tests { - let emitter: events.EventEmitter; - let event: string | symbol; - let listener: (...args: any[]) => void; - let any: any; - - { - let result: events.EventEmitter; - - result = emitter.addListener(event, listener); - result = emitter.on(event, listener); - result = emitter.once(event, listener); - result = emitter.prependListener(event, listener); - result = emitter.prependOnceListener(event, listener); - result = emitter.removeListener(event, listener); - result = emitter.removeAllListeners(); - result = emitter.removeAllListeners(event); - result = emitter.setMaxListeners(42); - } - - { - let result: number; - - result = events.EventEmitter.defaultMaxListeners; - result = events.EventEmitter.listenerCount(emitter, event); // deprecated - - result = emitter.getMaxListeners(); - result = emitter.listenerCount(event); - } - - { - let result: Function[]; - - result = emitter.listeners(event); - } - - { - let result: boolean; - - result = emitter.emit(event); - result = emitter.emit(event, any); - result = emitter.emit(event, any, any); - result = emitter.emit(event, any, any, any); - } - - { - let result: Array; - - result = emitter.eventNames(); - } - - { - class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } - } - } - - { - new events2(); - } -} - -//////////////////////////////////////////////////// -/// File system tests : http://nodejs.org/api/fs.html -//////////////////////////////////////////////////// - -namespace fs_tests { - { - fs.writeFile("thebible.txt", - "Do unto others as you would have them do unto you.", - assert.ifError); - - fs.write(1234, "test", () => { }); - - fs.writeFile("Harry Potter", - "\"You be wizzing, Harry,\" jived Dumbledore.", - { - encoding: "ascii" - }, - assert.ifError); - - fs.writeFile("testfile", "content", "utf8", assert.ifError); - - fs.writeFileSync("testfile", "content", "utf8"); - fs.writeFileSync("testfile", "content", { encoding: "utf8" }); - } - - { - fs.appendFile("testfile", "foobar", "utf8", assert.ifError); - fs.appendFile("testfile", "foobar", { encoding: "utf8" }, assert.ifError); - fs.appendFileSync("testfile", "foobar", "utf8"); - fs.appendFileSync("testfile", "foobar", { encoding: "utf8" }); - } - - { - var content: string; - var buffer: Buffer; - var stringOrBuffer: string | Buffer; - var nullEncoding: string | null = null; - var stringEncoding: string | null = 'utf8'; - - content = fs.readFileSync('testfile', 'utf8'); - content = fs.readFileSync('testfile', { encoding: 'utf8' }); - stringOrBuffer = fs.readFileSync('testfile', stringEncoding); - stringOrBuffer = fs.readFileSync('testfile', { encoding: stringEncoding }); - - buffer = fs.readFileSync('testfile'); - buffer = fs.readFileSync('testfile', null); - buffer = fs.readFileSync('testfile', { encoding: null }); - stringOrBuffer = fs.readFileSync('testfile', nullEncoding); - stringOrBuffer = fs.readFileSync('testfile', { encoding: nullEncoding }); - - buffer = fs.readFileSync('testfile', { flag: 'r' }); - - fs.readFile('testfile', 'utf8', (err, data) => content = data); - fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); - fs.readFile('testfile', stringEncoding, (err, data) => stringOrBuffer = data); - fs.readFile('testfile', { encoding: stringEncoding }, (err, data) => stringOrBuffer = data); - - fs.readFile('testfile', (err, data) => buffer = data); - fs.readFile('testfile', null, (err, data) => buffer = data); - fs.readFile('testfile', { encoding: null }, (err, data) => buffer = data); - fs.readFile('testfile', nullEncoding, (err, data) => stringOrBuffer = data); - fs.readFile('testfile', { encoding: nullEncoding }, (err, data) => stringOrBuffer = data); - - fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); - } - - { - var errno: number; - fs.readFile('testfile', (err, data) => { - if (err && err.errno) { - errno = err.errno; - } - }); - } - - { - let listS: string[]; - listS = fs.readdirSync('path'); - listS = fs.readdirSync('path', { encoding: 'utf8' }); - listS = fs.readdirSync('path', { encoding: null }); - listS = fs.readdirSync('path', { encoding: undefined }); - listS = fs.readdirSync('path', 'utf8'); - listS = fs.readdirSync('path', null); - listS = fs.readdirSync('path', undefined); - - let listB: Buffer[]; - listB = fs.readdirSync('path', { encoding: 'buffer' }); - listB = fs.readdirSync("path", 'buffer'); - - let enc = 'buffer'; - fs.readdirSync('path', { encoding: enc }); // $ExpectType string[] | Buffer[] - fs.readdirSync('path', { }); // $ExpectType string[] | Buffer[] - } - - { - fs.mkdtemp('/tmp/foo-', (err, folder) => { - console.log(folder); - // Prints: /tmp/foo-itXde2 - }); - } - - { - var tempDir: string; - tempDir = fs.mkdtempSync('/tmp/foo-'); - } - - { - fs.watch('/tmp/foo-', (event, filename) => { - console.log(event, filename); - }); - - fs.watch('/tmp/foo-', 'utf8', (event, filename) => { - console.log(event, filename); - }); - - fs.watch('/tmp/foo-', { - recursive: true, - persistent: true, - encoding: 'utf8' - }, (event, filename) => { - console.log(event, filename); - }); - } - - { - fs.access('/path/to/folder', (err) => { }); - - fs.access(Buffer.from(''), (err) => { }); - - fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - - fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - - fs.accessSync('/path/to/folder'); - - fs.accessSync(Buffer.from('')); - - fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); - - fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); - } - - { - let s: string; - let b: Buffer; - fs.readlink('/path/to/folder', (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', undefined, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', 'utf8', (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', 'buffer', (err, linkString) => b = linkString); - fs.readlink('/path/to/folder', s, (err, linkString) => typeof linkString === 'string' ? s = linkString : b = linkString); - fs.readlink('/path/to/folder', {}, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', { encoding: undefined }, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', { encoding: 'utf8' }, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', { encoding: 'buffer' }, (err, linkString) => b = linkString); - fs.readlink('/path/to/folder', { encoding: s }, (err, linkString) => typeof linkString === "string" ? s = linkString : b = linkString); - - s = fs.readlinkSync('/path/to/folder'); - s = fs.readlinkSync('/path/to/folder', undefined); - s = fs.readlinkSync('/path/to/folder', 'utf8'); - b = fs.readlinkSync('/path/to/folder', 'buffer'); - const v1 = fs.readlinkSync('/path/to/folder', s); - typeof v1 === "string" ? s = v1 : b = v1; - - s = fs.readlinkSync('/path/to/folder', {}); - s = fs.readlinkSync('/path/to/folder', { encoding: undefined }); - s = fs.readlinkSync('/path/to/folder', { encoding: 'utf8' }); - b = fs.readlinkSync('/path/to/folder', { encoding: 'buffer' }); - const v2 = fs.readlinkSync('/path/to/folder', { encoding: s }); - typeof v2 === "string" ? s = v2 : b = v2; - } - - { - let s: string; - let b: Buffer; - fs.realpath('/path/to/folder', (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath); - fs.realpath('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath); - fs.realpath('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath); - fs.realpath('/path/to/folder', { encoding: s }, (err, resolvedPath) => typeof resolvedPath === "string" ? s = resolvedPath : b = resolvedPath); - - s = fs.realpathSync('/path/to/folder'); - s = fs.realpathSync('/path/to/folder', undefined); - s = fs.realpathSync('/path/to/folder', 'utf8'); - b = fs.realpathSync('/path/to/folder', 'buffer'); - const v1 = fs.realpathSync('/path/to/folder', s); - typeof v1 === "string" ? s = v1 : b = v1; - - s = fs.realpathSync('/path/to/folder', {}); - s = fs.realpathSync('/path/to/folder', { encoding: undefined }); - s = fs.realpathSync('/path/to/folder', { encoding: 'utf8' }); - b = fs.realpathSync('/path/to/folder', { encoding: 'buffer' }); - const v2 = fs.realpathSync('/path/to/folder', { encoding: s }); - typeof v2 === "string" ? s = v2 : b = v2; - } - - { - fs.copyFile('/path/to/src', '/path/to/dest', (err) => console.error(err)); - fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL, (err) => console.error(err)); - - fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL); - - const cf = util.promisify(fs.copyFile); - cf('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL).then(console.log); - } -} - -/////////////////////////////////////////////////////// -/// Buffer tests : https://nodejs.org/api/buffer.html -/////////////////////////////////////////////////////// - -function bufferTests() { - var utf8Buffer = new Buffer('test'); - var base64Buffer = new Buffer('', 'base64'); - var octets: Uint8Array = null; - var octetBuffer = new Buffer(octets); - var sharedBuffer = new Buffer(octets.buffer); - var copiedBuffer = new Buffer(utf8Buffer); - console.log(Buffer.isBuffer(octetBuffer)); - console.log(Buffer.isEncoding('utf8')); - console.log(Buffer.byteLength('xyz123')); - console.log(Buffer.byteLength('xyz123', 'ascii')); - var result1 = Buffer.concat([utf8Buffer, base64Buffer]); - var result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999); - - // Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64() - { - const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); - buf.swap16(); - buf.swap32(); - buf.swap64(); - } - - // Class Method: Buffer.from(data) - { - // Array - const buf1: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); - // Buffer - const buf2: Buffer = Buffer.from(buf1); - // String - const buf3: Buffer = Buffer.from('this is a tést'); - // ArrayBuffer - const arr: Uint16Array = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; - const buf4: Buffer = Buffer.from(arr.buffer); - } - - // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) - { - const arr: Uint16Array = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; - - let buf: Buffer; - buf = Buffer.from(arr.buffer, 1); - buf = Buffer.from(arr.buffer, 0, 1); - } - - // Class Method: Buffer.from(str[, encoding]) - { - const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); - } - - // Class Method: Buffer.alloc(size[, fill[, encoding]]) - { - const buf1: Buffer = Buffer.alloc(5); - const buf2: Buffer = Buffer.alloc(5, 'a'); - const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); - } - // Class Method: Buffer.allocUnsafe(size) - { - const buf: Buffer = Buffer.allocUnsafe(5); - } - // Class Method: Buffer.allocUnsafeSlow(size) - { - const buf: Buffer = Buffer.allocUnsafeSlow(10); - } - - // Class Method byteLenght - { - let len: number; - len = Buffer.byteLength("foo"); - len = Buffer.byteLength("foo", "utf8"); - - const b = Buffer.from("bar"); - len = Buffer.byteLength(b); - len = Buffer.byteLength(b, "utf16le"); - - const ab = new ArrayBuffer(15); - len = Buffer.byteLength(ab); - len = Buffer.byteLength(ab, "ascii"); - - const dv = new DataView(ab); - len = Buffer.byteLength(dv); - len = Buffer.byteLength(dv, "utf16le"); - } - - // Class Method poolSize - { - let s: number; - s = Buffer.poolSize; - Buffer.poolSize = 4096; - } - - // Test that TS 1.6 works with the 'as Buffer' annotation - // on isBuffer. - var a: Buffer | number; - a = new Buffer(10); - if (Buffer.isBuffer(a)) { - a.writeUInt8(3, 4); - } - - // write* methods return offsets. - var b = new Buffer(16); - var result: number = b.writeUInt32LE(0, 0); - result = b.writeUInt16LE(0, 4); - result = b.writeUInt8(0, 6); - result = b.writeInt8(0, 7); - result = b.writeDoubleLE(0, 8); - - // fill returns the input buffer. - b.fill('a').fill('b'); - - { - let buffer = new Buffer('123'); - let index: number; - index = buffer.indexOf("23"); - index = buffer.indexOf("23", 1); - index = buffer.indexOf("23", 1, "utf8"); - index = buffer.indexOf(23); - index = buffer.indexOf(buffer); - } - - { - let buffer = new Buffer('123'); - let index: number; - index = buffer.lastIndexOf("23"); - index = buffer.lastIndexOf("23", 1); - index = buffer.lastIndexOf("23", 1, "utf8"); - index = buffer.lastIndexOf(23); - index = buffer.lastIndexOf(buffer); - } - - { - let buffer = new Buffer('123'); - let val: [number, number]; - - /* comment out for --target es5 - for (let entry of buffer.entries()) { - val = entry; - } - */ - } - - { - let buffer = new Buffer('123'); - let includes: boolean; - includes = buffer.includes("23"); - includes = buffer.includes("23", 1); - includes = buffer.includes("23", 1, "utf8"); - includes = buffer.includes(23); - includes = buffer.includes(23, 1); - includes = buffer.includes(23, 1, "utf8"); - includes = buffer.includes(buffer); - includes = buffer.includes(buffer, 1); - includes = buffer.includes(buffer, 1, "utf8"); - } - - { - let buffer = new Buffer('123'); - let val: number; - - /* comment out for --target es5 - for (let key of buffer.keys()) { - val = key; - } - */ - } - - { - let buffer = new Buffer('123'); - let val: number; - - /* comment out for --target es5 - for (let value of buffer.values()) { - val = value; - } - */ - } - - // Imported Buffer from buffer module works properly - { - let b = new ImportedBuffer('123'); - b.writeUInt8(0, 6); - let sb = new ImportedSlowBuffer(43); - b.writeUInt8(0, 6); - } - - // Buffer has Uint8Array's buffer field (an ArrayBuffer). - { - let buffer = new Buffer('123'); - let octets = new Uint8Array(buffer.buffer); - } - - // Buffer module, transcode function - { - transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer - - const source: TranscodeEncoding = 'utf8'; - const target: TranscodeEncoding = 'ascii'; - transcode(Buffer.from('€'), source, target); // $ExpectType Buffer - } -} - -//////////////////////////////////////////////////// -/// Url tests : http://nodejs.org/api/url.html -//////////////////////////////////////////////////// - -namespace url_tests { - { - url.format(url.parse('http://www.example.com/xyz')); - - url.format('http://www.example.com/xyz'); - - // https://google.com/search?q=you're%20a%20lizard%2C%20gary - url.format({ - protocol: 'https', - host: "google.com", - pathname: 'search', - query: { q: "you're a lizard, gary" } - }); - - const myURL = new url.URL('https://a:b@你好你好?abc#foo'); - url.format(myURL, { fragment: false, unicode: true, auth: false }); - } - - { - const helloUrl = url.parse('http://example.com/?hello=world', true); - let helloQuery = helloUrl.query['hello']; - assert.equal(helloUrl.query['hello'], 'world'); - - let strUrl = url.parse('http://example.com/?hello=world'); - let queryStr: string = strUrl.query; - - strUrl = url.parse('http://example.com/?hello=world', false); - queryStr = strUrl.query; - - function getBoolean(): boolean { return false; } - const urlUrl = url.parse('http://example.com/?hello=world', getBoolean()); - if (typeof(urlUrl.query) === 'string') { - queryStr = urlUrl.query; - } else if (urlUrl.query) { - helloQuery = urlUrl.query['hello']; - } - } - - { - const ascii: string = url.domainToASCII('español.com'); - const unicode: string = url.domainToUnicode('xn--espaol-zwa.com'); - } - - { - let myURL = new url.URL('https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.hash, '#bar'); - assert.equal(myURL.host, 'example.org:81'); - assert.equal(myURL.hostname, 'example.org'); - assert.equal(myURL.href, 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.origin, 'https://example.org:81'); - assert.equal(myURL.password, 'thepwd'); - assert.equal(myURL.username, 'theuser'); - assert.equal(myURL.pathname, '/foo/path'); - assert.equal(myURL.port, "81"); - assert.equal(myURL.protocol, "https:"); - assert.equal(myURL.search, "?query=string"); - assert.equal(myURL.toString(), 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert(myURL.searchParams instanceof url.URLSearchParams); - - myURL.host = 'example.org:82'; - myURL.hostname = 'example.com'; - myURL.href = 'http://other.com'; - myURL.hash = 'baz'; - myURL.password = "otherpwd"; - myURL.username = "otheruser"; - myURL.pathname = "/otherPath"; - myURL.port = "82"; - myURL.protocol = "http"; - myURL.search = "a=b"; - assert.equal(myURL.href, 'http://otheruser:otherpwd@other.com:82/otherPath?a=b#baz'); - - myURL = new url.URL('/foo', 'https://example.org/'); - assert.equal(myURL.href, 'https://example.org/foo'); - assert.equal(myURL.toJSON(), myURL.href); - } - - { - const searchParams = new url.URLSearchParams('abc=123'); - - assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { - assert.equal(name, 'abc'); - assert.equal(value, '123'); - assert.equal(me, searchParams); - }); - - assert.equal(searchParams.get('abc'), '123'); - - searchParams.append('abc', 'xyz'); - - assert.deepEqual(searchParams.getAll('abc'), ['123', 'xyz']); - - const entries = searchParams.entries(); - assert.deepEqual(entries.next(), { value: ["abc", "123"], done: false }); - assert.deepEqual(entries.next(), { value: ["abc", "xyz"], done: false }); - assert.deepEqual(entries.next(), { value: undefined, done: true }); - - const keys = searchParams.keys(); - assert.deepEqual(keys.next(), { value: "abc", done: false }); - assert.deepEqual(keys.next(), { value: "abc", done: false }); - assert.deepEqual(keys.next(), { value: undefined, done: true }); - - const values = searchParams.values(); - assert.deepEqual(values.next(), { value: "123", done: false }); - assert.deepEqual(values.next(), { value: "xyz", done: false }); - assert.deepEqual(values.next(), { value: undefined, done: true }); - - searchParams.set('abc', 'b'); - assert.deepEqual(searchParams.getAll('abc'), ['b']); - - searchParams.delete('a'); - assert(!searchParams.has('a')); - assert.equal(searchParams.get('a'), null); - - searchParams.sort(); - } - - { - const searchParams = new url.URLSearchParams({ - user: 'abc', - query: ['first', 'second'] - }); - - assert.equal(searchParams.toString(), 'user=abc&query=first%2Csecond'); - assert.deepEqual(searchParams.getAll('query'), ['first,second']); - } - - { - // Using an array - let params = new url.URLSearchParams([ - ['user', 'abc'], - ['query', 'first'], - ['query', 'second'] - ]); - assert.equal(params.toString(), 'user=abc&query=first&query=second'); - } -} - -///////////////////////////////////////////////////// -/// util tests : https://nodejs.org/api/util.html /// -///////////////////////////////////////////////////// - -namespace util_tests { - { - // Old and new util.inspect APIs - util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], false, null); - util.inspect(["This is nice"], { - colors: true, - depth: 5, - customInspect: false, - showProxy: true, - maxArrayLength: 10, - breakLength: 20 - }); - util.inspect(["This is nice"], { - colors: true, - depth: null, - customInspect: false, - showProxy: true, - maxArrayLength: null, - breakLength: Infinity - }); - assert(typeof util.inspect.custom === 'symbol'); - - // util.callbackify - // tslint:disable-next-line no-unnecessary-class - class callbackifyTest { - static fn(): Promise { - assert(arguments.length === 0); - - return Promise.resolve(); - } - - static fnE(): Promise { - assert(arguments.length === 0); - - return Promise.reject(new Error('fail')); - } - - static fnT1(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.resolve(); - } - - static fnT1E(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.reject(new Error('fail')); - } - - static fnTResult(): Promise { - assert(arguments.length === 0); - - return Promise.resolve('result'); - } - - static fnTResultE(): Promise { - assert(arguments.length === 0); - - return Promise.reject(new Error('fail')); - } - - static fnT1TResult(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.resolve('result'); - } - - static fnT1TResultE(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.reject(new Error('fail')); - } - - static test(): void { - var cfn = util.callbackify(callbackifyTest.fn); - var cfnE = util.callbackify(callbackifyTest.fnE); - var cfnT1 = util.callbackify(callbackifyTest.fnT1); - var cfnT1E = util.callbackify(callbackifyTest.fnT1E); - var cfnTResult = util.callbackify(callbackifyTest.fnTResult); - var cfnTResultE = util.callbackify(callbackifyTest.fnTResultE); - var cfnT1TResult = util.callbackify(callbackifyTest.fnT1TResult); - var cfnT1TResultE = util.callbackify(callbackifyTest.fnT1TResultE); - - cfn((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); - cfnE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - cfnT1('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); - cfnT1E('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - cfnTResult((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); - cfnTResultE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - cfnT1TResult('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); - cfnT1TResultE('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - } - } - callbackifyTest.test(); - - // util.promisify - var readPromised = util.promisify(fs.readFile); - var sampleRead: Promise = readPromised(__filename).then((data: Buffer): void => { }).catch((error: Error): void => { }); - var arg0: () => Promise = util.promisify((cb: (err: Error, result: number) => void): void => { }); - var arg0NoResult: () => Promise = util.promisify((cb: (err: Error) => void): void => { }); - var arg1: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error, result: number) => void): void => { }); - var arg1NoResult: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error) => void): void => { }); - // The following test requires typescript >= 2.4, but definitions currently tested with typescript@2.1 - // var cbOptionalError: () => Promise = util.promisify((cb: (err?: Error | null) => void): void => { cb(); }); - assert(typeof util.promisify.custom === 'symbol'); - // util.deprecate - const foo = () => {}; - // $ExpectType () => void - util.deprecate(foo, 'foo() is deprecated, use bar() instead'); - // $ExpectType (fn: T, message: string, code?: string) => T - util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); - // $ExpectType (fn: T, message: string, code?: string) => T - util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead', 'DEP0001'); - - // util.TextDecoder() - var td = new util.TextDecoder(); - new util.TextDecoder("utf-8"); - new util.TextDecoder("utf-8", { fatal: true }); - new util.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); - var ignoreBom: boolean = td.ignoreBOM; - var fatal: boolean = td.fatal; - var encoding: string = td.encoding; - td.decode(new Int8Array(1)); - td.decode(new Int16Array(1)); - td.decode(new Int32Array(1)); - td.decode(new Uint8Array(1)); - td.decode(new Uint16Array(1)); - td.decode(new Uint32Array(1)); - td.decode(new Uint8ClampedArray(1)); - td.decode(new Float32Array(1)); - td.decode(new Float64Array(1)); - td.decode(new DataView(new Int8Array(1).buffer)); - td.decode(new ArrayBuffer(1)); - td.decode(null); - td.decode(null, { stream: true }); - td.decode(new Int8Array(1), { stream: true }); - var decode: string = td.decode(new Int8Array(1)); - - // util.TextEncoder() - var te = new util.TextEncoder(); - var teEncoding: string = te.encoding; - var teEncodeRes: Uint8Array = te.encode("TextEncoder"); - } -} - -//////////////////////////////////////////////////// -/// Stream tests : http://nodejs.org/api/stream.html -//////////////////////////////////////////////////// - -// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options -function stream_readable_pipe_test() { - var rs = fs.createReadStream(Buffer.from('file.txt')); - var r = fs.createReadStream('file.txt'); - var z = zlib.createGzip({ finishFlush: zlib.constants.Z_FINISH }); - var w = fs.createWriteStream('file.txt.gz'); - - assert(typeof z.bytesRead === 'number'); - assert(typeof r.bytesRead === 'number'); - assert(typeof r.path === 'string'); - assert(rs.path instanceof Buffer); - - r.pipe(z).pipe(w); - - z.flush(); - r.close(); - z.close(); - rs.close(); -} - -// helpers -const compressMe = new Buffer("some data"); -const compressMeString = "compress me!"; - -zlib.deflate(compressMe, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflate(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMeString, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMeString, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflate(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -const inflated = zlib.inflateSync(zlib.deflateSync(compressMe)); -const inflatedString = zlib.inflateSync(zlib.deflateSync(compressMeString)); - -zlib.deflateRaw(compressMe, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); -zlib.deflateRaw(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -zlib.deflateRaw(compressMeString, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); -zlib.deflateRaw(compressMeString, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -const inflatedRaw: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMe)); -const inflatedRawString: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMeString)); - -zlib.gzip(compressMe, (err: Error, result: Buffer) => zlib.gunzip(result, (err: Error, result: Buffer) => result)); -zlib.gzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.gunzip(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -const gunzipped: Buffer = zlib.gunzipSync(zlib.gzipSync(compressMe)); - -zlib.unzip(compressMe, (err: Error, result: Buffer) => result); -zlib.unzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result); -const unzipped: Buffer = zlib.unzipSync(compressMe); - -// Simplified constructors -function simplified_stream_ctor_test() { - new stream.Readable({ - read(size) { - size.toFixed(); - }, - destroy(error, cb) { - error.stack; - cb(error); - } - }); - - new stream.Writable({ - write(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); - }, - writev(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); - }, - destroy(error, cb) { - error.stack; - cb(error); - }, - final(cb) { - cb(null); - } - }); - - new stream.Duplex({ - read(size) { - size.toFixed(); - }, - write(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); - }, - writev(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); - }, - destroy(error, cb) { - error.stack; - cb(error); - }, - readableObjectMode: true, - writableObjectMode: true - }); - - new stream.Transform({ - transform(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); - }, - flush(cb) { - cb(); - }, - read(size) { - size.toFixed(); - }, - write(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); - }, - writev(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); - }, - destroy(error, cb) { - error.stack; - cb(error); - }, - allowHalfOpen: true, - readableObjectMode: true, - writableObjectMode: true - }); -} - -//////////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html /// -//////////////////////////////////////////////////////// - -namespace crypto_tests { - { - // crypto_hash_string_test - var hashResult: string = crypto.createHash('md5').update('world').digest('hex'); - } - - { - // crypto_hash_buffer_test - var hashResult: string = crypto.createHash('md5') - .update(new Buffer('world')).digest('hex'); - } - - { - // crypto_hash_dataview_test - var hashResult: string = crypto.createHash('md5') - .update(new DataView(new Buffer('world').buffer)).digest('hex'); - } - - { - // crypto_hmac_string_test - var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); - } - - { - // crypto_hmac_buffer_test - var hmacResult: string = crypto.createHmac('md5', 'hello') - .update(new Buffer('world')).digest('hex'); - } - - { - // crypto_hmac_dataview_test - var hmacResult: string = crypto.createHmac('md5', 'hello') - .update(new DataView(new Buffer('world').buffer)).digest('hex'); - } - - { - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer | string = hmac.read(); - }); - } - - { - // crypto_cipher_decipher_string_test - let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - let clearText: string = "This is the clear text."; - let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - let cipherText: string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); - - let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - let clearText2: string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); - - assert.equal(clearText2, clearText); - } - - { - // crypto_cipher_decipher_buffer_test - let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - let cipherBuffers: Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); - - let cipherText: Buffer = Buffer.concat(cipherBuffers); - - let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - let decipherBuffers: Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - let clearText2: Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); - } - - { - // crypto_cipher_decipher_dataview_test - let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - let clearText: DataView = new DataView( - new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]).buffer); - let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - let cipherBuffers: Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); - - let cipherText: DataView = new DataView(Buffer.concat(cipherBuffers).buffer); - - let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - let decipherBuffers: Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - let clearText2: Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); - } - - { - let buffer1: Buffer = new Buffer([1, 2, 3, 4, 5]); - let buffer2: Buffer = new Buffer([1, 2, 3, 4, 5]); - let buffer3: Buffer = new Buffer([5, 4, 3, 2, 1]); - - assert(crypto.timingSafeEqual(buffer1, buffer2)); - assert(!crypto.timingSafeEqual(buffer1, buffer3)); - } - - { - let buffer: Buffer = new Buffer(10); - crypto.randomFillSync(buffer); - crypto.randomFillSync(buffer, 2); - crypto.randomFillSync(buffer, 2, 3); - - crypto.randomFill(buffer, (err: Error, buf: Buffer) => void {}); - crypto.randomFill(buffer, 2, (err: Error, buf: Buffer) => void {}); - crypto.randomFill(buffer, 2, 3, (err: Error, buf: Buffer) => void {}); - - let arr: Uint8Array = new Uint8Array(10); - crypto.randomFillSync(arr); - crypto.randomFillSync(arr, 2); - crypto.randomFillSync(arr, 2, 3); - - crypto.randomFill(arr, (err: Error, buf: Uint8Array) => void {}); - crypto.randomFill(arr, 2, (err: Error, buf: Uint8Array) => void {}); - crypto.randomFill(arr, 2, 3, (err: Error, buf: Uint8Array) => void {}); - } -} - -////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html /// -////////////////////////////////////////////////// - -namespace tls_tests { - { - var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", - }); - var blah = ctx.context; - - var connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 - }; - var tlsSocket = tls.connect(connOpts); - - const ciphers: string[] = tls.getCiphers(); - const curve: string = tls.DEFAULT_ECDH_CURVE; - } - - { - let _server: tls.Server; - let _boolean: boolean; - let _func1 = (err: Error, resp: Buffer) => { }; - let _func2 = (err: Error, sessionData: any) => { }; - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - */ - - _server = _server.addListener("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.addListener("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }); - _server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }); - _server = _server.addListener("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }); - _server = _server.addListener("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - let _err: Error; - let _tlsSocket: tls.TLSSocket; - let _any: any; - let _func: Function; - let _buffer: Buffer; - _boolean = _server.emit("tlsClientError", _err, _tlsSocket); - _boolean = _server.emit("newSession", _any, _any, _func1); - _boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func); - _boolean = _server.emit("resumeSession", _any, _func2); - _boolean = _server.emit("secureConnection", _tlsSocket); - - _server = _server.on("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.on("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }); - _server = _server.on("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }); - _server = _server.on("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }); - _server = _server.on("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.once("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.once("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }); - _server = _server.once("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }); - _server = _server.once("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }); - _server = _server.once("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.prependListener("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.prependListener("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }); - _server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }); - _server = _server.prependListener("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }); - _server = _server.prependListener("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }); - _server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }); - _server = _server.prependOnceListener("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }); - _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - // close callback parameter is optional - _server = _server.close(); - - // close callback parameter can be either nothing (undefined) or an error - _server = _server.close(() => { }); - _server = _server.close((err) => { - if (typeof err !== 'undefined') { const _err: Error = err; } - }); - } - - { - let _TLSSocket: tls.TLSSocket; - let _boolean: boolean; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - */ - - _TLSSocket = _TLSSocket.addListener("OCSPResponse", (response) => { - let _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.addListener("secureConnect", () => { }); - - let _buffer: Buffer; - _boolean = _TLSSocket.emit("OCSPResponse", _buffer); - _boolean = _TLSSocket.emit("secureConnect"); - - _TLSSocket = _TLSSocket.on("OCSPResponse", (response) => { - let _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.on("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.once("OCSPResponse", (response) => { - let _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.once("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependListener("OCSPResponse", (response) => { - let _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.prependListener("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependOnceListener("OCSPResponse", (response) => { - let _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.prependOnceListener("secureConnect", () => { }); - } -} - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html /// -//////////////////////////////////////////////////// - -namespace http_tests { - // http Server - { - var server: http.Server = new http.Server(); - - // test public props - const maxHeadersCount: number = server.maxHeadersCount; - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } - - // http IncomingMessage - // http ServerResponse - { - // incoming - var incoming: http.IncomingMessage = new http.IncomingMessage(new net.Socket()); - - incoming.setEncoding('utf8'); - - // stream - incoming.pause(); - incoming.resume(); - - // response - var res: http.ServerResponse = new http.ServerResponse(incoming); - - // test headers - res.setHeader('Content-Type', 'text/plain'); - var bool: boolean = res.hasHeader('Content-Type'); - var headers: string[] = res.getHeaderNames(); - - // trailers - res.addTrailers([ - ['x-fOo', 'xOxOxOx'], - ['x-foO', 'OxOxOxO'], - ['X-fOo', 'xOxOxOx'], - ['X-foO', 'OxOxOxO'] - ]); - res.addTrailers({ 'x-foo': 'bar' }); - - // writeHead - res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n'); - res.writeHead(200, { 'Transfer-Encoding': 'chunked' }); - res.writeHead(200); - - // write string - res.write('Part of my res.'); - // write buffer - const chunk = Buffer.alloc(16390, 'Й'); - req.write(chunk); - res.write(chunk, 'hex'); - - // end - res.end("end msg"); - // without msg - res.end(); - - // flush - res.flushHeaders(); - } - - // http ClientRequest - { - var req: http.ClientRequest = new http.ClientRequest("https://www.google.com"); - var req: http.ClientRequest = new http.ClientRequest(new url.URL("https://www.google.com")); - var req: http.ClientRequest = new http.ClientRequest({ path: 'http://0.0.0.0' }); - - // header - req.setHeader('Content-Type', 'text/plain'); - var bool: boolean = req.hasHeader('Content-Type'); - var headers: string[] = req.getHeaderNames(); - req.removeHeader('Date'); - - // write - const chunk = Buffer.alloc(16390, 'Й'); - req.write(chunk); - req.write('a'); - req.end(); - - // abort - req.abort(); - - // connection - req.connection.on('pause', () => { }); - - // event - req.on('data', () => { }); - } - - { - // Status codes - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; - } - - { - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); - - var agent: http.Agent = http.globalAgent; - - http.request({ agent: false }); - http.request({ agent }); - http.request({ agent: undefined }); - } - - { - http.request('http://www.example.com/xyz'); - } - - { - // Make sure .listen() and .close() return a Server instance - http.createServer().listen(0).close().address(); - net.createServer().listen(0).close().address(); - } - - { - var request = http.request({ path: 'http://0.0.0.0' }); - request.once('error', () => { }); - request.setNoDelay(true); - request.abort(); - } - - // http request options - { - const requestOpts: http.RequestOptions = { - timeout: 30000 - }; - - const clientArgs: http.ClientRequestArgs = { - timeout: 30000 - }; - } - - // http headers - { - const headers: http.IncomingHttpHeaders = { - 'content-type': 'application/json', - 'set-cookie': [ 'type=ninja', 'language=javascript' ] - }; - } -} - -////////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html /// -////////////////////////////////////////////////////// - -namespace https_tests { - var agent: https.Agent = new https.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256, - maxCachedSessions: 100 - }); - - var agent: https.Agent = https.globalAgent; - - https.request({ - agent: false - }); - https.request({ - agent - }); - https.request({ - agent: undefined - }); - - https.request('http://www.example.com/xyz'); - - https.globalAgent.options.ca = []; - - { - const server = new https.Server(); - - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } -} - -//////////////////////////////////////////////////// -/// TTY tests : http://nodejs.org/api/tty.html -//////////////////////////////////////////////////// - -namespace tty_tests { - let rs: tty.ReadStream; - let ws: tty.WriteStream; - - let rsIsRaw: boolean = rs.isRaw; - rs.setRawMode(true); - - let wsColumns: number = ws.columns; - let wsRows: number = ws.rows; - - let isTTY: boolean = tty.isatty(1); -} - -//////////////////////////////////////////////////// -/// Dgram tests : http://nodejs.org/api/dgram.html -//////////////////////////////////////////////////// - -namespace dgram_tests { - { - var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { - }); - ds.bind(); - ds.bind(41234); - ds.bind(4123, 'localhost'); - ds.bind(4123, 'localhost', () => { }); - ds.bind(4123, () => { }); - ds.bind(() => { }); - var ai: dgram.AddressInfo = ds.address(); - ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { - }); - ds.send(new Buffer("hello"), 5000, "127.0.0.1"); - ds.setMulticastInterface("127.0.0.1"); - ds = dgram.createSocket({ type: "udp4", reuseAddr: true, recvBufferSize: 1000, sendBufferSize: 1000, lookup: dns.lookup }); - } - - { - let _socket: dgram.Socket; - let _boolean: boolean; - let _err: Error; - let _str: string; - let _rinfo: dgram.AddressInfo; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - */ - - _socket = _socket.addListener("close", () => { }); - _socket = _socket.addListener("error", (err) => { - let _err: Error = err; - }); - _socket = _socket.addListener("listening", () => { }); - _socket = _socket.addListener("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }); - - _boolean = _socket.emit("close"); - _boolean = _socket.emit("error", _err); - _boolean = _socket.emit("listening"); - _boolean = _socket.emit("message", _str, _rinfo); - - _socket = _socket.on("close", () => { }); - _socket = _socket.on("error", (err) => { - let _err: Error = err; - }); - _socket = _socket.on("listening", () => { }); - _socket = _socket.on("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }); - - _socket = _socket.once("close", () => { }); - _socket = _socket.once("error", (err) => { - let _err: Error = err; - }); - _socket = _socket.once("listening", () => { }); - _socket = _socket.once("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }); - - _socket = _socket.prependListener("close", () => { }); - _socket = _socket.prependListener("error", (err) => { - let _err: Error = err; - }); - _socket = _socket.prependListener("listening", () => { }); - _socket = _socket.prependListener("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }); - - _socket = _socket.prependOnceListener("close", () => { }); - _socket = _socket.prependOnceListener("error", (err) => { - let _err: Error = err; - }); - _socket = _socket.prependOnceListener("listening", () => { }); - _socket = _socket.prependOnceListener("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; - }); - } - - { - let ds: dgram.Socket = dgram.createSocket({ - type: 'udp4', - recvBufferSize: 10000, - sendBufferSize: 15000 - }); - - let size: number; - size = ds.getRecvBufferSize(); - ds.setRecvBufferSize(size); - size = ds.getSendBufferSize(); - ds.setSendBufferSize(size); - } -} - -//////////////////////////////////////////////////// -/// Querystring tests : https://nodejs.org/api/querystring.html -//////////////////////////////////////////////////// - -namespace querystring_tests { - interface SampleObject { a: string; b: number; } - - { - let obj: SampleObject; - let sep: string; - let eq: string; - let options: querystring.StringifyOptions; - let result: string; - - result = querystring.stringify(obj); - result = querystring.stringify(obj, sep); - result = querystring.stringify(obj, sep, eq); - result = querystring.stringify(obj, sep, eq); - result = querystring.stringify(obj, sep, eq, options); - } - - { - let str: string; - let sep: string; - let eq: string; - let options: querystring.ParseOptions; - let result: SampleObject; - - result = querystring.parse(str); - result = querystring.parse(str, sep); - result = querystring.parse(str, sep, eq); - result = querystring.parse(str, sep, eq, options); - } - - { - let str: string; - let result: string; - - result = querystring.escape(str); - result = querystring.unescape(str); - } -} - -//////////////////////////////////////////////////// -/// path tests : http://nodejs.org/api/path.html -//////////////////////////////////////////////////// - -namespace path_tests { - path.normalize('/foo/bar//baz/asdf/quux/..'); - - path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); - // returns - // '/foo/bar/baz/asdf' - - try { - path.join('foo', 'bar'); - } catch (error) { } - - path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile'); - // Is similar to: - // - // cd foo/bar - // cd /tmp/file/ - // cd .. - // cd a/../subfile - // pwd - - path.resolve('/foo/bar', './baz'); - // returns - // '/foo/bar/baz' - - path.resolve('/foo/bar', '/tmp/file/'); - // returns - // '/tmp/file' - - path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); - // if currently in /home/myself/node, it returns - // '/home/myself/node/wwwroot/static_files/gif/image.gif' - - path.isAbsolute('/foo/bar'); // true - path.isAbsolute('/baz/..'); // true - path.isAbsolute('qux/'); // false - path.isAbsolute('.'); // false - - path.isAbsolute('//server'); // true - path.isAbsolute('C:/foo/..'); // true - path.isAbsolute('bar\\baz'); // false - path.isAbsolute('.'); // false - - path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'); - // returns - // '..\\..\\impl\\bbb' - - path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); - // returns - // '../../impl/bbb' - - path.dirname('/foo/bar/baz/asdf/quux'); - // returns - // '/foo/bar/baz/asdf' - - path.basename('/foo/bar/baz/asdf/quux.html'); - // returns - // 'quux.html' - - path.basename('/foo/bar/baz/asdf/quux.html', '.html'); - // returns - // 'quux' - - path.extname('index.html'); - // returns - // '.html' - - path.extname('index.coffee.md'); - // returns - // '.md' - - path.extname('index.'); - // returns - // '.' - - path.extname('index'); - // returns - // '' - - 'foo/bar/baz'.split(path.sep); - // returns - // ['foo', 'bar', 'baz'] - - 'foo\\bar\\baz'.split(path.sep); - // returns - // ['foo', 'bar', 'baz'] - - process.env["PATH"]; // $ExpectType string - - path.parse('/home/user/dir/file.txt'); - // returns - // { - // root : "/", - // dir : "/home/user/dir", - // base : "file.txt", - // ext : ".txt", - // name : "file" - // } - - path.parse('C:\\path\\dir\\index.html'); - // returns - // { - // root : "C:\", - // dir : "C:\path\dir", - // base : "index.html", - // ext : ".html", - // name : "index" - // } - - path.format({ - root: "/", - dir: "/home/user/dir", - base: "file.txt", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - path.format({ - root: "/", - dir: "/home/user/dir", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - path.format({ - dir: "/home/user/dir", - base: "file.txt" - }); - // returns - // '/home/user/dir/file.txt' - - path.posix.format({ - root: "/", - dir: "/home/user/dir", - base: "file.txt", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - path.posix.format({ - dir: "/home/user/dir", - base: "file.txt" - }); - // returns - // '/home/user/dir/file.txt' - - path.win32.format({ - root: "C:\\", - dir: "C:\\home\\user\\dir", - ext: ".txt", - name: "file" - }); - // returns - // 'C:\home\user\dir\file.txt' - - path.win32.format({ - dir: "C:\\home\\user\\dir", - base: "file.txt" - }); - // returns - // 'C:\home\user\dir\file.txt' -} - -//////////////////////////////////////////////////// -/// readline tests : https://nodejs.org/api/readline.html -//////////////////////////////////////////////////// - -namespace readline_tests { - let rl: readline.ReadLine; - - { - let options: readline.ReadLineOptions; - let input: NodeJS.ReadableStream; - let output: NodeJS.WritableStream; - let completer: readline.Completer; - let terminal: boolean; - - let result: readline.ReadLine; - - result = readline.createInterface(options); - result = readline.createInterface(input); - result = readline.createInterface(input, output); - result = readline.createInterface(input, output, completer); - result = readline.createInterface(input, output, completer, terminal); - result = readline.createInterface({ - input, - completer(str: string): readline.CompleterResult { - return [['test'], 'test']; - } - }); - result = readline.createInterface({ - input, - completer(str: string, callback: (err: any, result: readline.CompleterResult) => void): any { - callback(null, [['test'], 'test']); - } - }); - } - - { - let prompt: string; - - rl.setPrompt(prompt); - } - - { - let preserveCursor: boolean; - - rl.prompt(); - rl.prompt(preserveCursor); - } - - { - let query: string; - let callback: (answer: string) => void; - - rl.question(query, callback); - } - - { - let result: readline.ReadLine; - - result = rl.pause(); - } - - { - let result: readline.ReadLine; - - result = rl.resume(); - } - - { - rl.close(); - } - - { - let data: string | Buffer; - let key: readline.Key; - - rl.write(data); - rl.write(null, key); - } - - { - let stream: NodeJS.WritableStream; - let x: number; - let y: number; - - readline.cursorTo(stream, x); - readline.cursorTo(stream, x, y); - } - - { - let stream: NodeJS.ReadableStream; - let readLineInterface: readline.ReadLine; - - readline.emitKeypressEvents(stream); - readline.emitKeypressEvents(stream, readLineInterface); - } - - { - let stream: NodeJS.WritableStream; - let dx: number | string; - let dy: number | string; - - readline.moveCursor(stream, dx, dy); - } - - { - let stream: NodeJS.WritableStream; - let dir: number; - - readline.clearLine(stream, dir); - } - - { - let stream: NodeJS.WritableStream; - - readline.clearScreenDown(stream); - } - - { - let _rl: readline.ReadLine; - let _boolean: boolean; - - _rl = _rl.addListener("close", () => { }); - _rl = _rl.addListener("line", (input) => { - let _input: any = input; - }); - _rl = _rl.addListener("pause", () => { }); - _rl = _rl.addListener("resume", () => { }); - _rl = _rl.addListener("SIGCONT", () => { }); - _rl = _rl.addListener("SIGINT", () => { }); - _rl = _rl.addListener("SIGTSTP", () => { }); - - _boolean = _rl.emit("close", () => { }); - _boolean = _rl.emit("line", () => { }); - _boolean = _rl.emit("pause", () => { }); - _boolean = _rl.emit("resume", () => { }); - _boolean = _rl.emit("SIGCONT", () => { }); - _boolean = _rl.emit("SIGINT", () => { }); - _boolean = _rl.emit("SIGTSTP", () => { }); - - _rl = _rl.on("close", () => { }); - _rl = _rl.on("line", (input) => { - let _input: any = input; - }); - _rl = _rl.on("pause", () => { }); - _rl = _rl.on("resume", () => { }); - _rl = _rl.on("SIGCONT", () => { }); - _rl = _rl.on("SIGINT", () => { }); - _rl = _rl.on("SIGTSTP", () => { }); - - _rl = _rl.once("close", () => { }); - _rl = _rl.once("line", (input) => { - let _input: any = input; - }); - _rl = _rl.once("pause", () => { }); - _rl = _rl.once("resume", () => { }); - _rl = _rl.once("SIGCONT", () => { }); - _rl = _rl.once("SIGINT", () => { }); - _rl = _rl.once("SIGTSTP", () => { }); - - _rl = _rl.prependListener("close", () => { }); - _rl = _rl.prependListener("line", (input) => { - let _input: any = input; - }); - _rl = _rl.prependListener("pause", () => { }); - _rl = _rl.prependListener("resume", () => { }); - _rl = _rl.prependListener("SIGCONT", () => { }); - _rl = _rl.prependListener("SIGINT", () => { }); - _rl = _rl.prependListener("SIGTSTP", () => { }); - - _rl = _rl.prependOnceListener("close", () => { }); - _rl = _rl.prependOnceListener("line", (input) => { - let _input: any = input; - }); - _rl = _rl.prependOnceListener("pause", () => { }); - _rl = _rl.prependOnceListener("resume", () => { }); - _rl = _rl.prependOnceListener("SIGCONT", () => { }); - _rl = _rl.prependOnceListener("SIGINT", () => { }); - _rl = _rl.prependOnceListener("SIGTSTP", () => { }); - } -} - -//////////////////////////////////////////////////// -/// string_decoder tests : https://nodejs.org/api/string_decoder.html -//////////////////////////////////////////////////// - -namespace string_decoder_tests { - const StringDecoder = string_decoder.StringDecoder; - const buffer = new Buffer('test'); - const decoder1 = new StringDecoder(); - const decoder2 = new StringDecoder('utf8'); - const part1: string = decoder1.write(new Buffer('test')); - const end1: string = decoder1.end(); - const part2: string = decoder2.write(new Buffer('test')); - const end2: string = decoder1.end(new Buffer('test')); -} - -////////////////////////////////////////////////////////////////////// -/// Child Process tests: https://nodejs.org/api/child_process.html /// -////////////////////////////////////////////////////////////////////// - -namespace child_process_tests { - { - childProcess.exec("echo test"); - childProcess.spawn("echo", ["test"], { windowsHide: true }); - childProcess.exec("echo test", { windowsHide: true }); - childProcess.spawnSync("echo test"); - childProcess.spawnSync("echo test", { windowsVerbatimArguments: false }); - } - - { - childProcess.execFile("npm", () => {}); - childProcess.execFile("npm", { windowsHide: true }, () => {}); - childProcess.execFile("npm", ["-v"], () => {}); - childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); - childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); - childProcess.execFile("npm", { encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); - childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); - } - - { - const forked = childProcess.fork('./', ['asd'], { - windowsVerbatimArguments: true, - silent: false, - stdio: ["inherit"], - execPath: '', - execArgv: ['asda'] - }); - const exitCode: number | null = forked.exitCode; - const signalCode: number | null = forked.signalCode; - const ipc: stream.Pipe = forked.channel; - const hasRef: boolean = ipc.hasRef(); - ipc.close(); - ipc.unref(); - ipc.ref(); - } - - { - const forked = childProcess.fork('./', { - windowsVerbatimArguments: true, - silent: false, - stdio: ["inherit"], - execPath: '', - execArgv: ['asda'] - }); - } - - { - const forked = childProcess.fork('./'); - } - - async function testPromisify() { - const execFile = util.promisify(childProcess.execFile); - let r: { stdout: string | Buffer, stderr: string | Buffer } = await execFile("npm"); - r = await execFile("npm", ["-v"]); - r = await execFile("npm", ["-v"], { encoding: 'utf-8' }); - r = await execFile("npm", ["-v"], { encoding: 'buffer' }); - r = await execFile("npm", { encoding: 'utf-8' }); - r = await execFile("npm", { encoding: 'buffer' }); - } - - { - let _cp: childProcess.ChildProcess; - let _socket: net.Socket; - let _server: net.Server; - let _boolean: boolean; - - _boolean = _cp.send(1); - _boolean = _cp.send('one'); - _boolean = _cp.send({ - type: 'test' - }); - - _boolean = _cp.send(1, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send('one', (error) => { - let _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, (error) => { - let _err: Error = error; - }); - - _boolean = _cp.send(1, _socket); - _boolean = _cp.send('one', _socket); - _boolean = _cp.send({ - type: 'test' - }, _socket); - - _boolean = _cp.send(1, _socket, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send('one', _socket, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, (error) => { - let _err: Error = error; - }); - - _boolean = _cp.send(1, _socket, { - keepOpen: true - }); - _boolean = _cp.send('one', _socket, { - keepOpen: true - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, { - keepOpen: true - }); - - _boolean = _cp.send(1, _socket, { - keepOpen: true - }, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send('one', _socket, { - keepOpen: true - }, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, { - keepOpen: true - }, (error) => { - let _err: Error = error; - }); - - _boolean = _cp.send(1, _server); - _boolean = _cp.send('one', _server); - _boolean = _cp.send({ - type: 'test' - }, _server); - - _boolean = _cp.send(1, _server, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send('one', _server, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _server, (error) => { - let _err: Error = error; - }); - - _boolean = _cp.send(1, _server, { - keepOpen: true - }); - _boolean = _cp.send('one', _server, { - keepOpen: true - }); - _boolean = _cp.send({ - type: 'test' - }, _server, { - keepOpen: true - }); - - _boolean = _cp.send(1, _server, { - keepOpen: true - }, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send('one', _server, { - keepOpen: true - }, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _server, { - keepOpen: true - }, (error) => { - let _err: Error = error; - }); - - _cp = _cp.addListener("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.addListener("disconnect", () => { }); - _cp = _cp.addListener("error", (err) => { - let _err: Error = err; - }); - _cp = _cp.addListener("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.addListener("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _boolean = _cp.emit("close", () => { }); - _boolean = _cp.emit("disconnect", () => { }); - _boolean = _cp.emit("error", () => { }); - _boolean = _cp.emit("exit", () => { }); - _boolean = _cp.emit("message", () => { }); - - _cp = _cp.on("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.on("disconnect", () => { }); - _cp = _cp.on("error", (err) => { - let _err: Error = err; - }); - _cp = _cp.on("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.on("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.once("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.once("disconnect", () => { }); - _cp = _cp.once("error", (err) => { - let _err: Error = err; - }); - _cp = _cp.once("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.once("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.prependListener("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.prependListener("disconnect", () => { }); - _cp = _cp.prependListener("error", (err) => { - let _err: Error = err; - }); - _cp = _cp.prependListener("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.prependListener("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.prependOnceListener("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.prependOnceListener("disconnect", () => { }); - _cp = _cp.prependOnceListener("error", (err) => { - let _err: Error = err; - }); - _cp = _cp.prependOnceListener("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.prependOnceListener("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }); - } - { - process.stdin.setEncoding('utf8'); - - process.stdin.on('readable', () => { - const chunk = process.stdin.read(); - if (chunk !== null) { - process.stdout.write(`data: ${chunk}`); - } - }); - - process.stdin.on('end', () => { - process.stdout.write('end'); - }); - - process.stdin.pipe(process.stdout); - - console.log(process.stdin.isTTY); - console.log(process.stdout.isTTY); - - console.log(process.stdin instanceof net.Socket); - console.log(process.stdout instanceof fs.ReadStream); - - var stdin: stream.Readable = process.stdin; - console.log(stdin instanceof net.Socket); - console.log(stdin instanceof fs.ReadStream); - - var stdout: stream.Writable = process.stdout; - console.log(stdout instanceof net.Socket); - console.log(stdout instanceof fs.WriteStream); - } -} - -////////////////////////////////////////////////////////////////////// -/// cluster tests: https://nodejs.org/api/cluster.html /// -////////////////////////////////////////////////////////////////////// - -namespace cluster_tests { - { - cluster.fork(); - Object.keys(cluster.workers).forEach(key => { - const worker = cluster.workers[key]; - if (worker.isDead()) { - console.log('worker %d is dead', worker.process.pid); - } - }); - } -} - -//////////////////////////////////////////////////// -/// os tests : https://nodejs.org/api/os.html -//////////////////////////////////////////////////// - -namespace os_tests { - { - let result: string; - - result = os.tmpdir(); - result = os.homedir(); - result = os.endianness(); - result = os.hostname(); - result = os.type(); - result = os.arch(); - result = os.release(); - result = os.EOL; - } - - { - let result: number; - - result = os.uptime(); - result = os.totalmem(); - result = os.freemem(); - } - - { - let result: number[]; - - result = os.loadavg(); - } - - { - let result: os.CpuInfo[]; - - result = os.cpus(); - } - - { - let result: { [index: string]: os.NetworkInterfaceInfo[] }; - - result = os.networkInterfaces(); - } - - { - let result: number; - - result = os.constants.signals.SIGHUP; - result = os.constants.signals.SIGINT; - result = os.constants.signals.SIGQUIT; - result = os.constants.signals.SIGILL; - result = os.constants.signals.SIGTRAP; - result = os.constants.signals.SIGABRT; - result = os.constants.signals.SIGIOT; - result = os.constants.signals.SIGBUS; - result = os.constants.signals.SIGFPE; - result = os.constants.signals.SIGKILL; - result = os.constants.signals.SIGUSR1; - result = os.constants.signals.SIGSEGV; - result = os.constants.signals.SIGUSR2; - result = os.constants.signals.SIGPIPE; - result = os.constants.signals.SIGALRM; - result = os.constants.signals.SIGTERM; - result = os.constants.signals.SIGCHLD; - result = os.constants.signals.SIGSTKFLT; - result = os.constants.signals.SIGCONT; - result = os.constants.signals.SIGSTOP; - result = os.constants.signals.SIGTSTP; - result = os.constants.signals.SIGTTIN; - result = os.constants.signals.SIGTTOU; - result = os.constants.signals.SIGURG; - result = os.constants.signals.SIGXCPU; - result = os.constants.signals.SIGXFSZ; - result = os.constants.signals.SIGVTALRM; - result = os.constants.signals.SIGPROF; - result = os.constants.signals.SIGWINCH; - result = os.constants.signals.SIGIO; - result = os.constants.signals.SIGPOLL; - result = os.constants.signals.SIGPWR; - result = os.constants.signals.SIGSYS; - result = os.constants.signals.SIGUNUSED; - } - - { - let result: number; - - result = os.constants.errno.E2BIG; - result = os.constants.errno.EACCES; - result = os.constants.errno.EADDRINUSE; - result = os.constants.errno.EADDRNOTAVAIL; - result = os.constants.errno.EAFNOSUPPORT; - result = os.constants.errno.EAGAIN; - result = os.constants.errno.EALREADY; - result = os.constants.errno.EBADF; - result = os.constants.errno.EBADMSG; - result = os.constants.errno.EBUSY; - result = os.constants.errno.ECANCELED; - result = os.constants.errno.ECHILD; - result = os.constants.errno.ECONNABORTED; - result = os.constants.errno.ECONNREFUSED; - result = os.constants.errno.ECONNRESET; - result = os.constants.errno.EDEADLK; - result = os.constants.errno.EDESTADDRREQ; - result = os.constants.errno.EDOM; - result = os.constants.errno.EDQUOT; - result = os.constants.errno.EEXIST; - result = os.constants.errno.EFAULT; - result = os.constants.errno.EFBIG; - result = os.constants.errno.EHOSTUNREACH; - result = os.constants.errno.EIDRM; - result = os.constants.errno.EILSEQ; - result = os.constants.errno.EINPROGRESS; - result = os.constants.errno.EINTR; - result = os.constants.errno.EINVAL; - result = os.constants.errno.EIO; - result = os.constants.errno.EISCONN; - result = os.constants.errno.EISDIR; - result = os.constants.errno.ELOOP; - result = os.constants.errno.EMFILE; - result = os.constants.errno.EMLINK; - result = os.constants.errno.EMSGSIZE; - result = os.constants.errno.EMULTIHOP; - result = os.constants.errno.ENAMETOOLONG; - result = os.constants.errno.ENETDOWN; - result = os.constants.errno.ENETRESET; - result = os.constants.errno.ENETUNREACH; - result = os.constants.errno.ENFILE; - result = os.constants.errno.ENOBUFS; - result = os.constants.errno.ENODATA; - result = os.constants.errno.ENODEV; - result = os.constants.errno.ENOENT; - result = os.constants.errno.ENOEXEC; - result = os.constants.errno.ENOLCK; - result = os.constants.errno.ENOLINK; - result = os.constants.errno.ENOMEM; - result = os.constants.errno.ENOMSG; - result = os.constants.errno.ENOPROTOOPT; - result = os.constants.errno.ENOSPC; - result = os.constants.errno.ENOSR; - result = os.constants.errno.ENOSTR; - result = os.constants.errno.ENOSYS; - result = os.constants.errno.ENOTCONN; - result = os.constants.errno.ENOTDIR; - result = os.constants.errno.ENOTEMPTY; - result = os.constants.errno.ENOTSOCK; - result = os.constants.errno.ENOTSUP; - result = os.constants.errno.ENOTTY; - result = os.constants.errno.ENXIO; - result = os.constants.errno.EOPNOTSUPP; - result = os.constants.errno.EOVERFLOW; - result = os.constants.errno.EPERM; - result = os.constants.errno.EPIPE; - result = os.constants.errno.EPROTO; - result = os.constants.errno.EPROTONOSUPPORT; - result = os.constants.errno.EPROTOTYPE; - result = os.constants.errno.ERANGE; - result = os.constants.errno.EROFS; - result = os.constants.errno.ESPIPE; - result = os.constants.errno.ESRCH; - result = os.constants.errno.ESTALE; - result = os.constants.errno.ETIME; - result = os.constants.errno.ETIMEDOUT; - result = os.constants.errno.ETXTBSY; - result = os.constants.errno.EWOULDBLOCK; - result = os.constants.errno.EXDEV; - } -} - -//////////////////////////////////////////////////// -/// vm tests : https://nodejs.org/api/vm.html -//////////////////////////////////////////////////// - -namespace vm_tests { - { - const sandbox = { - animal: 'cat', - count: 2 - }; - - const context = vm.createContext(sandbox); - console.log(vm.isContext(context)); - const script = new vm.Script('count += 1; name = "kitty"'); - - for (let i = 0; i < 10; ++i) { - script.runInContext(context); - } - - console.log(util.inspect(sandbox)); - - vm.runInNewContext('count += 1; name = "kitty"', sandbox); - console.log(util.inspect(sandbox)); - } - - { - const sandboxes = [{}, {}, {}]; - - const script = new vm.Script('globalVar = "set"'); - - sandboxes.forEach((sandbox) => { - script.runInNewContext(sandbox); - script.runInThisContext(); - }); - - console.log(util.inspect(sandboxes)); - - var localVar = 'initial value'; - vm.runInThisContext('localVar = "vm";'); - - console.log(localVar); - } - - { - const Debug = vm.runInDebugContext('Debug'); - Debug.scripts().forEach((script: any) => { console.log(script.name); }); - } - - { - vm.runInThisContext('console.log("hello world"', './my-file.js'); - } -} - -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - -namespace timers_tests { - { - let immediateId = timers.setImmediate(() => { console.log("immediate"); }); - timers.clearImmediate(immediateId); - } - { - let counter = 0; - let timeout = timers.setInterval(() => { console.log("interval"); }, 20); - timeout.unref(); - timeout.ref(); - timers.clearInterval(timeout); - } - { - let counter = 0; - let timeout = timers.setTimeout(() => { console.log("timeout"); }, 20); - timeout.unref(); - timeout.ref(); - timers.clearTimeout(timeout); - } - async function testPromisify() { - const setTimeout = util.promisify(timers.setTimeout); - let v: void = await setTimeout(100); // tslint:disable-line no-void-expression void-return - let s: string = await setTimeout(100, ""); - - const setImmediate = util.promisify(timers.setImmediate); - v = await setImmediate(); // tslint:disable-line no-void-expression - s = await setImmediate(""); - } -} - -///////////////////////////////////////////////////////// -/// Errors Tests : https://nodejs.org/api/errors.html /// -///////////////////////////////////////////////////////// - -namespace errors_tests { - { - Error.stackTraceLimit = Infinity; - } - { - const myObject = {}; - Error.captureStackTrace(myObject); - } - { - let frames: NodeJS.CallSite[] = []; - Error.prepareStackTrace(new Error(), frames); - } - { - let frame: NodeJS.CallSite = null; - let frameThis: any = frame.getThis(); - let typeName: string = frame.getTypeName(); - let func: Function = frame.getFunction(); - let funcName: string = frame.getFunctionName(); - let meth: string = frame.getMethodName(); - let fname: string = frame.getFileName(); - let lineno: number = frame.getLineNumber(); - let colno: number = frame.getColumnNumber(); - let evalOrigin: string = frame.getEvalOrigin(); - let isTop: boolean = frame.isToplevel(); - let isEval: boolean = frame.isEval(); - let isNative: boolean = frame.isNative(); - let isConstr: boolean = frame.isConstructor(); - } -} - -/////////////////////////////////////////////////////////// -/// Process Tests : https://nodejs.org/api/process.html /// -/////////////////////////////////////////////////////////// - -import * as p from "process"; -namespace process_tests { - { - var eventEmitter: events.EventEmitter; - eventEmitter = process; // Test that process implements EventEmitter... - - var _p: NodeJS.Process = process; - _p = p; - } - { - assert(process.argv[0] === process.argv0); - } - { - var module: NodeModule | undefined; - module = process.mainModule; - } - { - process.on("message", (req: any) => { }); - process.addListener("beforeExit", (code: number) => { }); - process.once("disconnect", () => { }); - process.prependListener("exit", (code: number) => { }); - process.prependOnceListener("rejectionHandled", (promise: Promise) => { }); - process.on("uncaughtException", (error: Error) => { }); - process.addListener("unhandledRejection", (reason: any, promise: Promise) => { }); - process.once("warning", (warning: Error) => { }); - process.prependListener("message", (message: any, sendHandle: any) => { }); - process.prependOnceListener("SIGBREAK", () => { }); - process.on("newListener", (event: string | symbol, listener: Function) => { }); - process.once("removeListener", (event: string | symbol, listener: Function) => { }); - - const listeners = process.listeners('uncaughtException'); - const oldHandler = listeners[listeners.length - 1]; - process.addListener('uncaughtException', oldHandler); - } -} - -/////////////////////////////////////////////////////////// -/// Console Tests : https://nodejs.org/api/console.html /// -/////////////////////////////////////////////////////////// - -import * as c from "console"; -namespace console_tests { - { - var _c: Console = console; - _c = c; - } - { - var writeStream = fs.createWriteStream('./index.d.ts'); - var consoleInstance = new console.Console(writeStream); - } - { - console.assert('value'); - console.assert('value', 'message'); - console.assert('value', 'message', 'foo', 'bar'); - console.clear(); - console.count(); - console.count('label'); - console.countReset(); - console.countReset('label'); - console.debug(); - console.debug('message'); - console.debug('message', 'foo', 'bar'); - console.dir('obj'); - console.dir('obj', { depth: 1 }); - console.error(); - console.error('message'); - console.error('message', 'foo', 'bar'); - console.group(); - console.group('label'); - console.group('label1', 'label2'); - console.groupCollapsed(); - console.groupEnd(); - console.info(); - console.info('message'); - console.info('message', 'foo', 'bar'); - console.log(); - console.log('message'); - console.log('message', 'foo', 'bar'); - console.time('label'); - console.timeEnd('label'); - console.trace(); - console.trace('message'); - console.trace('message', 'foo', 'bar'); - console.warn(); - console.warn('message'); - console.warn('message', 'foo', 'bar'); - - // --- Inspector mode only --- - console.markTimeline(); - console.markTimeline('label'); - console.profile(); - console.profile('label'); - console.profileEnd(); - console.profileEnd('label'); - console.timeStamp(); - console.timeStamp('label'); - console.timeline(); - console.timeline('label'); - console.timelineEnd(); - console.timelineEnd('label'); - } -} - -/////////////////////////////////////////////////// -/// Net Tests : https://nodejs.org/api/net.html /// -/////////////////////////////////////////////////// - -namespace net_tests { - { - const connectOpts: net.NetConnectOpts = { - allowHalfOpen: true, - family: 4, - host: "localhost", - port: 443, - timeout: 10E3 - }; - const socket: net.Socket = net.createConnection(connectOpts, (): void => { - // nothing - }); - } - - { - let server = net.createServer(); - // Check methods which return server instances by chaining calls - server = server.listen(0) - .close() - .ref() - .unref(); - - // close callback parameter can be either nothing (undefined) or an error - server = server.close(() => { }); - server = server.close((err) => { - if (typeof err !== 'undefined') { const _err: Error = err; } - }); - - // test the types of the address object fields - let address = server.address(); - address.port = 1234; - address.family = "ipv4"; - address.address = "127.0.0.1"; - } - - { - const constructorOpts: net.SocketConstructorOpts = { - fd: 1, - allowHalfOpen: false, - readable: false, - writable: false - }; - - /** - * net.Socket - events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout - */ - let _socket: net.Socket = new net.Socket(constructorOpts); - - let bool: boolean; - let buffer: Buffer; - let error: Error; - let str: string; - let num: number; - - let ipcConnectOpts: net.IpcSocketConnectOpts = { - path: "/" - }; - let tcpConnectOpts: net.TcpSocketConnectOpts = { - family: 4, - hints: 0, - host: "localhost", - localAddress: "10.0.0.1", - localPort: 1234, - lookup: (_hostname: string, _options: dns.LookupOneOptions, _callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void => { - // nothing - }, - port: 80 - }; - _socket = _socket.connect(ipcConnectOpts); - _socket = _socket.connect(ipcConnectOpts, (): void => {}); - _socket = _socket.connect(tcpConnectOpts); - _socket = _socket.connect(tcpConnectOpts, (): void => {}); - _socket = _socket.connect(80, "localhost"); - _socket = _socket.connect(80, "localhost", (): void => {}); - _socket = _socket.connect(80); - _socket = _socket.connect(80, (): void => {}); - - /// addListener - - _socket = _socket.addListener("close", had_error => { - bool = had_error; - }); - _socket = _socket.addListener("connect", () => { }); - _socket = _socket.addListener("data", data => { - buffer = data; - }); - _socket = _socket.addListener("drain", () => { }); - _socket = _socket.addListener("end", () => { }); - _socket = _socket.addListener("error", err => { - error = err; - }); - _socket = _socket.addListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.addListener("timeout", () => { }); - - /// emit - bool = _socket.emit("close", bool); - bool = _socket.emit("connect"); - bool = _socket.emit("data", buffer); - bool = _socket.emit("drain"); - bool = _socket.emit("end"); - bool = _socket.emit("error", error); - bool = _socket.emit("lookup", error, str, str, str); - bool = _socket.emit("lookup", error, str, num, str); - bool = _socket.emit("timeout"); - - /// on - _socket = _socket.on("close", had_error => { - bool = had_error; - }); - _socket = _socket.on("connect", () => { }); - _socket = _socket.on("data", data => { - buffer = data; - }); - _socket = _socket.on("drain", () => { }); - _socket = _socket.on("end", () => { }); - _socket = _socket.on("error", err => { - error = err; - }); - _socket = _socket.on("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.on("timeout", () => { }); - - /// once - _socket = _socket.once("close", had_error => { - bool = had_error; - }); - _socket = _socket.once("connect", () => { }); - _socket = _socket.once("data", data => { - buffer = data; - }); - _socket = _socket.once("drain", () => { }); - _socket = _socket.once("end", () => { }); - _socket = _socket.once("error", err => { - error = err; - }); - _socket = _socket.once("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.once("timeout", () => { }); - - /// prependListener - _socket = _socket.prependListener("close", had_error => { - bool = had_error; - }); - _socket = _socket.prependListener("connect", () => { }); - _socket = _socket.prependListener("data", data => { - buffer = data; - }); - _socket = _socket.prependListener("drain", () => { }); - _socket = _socket.prependListener("end", () => { }); - _socket = _socket.prependListener("error", err => { - error = err; - }); - _socket = _socket.prependListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.prependListener("timeout", () => { }); - - /// prependOnceListener - _socket = _socket.prependOnceListener("close", had_error => { - bool = had_error; - }); - _socket = _socket.prependOnceListener("connect", () => { }); - _socket = _socket.prependOnceListener("data", data => { - buffer = data; - }); - _socket = _socket.prependOnceListener("drain", () => { }); - _socket = _socket.prependOnceListener("end", () => { }); - _socket = _socket.prependOnceListener("error", err => { - error = err; - }); - _socket = _socket.prependOnceListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.prependOnceListener("timeout", () => { }); - - bool = _socket.connecting; - bool = _socket.destroyed; - _socket.destroy(); - } - - { - /** - * net.Server - events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - */ - let _server: net.Server; - - let _socket: net.Socket; - let bool: boolean; - let error: Error; - - /// addListener - _server = _server.addListener("close", () => { }); - _server = _server.addListener("connection", socket => { - _socket = socket; - }); - _server = _server.addListener("error", err => { - error = err; - }); - _server = _server.addListener("listening", () => { }); - - /// emit - bool = _server.emit("close"); - bool = _server.emit("connection", _socket); - bool = _server.emit("error", error); - bool = _server.emit("listening"); - - /// once - _server = _server.once("close", () => { }); - _server = _server.once("connection", socket => { - _socket = socket; - }); - _server = _server.once("error", err => { - error = err; - }); - _server = _server.once("listening", () => { }); - - /// prependListener - _server = _server.prependListener("close", () => { }); - _server = _server.prependListener("connection", socket => { - _socket = socket; - }); - _server = _server.prependListener("error", err => { - error = err; - }); - _server = _server.prependListener("listening", () => { }); - - /// prependOnceListener - _server = _server.prependOnceListener("close", () => { }); - _server = _server.prependOnceListener("connection", socket => { - _socket = socket; - }); - _server = _server.prependOnceListener("error", err => { - error = err; - }); - _server = _server.prependOnceListener("listening", () => { }); - } -} - -///////////////////////////////////////////////////// -/// repl Tests : https://nodejs.org/api/repl.html /// -///////////////////////////////////////////////////// - -namespace repl_tests { - { - let _server: repl.REPLServer; - let _boolean: boolean; - let _ctx: any; - - _server = _server.addListener("exit", () => { }); - _server = _server.addListener("reset", () => { }); - - _boolean = _server.emit("exit", () => { }); - _boolean = _server.emit("reset", _ctx); - - _server = _server.on("exit", () => { }); - _server = _server.on("reset", () => { }); - - _server = _server.once("exit", () => { }); - _server = _server.once("reset", () => { }); - - _server = _server.prependListener("exit", () => { }); - _server = _server.prependListener("reset", () => { }); - - _server = _server.prependOnceListener("exit", () => { }); - _server = _server.prependOnceListener("reset", () => { }); - - _server.outputStream.write("test"); - let line = _server.inputStream.read(); - - throw new repl.Recoverable(new Error("test")); - } -} - -/////////////////////////////////////////////////// -/// DNS Tests : https://nodejs.org/api/dns.html /// -/////////////////////////////////////////////////// - -namespace dns_tests { - dns.lookup("nodejs.org", (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 4, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 6, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", {}, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup( - "nodejs.org", - { - family: 4, - hints: dns.ADDRCONFIG | dns.V4MAPPED, - all: false - }, - (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - } - ); - dns.lookup("nodejs.org", { all: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException = err; - const _address: dns.LookupAddress[] = addresses; - }); - dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException = err; - const _address: dns.LookupAddress[] = addresses; - }); - - function trueOrFalse(): boolean { - return Math.random() > 0.5 ? true : false; - } - dns.lookup("nodejs.org", { all: trueOrFalse() }, (err, addresses, family) => { - const _err: NodeJS.ErrnoException = err; - const _addresses: string | dns.LookupAddress[] = addresses; - const _family: number | undefined = family; - }); - - dns.lookupService("127.0.0.1", 0, (err, hostname, service) => { - const _err: NodeJS.ErrnoException = err; - const _hostname: string = hostname; - const _service: string = service; - }); - - dns.resolve("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "A", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "AAAA", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "MX", (err, addresses) => { - const _addresses: dns.MxRecord[] = addresses; - }); - - dns.resolve4("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve4("nodejs.org", { ttl: true }, (err, addresses) => { - const _addresses: dns.RecordWithTtl[] = addresses; - }); - { - const ttl = false; - dns.resolve4("nodejs.org", { ttl }, (err, addresses) => { - const _addresses: string[] | dns.RecordWithTtl[] = addresses; - }); - } - - dns.resolve6("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve6("nodejs.org", { ttl: true }, (err, addresses) => { - const _addresses: dns.RecordWithTtl[] = addresses; - }); - { - const ttl = false; - dns.resolve6("nodejs.org", { ttl }, (err, addresses) => { - const _addresses: string[] | dns.RecordWithTtl[] = addresses; - }); - } - { - const resolver = new dns.Resolver(); - resolver.setServers(["4.4.4.4"]); - resolver.resolve("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - resolver.cancel(); - } -} - -/***************************************************************************** - * * - * The following tests are the modules not mentioned in document but existed * - * * - *****************************************************************************/ - -/////////////////////////////////////////////////////////// -/// Constants Tests /// -/////////////////////////////////////////////////////////// - -import * as constants from 'constants'; -import { PerformanceObserver, PerformanceObserverCallback } from "perf_hooks"; -namespace constants_tests { - var str: string; - var num: number; - num = constants.SIGHUP; - num = constants.SIGINT; - num = constants.SIGQUIT; - num = constants.SIGILL; - num = constants.SIGTRAP; - num = constants.SIGABRT; - num = constants.SIGIOT; - num = constants.SIGBUS; - num = constants.SIGFPE; - num = constants.SIGKILL; - num = constants.SIGUSR1; - num = constants.SIGSEGV; - num = constants.SIGUSR2; - num = constants.SIGPIPE; - num = constants.SIGALRM; - num = constants.SIGTERM; - num = constants.SIGCHLD; - num = constants.SIGSTKFLT; - num = constants.SIGCONT; - num = constants.SIGSTOP; - num = constants.SIGTSTP; - num = constants.SIGTTIN; - num = constants.SIGTTOU; - num = constants.SIGURG; - num = constants.SIGXCPU; - num = constants.SIGXFSZ; - num = constants.SIGVTALRM; - num = constants.SIGPROF; - num = constants.SIGWINCH; - num = constants.SIGIO; - num = constants.SIGPOLL; - num = constants.SIGPWR; - num = constants.SIGSYS; - num = constants.SIGUNUSED; - num = constants.O_RDONLY; - num = constants.O_WRONLY; - num = constants.O_RDWR; - num = constants.S_IFMT; - num = constants.S_IFREG; - num = constants.S_IFDIR; - num = constants.S_IFCHR; - num = constants.S_IFBLK; - num = constants.S_IFIFO; - num = constants.S_IFLNK; - num = constants.S_IFSOCK; - num = constants.O_CREAT; - num = constants.O_EXCL; - num = constants.O_NOCTTY; - num = constants.O_TRUNC; - num = constants.O_APPEND; - num = constants.O_DIRECTORY; - num = constants.O_NOATIME; - num = constants.O_NOFOLLOW; - num = constants.O_SYNC; - num = constants.O_DSYNC; - num = constants.O_DIRECT; - num = constants.O_NONBLOCK; - num = constants.S_IRWXU; - num = constants.S_IRUSR; - num = constants.S_IWUSR; - num = constants.S_IXUSR; - num = constants.S_IRWXG; - num = constants.S_IRGRP; - num = constants.S_IWGRP; - num = constants.S_IXGRP; - num = constants.S_IRWXO; - num = constants.S_IROTH; - num = constants.S_IWOTH; - num = constants.S_IXOTH; - num = constants.F_OK; - num = constants.R_OK; - num = constants.W_OK; - num = constants.X_OK; - num = constants.SSL_OP_ALL; - num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION; - num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE; - num = constants.SSL_OP_CISCO_ANYCONNECT; - num = constants.SSL_OP_COOKIE_EXCHANGE; - num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG; - num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; - num = constants.SSL_OP_EPHEMERAL_RSA; - num = constants.SSL_OP_LEGACY_SERVER_CONNECT; - num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER; - num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG; - num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING; - num = constants.SSL_OP_NETSCAPE_CA_DN_BUG; - num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG; - num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG; - num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; - num = constants.SSL_OP_NO_COMPRESSION; - num = constants.SSL_OP_NO_QUERY_MTU; - num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION; - num = constants.SSL_OP_NO_SSLv2; - num = constants.SSL_OP_NO_SSLv3; - num = constants.SSL_OP_NO_TICKET; - num = constants.SSL_OP_NO_TLSv1; - num = constants.SSL_OP_NO_TLSv1_1; - num = constants.SSL_OP_NO_TLSv1_2; - num = constants.SSL_OP_PKCS1_CHECK_1; - num = constants.SSL_OP_PKCS1_CHECK_2; - num = constants.SSL_OP_SINGLE_DH_USE; - num = constants.SSL_OP_SINGLE_ECDH_USE; - num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG; - num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG; - num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG; - num = constants.SSL_OP_TLS_D5_BUG; - num = constants.SSL_OP_TLS_ROLLBACK_BUG; - num = constants.ENGINE_METHOD_RSA; - num = constants.ENGINE_METHOD_DSA; - num = constants.ENGINE_METHOD_DH; - num = constants.ENGINE_METHOD_RAND; - num = constants.ENGINE_METHOD_ECDH; - num = constants.ENGINE_METHOD_ECDSA; - num = constants.ENGINE_METHOD_CIPHERS; - num = constants.ENGINE_METHOD_DIGESTS; - num = constants.ENGINE_METHOD_STORE; - num = constants.ENGINE_METHOD_PKEY_METHS; - num = constants.ENGINE_METHOD_PKEY_ASN1_METHS; - num = constants.ENGINE_METHOD_ALL; - num = constants.ENGINE_METHOD_NONE; - num = constants.DH_CHECK_P_NOT_SAFE_PRIME; - num = constants.DH_CHECK_P_NOT_PRIME; - num = constants.DH_UNABLE_TO_CHECK_GENERATOR; - num = constants.DH_NOT_SUITABLE_GENERATOR; - num = constants.NPN_ENABLED; - num = constants.ALPN_ENABLED; - num = constants.RSA_PKCS1_PADDING; - num = constants.RSA_SSLV23_PADDING; - num = constants.RSA_NO_PADDING; - num = constants.RSA_PKCS1_OAEP_PADDING; - num = constants.RSA_X931_PADDING; - num = constants.RSA_PKCS1_PSS_PADDING; - num = constants.POINT_CONVERSION_COMPRESSED; - num = constants.POINT_CONVERSION_UNCOMPRESSED; - num = constants.POINT_CONVERSION_HYBRID; - str = constants.defaultCoreCipherList; - str = constants.defaultCipherList; -} - -//////////////////////////////////////////////////// -/// v8 tests : https://nodejs.org/api/v8.html -//////////////////////////////////////////////////// - -namespace v8_tests { - const heapStats = v8.getHeapStatistics(); - const heapSpaceStats = v8.getHeapSpaceStatistics(); - - const zapsGarbage: number = heapStats.does_zap_garbage; - - v8.setFlagsFromString('--collect_maps'); -} - -//////////////////////////////////////////////////// -/// PerfHooks tests : https://nodejs.org/api/perf_hooks.html -//////////////////////////////////////////////////// -namespace perf_hooks_tests { - perf_hooks.performance.mark('start'); - ( - () => {} - )(); - perf_hooks.performance.mark('end'); - - const { duration } = perf_hooks.performance.getEntriesByName('discover')[0]; - const timeOrigin = perf_hooks.performance.timeOrigin; - - const performanceObserverCallback: PerformanceObserverCallback = (list, obs) => { - const { - duration, - entryType, - name, - startTime, - } = list.getEntries()[0]; - obs.disconnect(); - perf_hooks.performance.clearFunctions(); - }; - const obs = new perf_hooks.PerformanceObserver(performanceObserverCallback); - obs.observe({ - entryTypes: ['function'], - buffered: true, - }); -} - -//////////////////////////////////////////////////// -/// AsyncHooks tests : https://nodejs.org/api/async_hooks.html -//////////////////////////////////////////////////// -namespace async_hooks_tests { - const hooks: async_hooks.HookCallbacks = { - init() {}, - before() {}, - after() {}, - destroy() {}, - promiseResolve() {}, - }; - - const asyncHook = async_hooks.createHook(hooks); - - asyncHook.enable().disable().enable(); - - const tId: number = async_hooks.triggerAsyncId(); - const eId: number = async_hooks.executionAsyncId(); - - class TestResource extends async_hooks.AsyncResource { - constructor() { - super('TEST_RESOURCE'); - } - } - - class AnotherTestResource extends async_hooks.AsyncResource { - constructor() { - super('TEST_RESOURCE', 42); - const aId: number = this.asyncId(); - const tId: number = this.triggerAsyncId(); - } - run() { - this.emitBefore(); - this.emitAfter(); - } - destroy() { - this.emitDestroy(); - } - } - - // check AsyncResource constructor options. - new async_hooks.AsyncResource(''); - new async_hooks.AsyncResource('', 0); - new async_hooks.AsyncResource('', {}); - new async_hooks.AsyncResource('', { triggerAsyncId: 0 }); - new async_hooks.AsyncResource('', { - triggerAsyncId: 0, - requireManualDestroy: true - }); -} - -//////////////////////////////////////////////////// -/// zlib tests : http://nodejs.org/api/zlib.html /// -//////////////////////////////////////////////////// - -namespace zlib_tests { - { - const gzipped = zlib.gzipSync('test'); - const unzipped = zlib.gunzipSync(gzipped.toString()); - } - - { - const deflate = zlib.deflateSync('test'); - const inflate = zlib.inflateSync(deflate.toString()); - } -} - -/////////////////////////////////////////////////////////// -/// HTTP/2 Tests /// -/////////////////////////////////////////////////////////// - -namespace http2_tests { - // Headers & Settings - { - let headers: http2.OutgoingHttpHeaders = { - ':status': 200, - 'content-type': 'text-plain', - ABC: ['has', 'more', 'than', 'one', 'value'], - undef: undefined - }; - - let settings: http2.Settings = { - headerTableSize: 0, - enablePush: true, - initialWindowSize: 0, - maxFrameSize: 0, - maxConcurrentStreams: 0, - maxHeaderListSize: 0 - }; - } - - // Http2Session - { - let http2Session: http2.Http2Session; - let ee: events.EventEmitter = http2Session; - - http2Session.on('close', () => {}); - http2Session.on('connect', (session: http2.Http2Session, socket: net.Socket) => {}); - http2Session.on('error', (err: Error) => {}); - http2Session.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); - http2Session.on('goaway', (errorCode: number, lastStreamID: number, opaqueData: Buffer) => {}); - http2Session.on('localSettings', (settings: http2.Settings) => {}); - http2Session.on('remoteSettings', (settings: http2.Settings) => {}); - http2Session.on('stream', (stream: http2.Http2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - http2Session.on('socketError', (err: Error) => {}); - http2Session.on('timeout', () => {}); - - http2Session.destroy(); - - let destroyed: boolean = http2Session.destroyed; - let pendingSettingsAck: boolean = http2Session.pendingSettingsAck; - let settings: http2.Settings = http2Session.localSettings; - settings = http2Session.remoteSettings; - - let headers: http2.OutgoingHttpHeaders; - let options: http2.ClientSessionRequestOptions = { - endStream: true, - exclusive: true, - parent: 0, - weight: 0, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {} - }; - (http2Session as http2.ClientHttp2Session).request(); - (http2Session as http2.ClientHttp2Session).request(headers); - (http2Session as http2.ClientHttp2Session).request(headers, options); - - let stream: http2.Http2Stream; - http2Session.rstStream(stream); - http2Session.rstStream(stream, 0); - - http2Session.setTimeout(100, () => {}); - - let shutdownOptions: http2.SessionShutdownOptions = { - graceful: true, - errorCode: 0, - lastStreamID: 0, - opaqueData: Buffer.from([]) - }; - shutdownOptions.opaqueData = Uint8Array.from([]); - http2Session.shutdown(shutdownOptions); - http2Session.shutdown(shutdownOptions, () => {}); - - let socket: net.Socket | tls.TLSSocket = http2Session.socket; - let state: http2.SessionState = http2Session.state; - state = { - effectiveLocalWindowSize: 0, - effectiveRecvDataLength: 0, - nextStreamID: 0, - localWindowSize: 0, - lastProcStreamID: 0, - remoteWindowSize: 0, - outboundQueueSize: 0, - deflateDynamicTableSize: 0, - inflateDynamicTableSize: 0 - }; - - http2Session.priority(stream, { - exclusive: true, - parent: 0, - weight: 0, - silent: true - }); - - http2Session.settings(settings); - } - - // Http2Stream - { - let http2Stream: http2.Http2Stream; - let duplex: stream.Duplex = http2Stream; - - http2Stream.on('aborted', () => {}); - http2Stream.on('error', (err: Error) => {}); - http2Stream.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); - http2Stream.on('streamClosed', (code: number) => {}); - http2Stream.on('timeout', () => {}); - http2Stream.on('trailers', (trailers: http2.IncomingHttpHeaders, flags: number) => {}); - - let aborted: boolean = http2Stream.aborted; - let destroyed: boolean = http2Stream.destroyed; - - http2Stream.priority({ - exclusive: true, - parent: 0, - weight: 0, - silent: true - }); - - let rstCode: number = http2Stream.rstCode; - http2Stream.rstStream(rstCode); - http2Stream.rstWithNoError(); - http2Stream.rstWithProtocolError(); - http2Stream.rstWithCancel(); - http2Stream.rstWithRefuse(); - http2Stream.rstWithInternalError(); - - let sesh: http2.Http2Session = http2Stream.session; - - http2Stream.setTimeout(100, () => {}); - - let state: http2.StreamState = http2Stream.state; - state = { - localWindowSize: 0, - state: 0, - streamLocalClose: 0, - streamRemoteClose: 0, - sumDependencyWeight: 0, - weight: 0 - }; - - // ClientHttp2Stream - let clientHttp2Stream: http2.ClientHttp2Stream; - clientHttp2Stream.on('headers', (headers: http2.IncomingHttpHeaders, flags: number) => {}); - clientHttp2Stream.on('push', (headers: http2.IncomingHttpHeaders, flags: number) => {}); - clientHttp2Stream.on('response', (headers: http2.IncomingHttpHeaders, flags: number) => {}); - - // ServerHttp2Stream - let serverHttp2Stream: http2.ServerHttp2Stream; - let headers: http2.OutgoingHttpHeaders; - - serverHttp2Stream.additionalHeaders(headers); - let headerSent: boolean = serverHttp2Stream.headersSent; - let pushAllowed: boolean = serverHttp2Stream.pushAllowed; - serverHttp2Stream.pushStream(headers, (pushStream: http2.ServerHttp2Stream) => {}); - - let options: http2.ServerStreamResponseOptions = { - endStream: true, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {} - }; - serverHttp2Stream.respond(); - serverHttp2Stream.respond(headers); - serverHttp2Stream.respond(headers, options); - - let options2: http2.ServerStreamFileResponseOptions = { - statCheck: (stats: fs.Stats, headers: http2.OutgoingHttpHeaders, statOptions: http2.StatOptions) => {}, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {}, - offset: 0, - length: 0 - }; - serverHttp2Stream.respondWithFD(0); - serverHttp2Stream.respondWithFD(0, headers); - serverHttp2Stream.respondWithFD(0, headers, options2); - serverHttp2Stream.respondWithFD(0, headers, {statCheck: () => false}); - let options3: http2.ServerStreamFileResponseOptionsWithError = { - onError: (err: NodeJS.ErrnoException) => {}, - statCheck: (stats: fs.Stats, headers: http2.OutgoingHttpHeaders, statOptions: http2.StatOptions) => {}, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {}, - offset: 0, - length: 0 - }; - serverHttp2Stream.respondWithFile(''); - serverHttp2Stream.respondWithFile('', headers); - serverHttp2Stream.respondWithFile('', headers, options3); - serverHttp2Stream.respondWithFile('', headers, {statCheck: () => false}); - } - - // Http2Server / Http2SecureServer - { - let http2Server: http2.Http2Server; - let http2SecureServer: http2.Http2SecureServer; - let s1: net.Server = http2Server; - let s2: tls.Server = http2SecureServer; - [http2Server, http2SecureServer].forEach((server) => { - server.on('sessionError', (err: Error) => {}); - server.on('socketError', (err: Error) => {}); - server.on('stream', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - server.on('request', (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => {}); - server.on('timeout', () => {}); - }); - - http2SecureServer.on('unknownProtocol', (socket: tls.TLSSocket) => {}); - } - - // Public API (except constants) - { - let settings: http2.Settings; - let serverOptions: http2.ServerOptions = { - maxDeflateDynamicTableSize: 0, - maxReservedRemoteStreams: 0, - maxSendHeaderBlockLength: 0, - paddingStrategy: 0, - peerMaxConcurrentStreams: 0, - selectPadding: (frameLen: number, maxFrameLen: number) => 0, - settings - }; - // tslint:disable-next-line prefer-object-spread (ts2.1 feature) - let secureServerOptions: http2.SecureServerOptions = Object.assign({}, serverOptions); - secureServerOptions.ca = ''; - let onRequestHandler = (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => { - // Http2ServerRequest - - let readable: stream.Readable = request; - let incomingHeaders: http2.IncomingHttpHeaders = request.headers; - incomingHeaders = request.trailers; - let httpVersion: string = request.httpVersion; - let method: string = request.method; - let rawHeaders: string[] = request.rawHeaders; - rawHeaders = request.rawTrailers; - let socket: net.Socket | tls.TLSSocket = request.socket; - let stream: http2.ServerHttp2Stream = request.stream; - let url: string = request.url; - - request.setTimeout(0, () => {}); - request.on('aborted', (hadError: boolean, code: number) => {}); - - // Http2ServerResponse - - let outgoingHeaders: http2.OutgoingHttpHeaders; - response.addTrailers(outgoingHeaders); - socket = response.connection; - let finished: boolean = response.finished; - response.sendDate = true; - response.statusCode = 200; - response.statusMessage = ''; - socket = response.socket; - stream = response.stream; - - method = response.getHeader(':method'); - let headers: string[] = response.getHeaderNames(); - outgoingHeaders = response.getHeaders(); - let hasMethod = response.hasHeader(':method'); - response.removeHeader(':method'); - response.setHeader(':method', 'GET'); - response.setHeader(':status', 200); - response.setHeader('some-list', ['', '']); - let headersSent: boolean = response.headersSent; - - response.setTimeout(0, () => {}); - response.createPushResponse(outgoingHeaders, (err: Error | null, res: http2.Http2ServerResponse) => {}); - - response.writeContinue(); - response.writeHead(200); - response.writeHead(200, outgoingHeaders); - response.writeHead(200, 'OK', outgoingHeaders); - response.writeHead(200, 'OK'); - response.write(''); - response.write('', (err: Error) => {}); - response.write('', 'utf8'); - response.write('', 'utf8', (err: Error) => {}); - response.write(Buffer.from([])); - response.write(Buffer.from([]), (err: Error) => {}); - response.write(Buffer.from([]), 'utf8'); - response.write(Buffer.from([]), 'utf8', (err: Error) => {}); - response.end(); - response.end(() => {}); - response.end(''); - response.end('', () => {}); - response.end('', 'utf8'); - response.end('', 'utf8', () => {}); - response.end(Buffer.from([])); - response.end(Buffer.from([]), () => {}); - response.end(Buffer.from([]), 'utf8'); - response.end(Buffer.from([]), 'utf8', () => {}); - - request.on('aborted', (hadError: boolean, code: number) => {}); - request.on('close', () => {}); - request.on('drain', () => {}); - request.on('error', (error: Error) => {}); - request.on('finish', () => {}); - }; - - let http2Server: http2.Http2Server; - let http2SecureServer: http2.Http2SecureServer; - - http2Server = http2.createServer(); - http2Server = http2.createServer(serverOptions); - http2Server = http2.createServer(onRequestHandler); - http2Server = http2.createServer(serverOptions, onRequestHandler); - - http2SecureServer = http2.createSecureServer(); - http2SecureServer = http2.createSecureServer(secureServerOptions); - http2SecureServer = http2.createSecureServer(onRequestHandler); - http2SecureServer = http2.createSecureServer(secureServerOptions, onRequestHandler); - - let clientSessionOptions: http2.ClientSessionOptions = { - maxDeflateDynamicTableSize: 0, - maxReservedRemoteStreams: 0, - maxSendHeaderBlockLength: 0, - paddingStrategy: 0, - peerMaxConcurrentStreams: 0, - selectPadding: (frameLen: number, maxFrameLen: number) => 0, - settings - }; - // tslint:disable-next-line prefer-object-spread (ts2.1 feature) - let secureClientSessionOptions: http2.SecureClientSessionOptions = Object.assign({}, clientSessionOptions); - secureClientSessionOptions.ca = ''; - let onConnectHandler = (session: http2.Http2Session, socket: net.Socket) => {}; - - let clientHttp2Session: http2.ClientHttp2Session; - - clientHttp2Session = http2.connect(''); - clientHttp2Session = http2.connect('', onConnectHandler); - clientHttp2Session = http2.connect('', clientSessionOptions); - clientHttp2Session = http2.connect('', clientSessionOptions, onConnectHandler); - clientHttp2Session = http2.connect('', secureClientSessionOptions); - clientHttp2Session = http2.connect('', secureClientSessionOptions, onConnectHandler); - - settings = http2.getDefaultSettings(); - settings = http2.getPackedSettings(settings); - settings = http2.getUnpackedSettings(Buffer.from([])); - settings = http2.getUnpackedSettings(Uint8Array.from([])); - } - - // constants - { - const constants = http2.constants; - let num: number; - let str: string; - num = constants.NGHTTP2_SESSION_SERVER; - num = constants.NGHTTP2_SESSION_CLIENT; - num = constants.NGHTTP2_STREAM_STATE_IDLE; - num = constants.NGHTTP2_STREAM_STATE_OPEN; - num = constants.NGHTTP2_STREAM_STATE_RESERVED_LOCAL; - num = constants.NGHTTP2_STREAM_STATE_RESERVED_REMOTE; - num = constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL; - num = constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE; - num = constants.NGHTTP2_STREAM_STATE_CLOSED; - num = constants.NGHTTP2_NO_ERROR; - num = constants.NGHTTP2_PROTOCOL_ERROR; - num = constants.NGHTTP2_INTERNAL_ERROR; - num = constants.NGHTTP2_FLOW_CONTROL_ERROR; - num = constants.NGHTTP2_SETTINGS_TIMEOUT; - num = constants.NGHTTP2_STREAM_CLOSED; - num = constants.NGHTTP2_FRAME_SIZE_ERROR; - num = constants.NGHTTP2_REFUSED_STREAM; - num = constants.NGHTTP2_CANCEL; - num = constants.NGHTTP2_COMPRESSION_ERROR; - num = constants.NGHTTP2_CONNECT_ERROR; - num = constants.NGHTTP2_ENHANCE_YOUR_CALM; - num = constants.NGHTTP2_INADEQUATE_SECURITY; - num = constants.NGHTTP2_HTTP_1_1_REQUIRED; - num = constants.NGHTTP2_ERR_FRAME_SIZE_ERROR; - num = constants.NGHTTP2_FLAG_NONE; - num = constants.NGHTTP2_FLAG_END_STREAM; - num = constants.NGHTTP2_FLAG_END_HEADERS; - num = constants.NGHTTP2_FLAG_ACK; - num = constants.NGHTTP2_FLAG_PADDED; - num = constants.NGHTTP2_FLAG_PRIORITY; - num = constants.DEFAULT_SETTINGS_HEADER_TABLE_SIZE; - num = constants.DEFAULT_SETTINGS_ENABLE_PUSH; - num = constants.DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE; - num = constants.DEFAULT_SETTINGS_MAX_FRAME_SIZE; - num = constants.MAX_MAX_FRAME_SIZE; - num = constants.MIN_MAX_FRAME_SIZE; - num = constants.MAX_INITIAL_WINDOW_SIZE; - num = constants.NGHTTP2_DEFAULT_WEIGHT; - num = constants.NGHTTP2_SETTINGS_HEADER_TABLE_SIZE; - num = constants.NGHTTP2_SETTINGS_ENABLE_PUSH; - num = constants.NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; - num = constants.NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; - num = constants.NGHTTP2_SETTINGS_MAX_FRAME_SIZE; - num = constants.NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE; - num = constants.PADDING_STRATEGY_NONE; - num = constants.PADDING_STRATEGY_MAX; - num = constants.PADDING_STRATEGY_CALLBACK; - num = constants.HTTP_STATUS_CONTINUE; - num = constants.HTTP_STATUS_SWITCHING_PROTOCOLS; - num = constants.HTTP_STATUS_PROCESSING; - num = constants.HTTP_STATUS_OK; - num = constants.HTTP_STATUS_CREATED; - num = constants.HTTP_STATUS_ACCEPTED; - num = constants.HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION; - num = constants.HTTP_STATUS_NO_CONTENT; - num = constants.HTTP_STATUS_RESET_CONTENT; - num = constants.HTTP_STATUS_PARTIAL_CONTENT; - num = constants.HTTP_STATUS_MULTI_STATUS; - num = constants.HTTP_STATUS_ALREADY_REPORTED; - num = constants.HTTP_STATUS_IM_USED; - num = constants.HTTP_STATUS_MULTIPLE_CHOICES; - num = constants.HTTP_STATUS_MOVED_PERMANENTLY; - num = constants.HTTP_STATUS_FOUND; - num = constants.HTTP_STATUS_SEE_OTHER; - num = constants.HTTP_STATUS_NOT_MODIFIED; - num = constants.HTTP_STATUS_USE_PROXY; - num = constants.HTTP_STATUS_TEMPORARY_REDIRECT; - num = constants.HTTP_STATUS_PERMANENT_REDIRECT; - num = constants.HTTP_STATUS_BAD_REQUEST; - num = constants.HTTP_STATUS_UNAUTHORIZED; - num = constants.HTTP_STATUS_PAYMENT_REQUIRED; - num = constants.HTTP_STATUS_FORBIDDEN; - num = constants.HTTP_STATUS_NOT_FOUND; - num = constants.HTTP_STATUS_METHOD_NOT_ALLOWED; - num = constants.HTTP_STATUS_NOT_ACCEPTABLE; - num = constants.HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED; - num = constants.HTTP_STATUS_REQUEST_TIMEOUT; - num = constants.HTTP_STATUS_CONFLICT; - num = constants.HTTP_STATUS_GONE; - num = constants.HTTP_STATUS_LENGTH_REQUIRED; - num = constants.HTTP_STATUS_PRECONDITION_FAILED; - num = constants.HTTP_STATUS_PAYLOAD_TOO_LARGE; - num = constants.HTTP_STATUS_URI_TOO_LONG; - num = constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE; - num = constants.HTTP_STATUS_RANGE_NOT_SATISFIABLE; - num = constants.HTTP_STATUS_EXPECTATION_FAILED; - num = constants.HTTP_STATUS_TEAPOT; - num = constants.HTTP_STATUS_MISDIRECTED_REQUEST; - num = constants.HTTP_STATUS_UNPROCESSABLE_ENTITY; - num = constants.HTTP_STATUS_LOCKED; - num = constants.HTTP_STATUS_FAILED_DEPENDENCY; - num = constants.HTTP_STATUS_UNORDERED_COLLECTION; - num = constants.HTTP_STATUS_UPGRADE_REQUIRED; - num = constants.HTTP_STATUS_PRECONDITION_REQUIRED; - num = constants.HTTP_STATUS_TOO_MANY_REQUESTS; - num = constants.HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE; - num = constants.HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS; - num = constants.HTTP_STATUS_INTERNAL_SERVER_ERROR; - num = constants.HTTP_STATUS_NOT_IMPLEMENTED; - num = constants.HTTP_STATUS_BAD_GATEWAY; - num = constants.HTTP_STATUS_SERVICE_UNAVAILABLE; - num = constants.HTTP_STATUS_GATEWAY_TIMEOUT; - num = constants.HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED; - num = constants.HTTP_STATUS_VARIANT_ALSO_NEGOTIATES; - num = constants.HTTP_STATUS_INSUFFICIENT_STORAGE; - num = constants.HTTP_STATUS_LOOP_DETECTED; - num = constants.HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED; - num = constants.HTTP_STATUS_NOT_EXTENDED; - num = constants.HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED; - str = constants.HTTP2_HEADER_STATUS; - str = constants.HTTP2_HEADER_METHOD; - str = constants.HTTP2_HEADER_AUTHORITY; - str = constants.HTTP2_HEADER_SCHEME; - str = constants.HTTP2_HEADER_PATH; - str = constants.HTTP2_HEADER_ACCEPT_CHARSET; - str = constants.HTTP2_HEADER_ACCEPT_ENCODING; - str = constants.HTTP2_HEADER_ACCEPT_LANGUAGE; - str = constants.HTTP2_HEADER_ACCEPT_RANGES; - str = constants.HTTP2_HEADER_ACCEPT; - str = constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN; - str = constants.HTTP2_HEADER_AGE; - str = constants.HTTP2_HEADER_ALLOW; - str = constants.HTTP2_HEADER_AUTHORIZATION; - str = constants.HTTP2_HEADER_CACHE_CONTROL; - str = constants.HTTP2_HEADER_CONNECTION; - str = constants.HTTP2_HEADER_CONTENT_DISPOSITION; - str = constants.HTTP2_HEADER_CONTENT_ENCODING; - str = constants.HTTP2_HEADER_CONTENT_LANGUAGE; - str = constants.HTTP2_HEADER_CONTENT_LENGTH; - str = constants.HTTP2_HEADER_CONTENT_LOCATION; - str = constants.HTTP2_HEADER_CONTENT_MD5; - str = constants.HTTP2_HEADER_CONTENT_RANGE; - str = constants.HTTP2_HEADER_CONTENT_TYPE; - str = constants.HTTP2_HEADER_COOKIE; - str = constants.HTTP2_HEADER_DATE; - str = constants.HTTP2_HEADER_ETAG; - str = constants.HTTP2_HEADER_EXPECT; - str = constants.HTTP2_HEADER_EXPIRES; - str = constants.HTTP2_HEADER_FROM; - str = constants.HTTP2_HEADER_HOST; - str = constants.HTTP2_HEADER_IF_MATCH; - str = constants.HTTP2_HEADER_IF_MODIFIED_SINCE; - str = constants.HTTP2_HEADER_IF_NONE_MATCH; - str = constants.HTTP2_HEADER_IF_RANGE; - str = constants.HTTP2_HEADER_IF_UNMODIFIED_SINCE; - str = constants.HTTP2_HEADER_LAST_MODIFIED; - str = constants.HTTP2_HEADER_LINK; - str = constants.HTTP2_HEADER_LOCATION; - str = constants.HTTP2_HEADER_MAX_FORWARDS; - str = constants.HTTP2_HEADER_PREFER; - str = constants.HTTP2_HEADER_PROXY_AUTHENTICATE; - str = constants.HTTP2_HEADER_PROXY_AUTHORIZATION; - str = constants.HTTP2_HEADER_RANGE; - str = constants.HTTP2_HEADER_REFERER; - str = constants.HTTP2_HEADER_REFRESH; - str = constants.HTTP2_HEADER_RETRY_AFTER; - str = constants.HTTP2_HEADER_SERVER; - str = constants.HTTP2_HEADER_SET_COOKIE; - str = constants.HTTP2_HEADER_STRICT_TRANSPORT_SECURITY; - str = constants.HTTP2_HEADER_TRANSFER_ENCODING; - str = constants.HTTP2_HEADER_TE; - str = constants.HTTP2_HEADER_UPGRADE; - str = constants.HTTP2_HEADER_USER_AGENT; - str = constants.HTTP2_HEADER_VARY; - str = constants.HTTP2_HEADER_VIA; - str = constants.HTTP2_HEADER_WWW_AUTHENTICATE; - str = constants.HTTP2_HEADER_HTTP2_SETTINGS; - str = constants.HTTP2_HEADER_KEEP_ALIVE; - str = constants.HTTP2_HEADER_PROXY_CONNECTION; - str = constants.HTTP2_METHOD_ACL; - str = constants.HTTP2_METHOD_BASELINE_CONTROL; - str = constants.HTTP2_METHOD_BIND; - str = constants.HTTP2_METHOD_CHECKIN; - str = constants.HTTP2_METHOD_CHECKOUT; - str = constants.HTTP2_METHOD_CONNECT; - str = constants.HTTP2_METHOD_COPY; - str = constants.HTTP2_METHOD_DELETE; - str = constants.HTTP2_METHOD_GET; - str = constants.HTTP2_METHOD_HEAD; - str = constants.HTTP2_METHOD_LABEL; - str = constants.HTTP2_METHOD_LINK; - str = constants.HTTP2_METHOD_LOCK; - str = constants.HTTP2_METHOD_MERGE; - str = constants.HTTP2_METHOD_MKACTIVITY; - str = constants.HTTP2_METHOD_MKCALENDAR; - str = constants.HTTP2_METHOD_MKCOL; - str = constants.HTTP2_METHOD_MKREDIRECTREF; - str = constants.HTTP2_METHOD_MKWORKSPACE; - str = constants.HTTP2_METHOD_MOVE; - str = constants.HTTP2_METHOD_OPTIONS; - str = constants.HTTP2_METHOD_ORDERPATCH; - str = constants.HTTP2_METHOD_PATCH; - str = constants.HTTP2_METHOD_POST; - str = constants.HTTP2_METHOD_PRI; - str = constants.HTTP2_METHOD_PROPFIND; - str = constants.HTTP2_METHOD_PROPPATCH; - str = constants.HTTP2_METHOD_PUT; - str = constants.HTTP2_METHOD_REBIND; - str = constants.HTTP2_METHOD_REPORT; - str = constants.HTTP2_METHOD_SEARCH; - str = constants.HTTP2_METHOD_TRACE; - str = constants.HTTP2_METHOD_UNBIND; - str = constants.HTTP2_METHOD_UNCHECKOUT; - str = constants.HTTP2_METHOD_UNLINK; - str = constants.HTTP2_METHOD_UNLOCK; - str = constants.HTTP2_METHOD_UPDATE; - str = constants.HTTP2_METHOD_UPDATEREDIRECTREF; - str = constants.HTTP2_METHOD_VERSION_CONTROL; - } -} - -/////////////////////////////////////////////////////////// -/// Inspector Tests /// -/////////////////////////////////////////////////////////// - -namespace inspector_tests { - { - inspector.open(); - inspector.open(0); - inspector.open(0, 'localhost'); - inspector.open(0, 'localhost', true); - inspector.close(); - const inspectorUrl: string | undefined = inspector.url(); - - const session = new inspector.Session(); - session.connect(); - session.disconnect(); - - // Unknown post method - session.post('A.b', { key: 'value' }, (err, params) => {}); - // TODO: parameters are implicitly 'any' and need type annotation - session.post('A.b', (err: Error | null, params?: {}) => {}); - session.post('A.b'); - // Known post method - const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; - session.post('Runtime.evaluate', parameter, - (err: Error, params: inspector.Runtime.EvaluateReturnType) => {}); - session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { - const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails; - const resultClassName: string = params.result.className; - }); - session.post('Runtime.evaluate'); - - // General event - session.on('inspectorNotification', message => { - message; // $ExpectType InspectorNotification<{}> - }); - // Known events - session.on('Debugger.paused', (message: inspector.InspectorNotification) => { - const method: string = message.method; - const pauseReason: string = message.params.reason; - }); - session.on('Debugger.resumed', () => {}); - } -} - -//////////////////////////////////////////////////// -/// module tests : http://nodejs.org/api/modules.html -//////////////////////////////////////////////////// - -namespace module_tests { - require.extensions[".ts"] = () => ""; - - Module.runMain(); - const s: string = Module.wrap("some code"); - - const m1: Module = new Module("moduleId"); - const m2: Module = new Module.Module("moduleId"); - const b: string[] = Module.builtinModules; - let paths: string[] = module.paths; - paths = m1.paths; -} - -//////////////////////////////////////////////////// -/// Node.js ESNEXT Support -//////////////////////////////////////////////////// - -namespace esnext_string_tests { - const s: string = 'foo'; - const s1: string = s.trimLeft(); - const s2: string = s.trimRight(); -} diff --git a/types/node/v8/ts3.1/tsconfig.json b/types/node/v8/ts3.1/tsconfig.json deleted file mode 100644 index 88dd7ac6c7..0000000000 --- a/types/node/v8/ts3.1/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "files": [ - "index.d.ts", - "node-tests.ts" - ], - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": true, - "baseUrl": "../../../", - "typeRoots": [ - "../../../" - ], - "paths": { - "node": [ - "node/v8" - ] - }, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - } -} diff --git a/types/node/v8/ts3.1/tslint.json b/types/node/v8/ts3.1/tslint.json deleted file mode 100644 index 8f9cf3a592..0000000000 --- a/types/node/v8/ts3.1/tslint.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "dt-header": false, - "max-line-length": false, - "no-empty-interface": false, - "no-internal-module": false, - "no-redundant-jsdoc": false, - "no-single-declare-module": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-var-keyword": false, - "prefer-method-signature": false, - "strict-export-declare-modifiers": false, - "unified-signatures": false - } -} diff --git a/types/node/v9/package.json b/types/node/v9/package.json deleted file mode 100644 index 54d5b8743e..0000000000 --- a/types/node/v9/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "private": true, - "types": "index", - "typesVersions": { - "<=3.1": { - "*": [ - "ts3.1/*" - ] - } - } -} diff --git a/types/node/v9/ts3.1/index.d.ts b/types/node/v9/ts3.1/index.d.ts deleted file mode 100644 index 11eeb49026..0000000000 --- a/types/node/v9/ts3.1/index.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.1. - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 - -// NOTE: Augmentations for TypeScript 3.1 and later should use individual files for overrides -// within the respective ~/ts3.1 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.1, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -// tslint:disable-next-line:no-bad-reference -/// - -// TypeScript 2.1-specific augmentations: - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } -interface IteratorResult { } -interface Iterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IterableIterator { } -interface SymbolConstructor { - readonly iterator: symbol; -} -declare var Symbol: SymbolConstructor; - -declare module "util" { - namespace inspect { - const custom: symbol; - } - namespace promisify { - const custom: symbol; - } -} diff --git a/types/node/v9/ts3.1/node-tests.ts b/types/node/v9/ts3.1/node-tests.ts deleted file mode 100644 index d3e55de398..0000000000 --- a/types/node/v9/ts3.1/node-tests.ts +++ /dev/null @@ -1,4168 +0,0 @@ -// NOTE: Disabled to preserve existing tests file: -// tslint:disable:no-namespace -// tslint:disable:no-duplicate-variable -// tslint:disable:no-duplicate-imports -// tslint:disable:no-var-keyword -// tslint:disable:no-inferrable-types -// tslint:disable:prefer-const -// tslint:disable:max-line-length -import assert = require("assert"); -import * as fs from "fs"; -import * as events from "events"; -import events2 = require("events"); -import * as zlib from "zlib"; -import * as url from "url"; -import * as util from "util"; -import * as crypto from "crypto"; -import * as tls from "tls"; -import * as http from "http"; -import * as https from "https"; -import * as net from "net"; -import * as tty from "tty"; -import * as dgram from "dgram"; -import * as querystring from "querystring"; -import * as path from "path"; -import * as readline from "readline"; -import * as childProcess from "child_process"; -import * as cluster from "cluster"; -import * as os from "os"; -import * as vm from "vm"; -import * as console2 from "console"; -import * as string_decoder from "string_decoder"; -import * as stream from "stream"; -import * as timers from "timers"; -import * as repl from "repl"; -import * as v8 from "v8"; -import * as dns from "dns"; -import * as async_hooks from "async_hooks"; -import * as http2 from "http2"; -import * as inspector from "inspector"; -import * as perf_hooks from "perf_hooks"; -import Module = require("module"); - -// Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; - -////////////////////////////////////////////////////////// -/// Global Tests : https://nodejs.org/api/global.html /// -////////////////////////////////////////////////////////// -namespace global_tests { - { - let x: NodeModule; - let y: NodeModule; - x.children.push(y); - x.parent = require.main; - require.main = y; - } -} - -////////////////////////////////////////////////////////// -/// Assert Tests : https://nodejs.org/api/assert.html /// -////////////////////////////////////////////////////////// - -namespace assert_tests { - { - assert(1 + 1 - 2 === 0, "The universe isn't how it should."); - - assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - - assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); - - assert.doesNotThrow(() => { - const b = false; - if (b) { throw new Error("a hammer at your face"); } - }, undefined, "What the...*crunch*"); - - assert.equal(3, "3", "uses == comparator"); - - assert.fail('stuff broke'); - - assert.fail('actual', 'expected', 'message'); - - assert.fail(1, 2, undefined, '>'); - - assert.ifError(0); - - assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - - assert.notEqual(1, 2, "uses != comparator"); - - assert.notStrictEqual(2, "2", "uses === comparator"); - - assert.ok(true); - assert.ok(1); - - assert.strictEqual(1, 1, "uses === comparator"); - - assert.throws(() => { throw new Error("a hammer at your face"); }, undefined, "DODGED IT"); - } -} - -//////////////////////////////////////////////////// -/// Events tests : http://nodejs.org/api/events.html -//////////////////////////////////////////////////// - -namespace events_tests { - let emitter: events.EventEmitter; - let event: string | symbol; - let listener: (...args: any[]) => void; - let any: any; - - { - let result: events.EventEmitter; - - result = emitter.addListener(event, listener); - result = emitter.on(event, listener); - result = emitter.once(event, listener); - result = emitter.prependListener(event, listener); - result = emitter.prependOnceListener(event, listener); - result = emitter.removeListener(event, listener); - result = emitter.removeAllListeners(); - result = emitter.removeAllListeners(event); - result = emitter.setMaxListeners(42); - } - - { - let result: number; - - result = events.EventEmitter.defaultMaxListeners; - result = events.EventEmitter.listenerCount(emitter, event); // deprecated - - result = emitter.getMaxListeners(); - result = emitter.listenerCount(event); - } - - { - let result: Function[]; - - result = emitter.listeners(event); - } - - { - let result: boolean; - - result = emitter.emit(event); - result = emitter.emit(event, any); - result = emitter.emit(event, any, any); - result = emitter.emit(event, any, any, any); - } - - { - let result: Array; - - result = emitter.eventNames(); - } - - { - class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } - } - } - - { - new events2(); - } -} - -//////////////////////////////////////////////////// -/// File system tests : http://nodejs.org/api/fs.html -//////////////////////////////////////////////////// - -namespace fs_tests { - { - fs.writeFile("thebible.txt", - "Do unto others as you would have them do unto you.", - assert.ifError); - - fs.write(1234, "test", () => { }); - - fs.writeFile("Harry Potter", - "\"You be wizzing, Harry,\" jived Dumbledore.", - { - encoding: "ascii" - }, - assert.ifError); - - fs.writeFile("testfile", "content", "utf8", assert.ifError); - - fs.writeFileSync("testfile", "content", "utf8"); - fs.writeFileSync("testfile", "content", { encoding: "utf8" }); - } - - { - fs.appendFile("testfile", "foobar", "utf8", assert.ifError); - fs.appendFile("testfile", "foobar", { encoding: "utf8" }, assert.ifError); - fs.appendFileSync("testfile", "foobar", "utf8"); - fs.appendFileSync("testfile", "foobar", { encoding: "utf8" }); - } - - { - var content: string; - var buffer: Buffer; - var stringOrBuffer: string | Buffer; - var nullEncoding: string | null = null; - var stringEncoding: string | null = 'utf8'; - - content = fs.readFileSync('testfile', 'utf8'); - content = fs.readFileSync('testfile', { encoding: 'utf8' }); - stringOrBuffer = fs.readFileSync('testfile', stringEncoding); - stringOrBuffer = fs.readFileSync('testfile', { encoding: stringEncoding }); - - buffer = fs.readFileSync('testfile'); - buffer = fs.readFileSync('testfile', null); - buffer = fs.readFileSync('testfile', { encoding: null }); - stringOrBuffer = fs.readFileSync('testfile', nullEncoding); - stringOrBuffer = fs.readFileSync('testfile', { encoding: nullEncoding }); - - buffer = fs.readFileSync('testfile', { flag: 'r' }); - - fs.readFile('testfile', 'utf8', (err, data) => content = data); - fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); - fs.readFile('testfile', stringEncoding, (err, data) => stringOrBuffer = data); - fs.readFile('testfile', { encoding: stringEncoding }, (err, data) => stringOrBuffer = data); - - fs.readFile('testfile', (err, data) => buffer = data); - fs.readFile('testfile', null, (err, data) => buffer = data); - fs.readFile('testfile', { encoding: null }, (err, data) => buffer = data); - fs.readFile('testfile', nullEncoding, (err, data) => stringOrBuffer = data); - fs.readFile('testfile', { encoding: nullEncoding }, (err, data) => stringOrBuffer = data); - - fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); - } - - { - var errno: number; - fs.readFile('testfile', (err, data) => { - if (err && err.errno) { - errno = err.errno; - } - }); - } - - { - let listS: string[]; - listS = fs.readdirSync('path'); - listS = fs.readdirSync('path', { encoding: 'utf8' }); - listS = fs.readdirSync('path', { encoding: null }); - listS = fs.readdirSync('path', { encoding: undefined }); - listS = fs.readdirSync('path', 'utf8'); - listS = fs.readdirSync('path', null); - listS = fs.readdirSync('path', undefined); - - let listB: Buffer[]; - listB = fs.readdirSync('path', { encoding: 'buffer' }); - listB = fs.readdirSync("path", 'buffer'); - - let enc = 'buffer'; - fs.readdirSync('path', { encoding: enc }); // $ExpectType string[] | Buffer[] - fs.readdirSync('path', { }); // $ExpectType string[] | Buffer[] - } - - { - fs.mkdtemp('/tmp/foo-', (err, folder) => { - console.log(folder); - // Prints: /tmp/foo-itXde2 - }); - } - - { - var tempDir: string; - tempDir = fs.mkdtempSync('/tmp/foo-'); - } - - { - fs.watch('/tmp/foo-', (event, filename) => { - console.log(event, filename); - }); - - fs.watch('/tmp/foo-', 'utf8', (event, filename) => { - console.log(event, filename); - }); - - fs.watch('/tmp/foo-', { - recursive: true, - persistent: true, - encoding: 'utf8' - }, (event, filename) => { - console.log(event, filename); - }); - } - - { - fs.access('/path/to/folder', (err) => { }); - - fs.access(Buffer.from(''), (err) => { }); - - fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - - fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - - fs.accessSync('/path/to/folder'); - - fs.accessSync(Buffer.from('')); - - fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); - - fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); - } - - { - let s: string; - let b: Buffer; - fs.readlink('/path/to/folder', (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', undefined, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', 'utf8', (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', 'buffer', (err, linkString) => b = linkString); - fs.readlink('/path/to/folder', s, (err, linkString) => typeof linkString === 'string' ? s = linkString : b = linkString); - fs.readlink('/path/to/folder', {}, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', { encoding: undefined }, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', { encoding: 'utf8' }, (err, linkString) => s = linkString); - fs.readlink('/path/to/folder', { encoding: 'buffer' }, (err, linkString) => b = linkString); - fs.readlink('/path/to/folder', { encoding: s }, (err, linkString) => typeof linkString === "string" ? s = linkString : b = linkString); - - s = fs.readlinkSync('/path/to/folder'); - s = fs.readlinkSync('/path/to/folder', undefined); - s = fs.readlinkSync('/path/to/folder', 'utf8'); - b = fs.readlinkSync('/path/to/folder', 'buffer'); - const v1 = fs.readlinkSync('/path/to/folder', s); - typeof v1 === "string" ? s = v1 : b = v1; - - s = fs.readlinkSync('/path/to/folder', {}); - s = fs.readlinkSync('/path/to/folder', { encoding: undefined }); - s = fs.readlinkSync('/path/to/folder', { encoding: 'utf8' }); - b = fs.readlinkSync('/path/to/folder', { encoding: 'buffer' }); - const v2 = fs.readlinkSync('/path/to/folder', { encoding: s }); - typeof v2 === "string" ? s = v2 : b = v2; - } - - { - let s: string; - let b: Buffer; - fs.realpath('/path/to/folder', (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath); - fs.realpath('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath); - fs.realpath('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath); - fs.realpath('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath); - fs.realpath('/path/to/folder', { encoding: s }, (err, resolvedPath) => typeof resolvedPath === "string" ? s = resolvedPath : b = resolvedPath); - - s = fs.realpathSync('/path/to/folder'); - s = fs.realpathSync('/path/to/folder', undefined); - s = fs.realpathSync('/path/to/folder', 'utf8'); - b = fs.realpathSync('/path/to/folder', 'buffer'); - const v1 = fs.realpathSync('/path/to/folder', s); - typeof v1 === "string" ? s = v1 : b = v1; - - s = fs.realpathSync('/path/to/folder', {}); - s = fs.realpathSync('/path/to/folder', { encoding: undefined }); - s = fs.realpathSync('/path/to/folder', { encoding: 'utf8' }); - b = fs.realpathSync('/path/to/folder', { encoding: 'buffer' }); - const v2 = fs.realpathSync('/path/to/folder', { encoding: s }); - typeof v2 === "string" ? s = v2 : b = v2; - - // native - fs.realpath.native('/path/to/folder', (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath); - fs.realpath.native('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath); - fs.realpath.native('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath); - fs.realpath.native('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath); - fs.realpath.native('/path/to/folder', { encoding: s }, (err, resolvedPath) => typeof resolvedPath === "string" ? s = resolvedPath : b = resolvedPath); - - s = fs.realpathSync.native('/path/to/folder'); - s = fs.realpathSync.native('/path/to/folder', undefined); - s = fs.realpathSync.native('/path/to/folder', 'utf8'); - b = fs.realpathSync.native('/path/to/folder', 'buffer'); - const v3 = fs.realpathSync.native('/path/to/folder', s); - typeof v3 === "string" ? s = v3 : b = v3; - - s = fs.realpathSync.native('/path/to/folder', {}); - s = fs.realpathSync.native('/path/to/folder', { encoding: undefined }); - s = fs.realpathSync.native('/path/to/folder', { encoding: 'utf8' }); - b = fs.realpathSync.native('/path/to/folder', { encoding: 'buffer' }); - const v4 = fs.realpathSync.native('/path/to/folder', { encoding: s }); - typeof v4 === "string" ? s = v4 : b = v4; - } - - { - fs.copyFile('/path/to/src', '/path/to/dest', (err) => console.error(err)); - fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL, (err) => console.error(err)); - - fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL); - - const cf = util.promisify(fs.copyFile); - cf('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL).then(console.log); - } -} - -/////////////////////////////////////////////////////// -/// Buffer tests : https://nodejs.org/api/buffer.html -/////////////////////////////////////////////////////// - -function bufferTests() { - var utf8Buffer = new Buffer('test'); - var base64Buffer = new Buffer('', 'base64'); - var octets: Uint8Array = null; - var octetBuffer = new Buffer(octets); - var sharedBuffer = new Buffer(octets.buffer); - var copiedBuffer = new Buffer(utf8Buffer); - console.log(Buffer.isBuffer(octetBuffer)); - console.log(Buffer.isEncoding('utf8')); - console.log(Buffer.byteLength('xyz123')); - console.log(Buffer.byteLength('xyz123', 'ascii')); - var result1 = Buffer.concat([utf8Buffer, base64Buffer]); - var result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999); - - // Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64() - { - const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); - buf.swap16(); - buf.swap32(); - buf.swap64(); - } - - // Class Method: Buffer.from(data) - { - // Array - const buf1: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); - // Buffer - const buf2: Buffer = Buffer.from(buf1); - // String - const buf3: Buffer = Buffer.from('this is a tést'); - // ArrayBuffer - const arr: Uint16Array = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; - const buf4: Buffer = Buffer.from(arr.buffer); - } - - // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) - { - const arr: Uint16Array = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; - - let buf: Buffer; - buf = Buffer.from(arr.buffer, 1); - buf = Buffer.from(arr.buffer, 0, 1); - } - - // Class Method: Buffer.from(str[, encoding]) - { - const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); - } - - // Class Method: Buffer.alloc(size[, fill[, encoding]]) - { - const buf1: Buffer = Buffer.alloc(5); - const buf2: Buffer = Buffer.alloc(5, 'a'); - const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); - } - // Class Method: Buffer.allocUnsafe(size) - { - const buf: Buffer = Buffer.allocUnsafe(5); - } - // Class Method: Buffer.allocUnsafeSlow(size) - { - const buf: Buffer = Buffer.allocUnsafeSlow(10); - } - - // Class Method byteLenght - { - let len: number; - len = Buffer.byteLength("foo"); - len = Buffer.byteLength("foo", "utf8"); - - const b = Buffer.from("bar"); - len = Buffer.byteLength(b); - len = Buffer.byteLength(b, "utf16le"); - - const ab = new ArrayBuffer(15); - len = Buffer.byteLength(ab); - len = Buffer.byteLength(ab, "ascii"); - - const dv = new DataView(ab); - len = Buffer.byteLength(dv); - len = Buffer.byteLength(dv, "utf16le"); - } - - // Class Method poolSize - { - let s: number; - s = Buffer.poolSize; - Buffer.poolSize = 4096; - } - - // Test that TS 1.6 works with the 'as Buffer' annotation - // on isBuffer. - var a: Buffer | number; - a = new Buffer(10); - if (Buffer.isBuffer(a)) { - a.writeUInt8(3, 4); - } - - // write* methods return offsets. - var b = new Buffer(16); - var result: number = b.writeUInt32LE(0, 0); - result = b.writeUInt16LE(0, 4); - result = b.writeUInt8(0, 6); - result = b.writeInt8(0, 7); - result = b.writeDoubleLE(0, 8); - - // fill returns the input buffer. - b.fill('a').fill('b'); - - { - let buffer = new Buffer('123'); - let index: number; - index = buffer.indexOf("23"); - index = buffer.indexOf("23", 1); - index = buffer.indexOf("23", 1, "utf8"); - index = buffer.indexOf(23); - index = buffer.indexOf(buffer); - } - - { - let buffer = new Buffer('123'); - let index: number; - index = buffer.lastIndexOf("23"); - index = buffer.lastIndexOf("23", 1); - index = buffer.lastIndexOf("23", 1, "utf8"); - index = buffer.lastIndexOf(23); - index = buffer.lastIndexOf(buffer); - } - - { - let buffer = new Buffer('123'); - let val: [number, number]; - - /* comment out for --target es5 - for (let entry of buffer.entries()) { - val = entry; - } - */ - } - - { - let buffer = new Buffer('123'); - let includes: boolean; - includes = buffer.includes("23"); - includes = buffer.includes("23", 1); - includes = buffer.includes("23", 1, "utf8"); - includes = buffer.includes(23); - includes = buffer.includes(23, 1); - includes = buffer.includes(23, 1, "utf8"); - includes = buffer.includes(buffer); - includes = buffer.includes(buffer, 1); - includes = buffer.includes(buffer, 1, "utf8"); - } - - { - let buffer = new Buffer('123'); - let val: number; - - /* comment out for --target es5 - for (let key of buffer.keys()) { - val = key; - } - */ - } - - { - let buffer = new Buffer('123'); - let val: number; - - /* comment out for --target es5 - for (let value of buffer.values()) { - val = value; - } - */ - } - - // Imported Buffer from buffer module works properly - { - let b = new ImportedBuffer('123'); - b.writeUInt8(0, 6); - let sb = new ImportedSlowBuffer(43); - b.writeUInt8(0, 6); - } - - // Buffer has Uint8Array's buffer field (an ArrayBuffer). - { - let buffer = new Buffer('123'); - let octets = new Uint8Array(buffer.buffer); - } - - // Buffer module, transcode function - { - transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer - - const source: TranscodeEncoding = 'utf8'; - const target: TranscodeEncoding = 'ascii'; - transcode(Buffer.from('€'), source, target); // $ExpectType Buffer - } -} - -//////////////////////////////////////////////////// -/// Url tests : http://nodejs.org/api/url.html -//////////////////////////////////////////////////// - -namespace url_tests { - { - url.format(url.parse('http://www.example.com/xyz')); - - url.format('http://www.example.com/xyz'); - - // https://google.com/search?q=you're%20a%20lizard%2C%20gary - url.format({ - protocol: 'https', - host: "google.com", - pathname: 'search', - query: { q: "you're a lizard, gary" } - }); - - const myURL = new url.URL('https://a:b@你好你好?abc#foo'); - url.format(myURL, { fragment: false, unicode: true, auth: false }); - } - - { - const helloUrl = url.parse('http://example.com/?hello=world', true); - let helloQuery = helloUrl.query['hello']; - assert.equal(helloUrl.query['hello'], 'world'); - - let strUrl = url.parse('http://example.com/?hello=world'); - let queryStr: string = strUrl.query; - - strUrl = url.parse('http://example.com/?hello=world', false); - queryStr = strUrl.query; - - function getBoolean(): boolean { return false; } - const urlUrl = url.parse('http://example.com/?hello=world', getBoolean()); - if (typeof(urlUrl.query) === 'string') { - queryStr = urlUrl.query; - } else if (urlUrl.query) { - helloQuery = urlUrl.query['hello']; - } - } - - { - const ascii: string = url.domainToASCII('español.com'); - const unicode: string = url.domainToUnicode('xn--espaol-zwa.com'); - } - - { - let myURL = new url.URL('https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.hash, '#bar'); - assert.equal(myURL.host, 'example.org:81'); - assert.equal(myURL.hostname, 'example.org'); - assert.equal(myURL.href, 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert.equal(myURL.origin, 'https://example.org:81'); - assert.equal(myURL.password, 'thepwd'); - assert.equal(myURL.username, 'theuser'); - assert.equal(myURL.pathname, '/foo/path'); - assert.equal(myURL.port, "81"); - assert.equal(myURL.protocol, "https:"); - assert.equal(myURL.search, "?query=string"); - assert.equal(myURL.toString(), 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); - assert(myURL.searchParams instanceof url.URLSearchParams); - - myURL.host = 'example.org:82'; - myURL.hostname = 'example.com'; - myURL.href = 'http://other.com'; - myURL.hash = 'baz'; - myURL.password = "otherpwd"; - myURL.username = "otheruser"; - myURL.pathname = "/otherPath"; - myURL.port = "82"; - myURL.protocol = "http"; - myURL.search = "a=b"; - assert.equal(myURL.href, 'http://otheruser:otherpwd@other.com:82/otherPath?a=b#baz'); - - myURL = new url.URL('/foo', 'https://example.org/'); - assert.equal(myURL.href, 'https://example.org/foo'); - assert.equal(myURL.toJSON(), myURL.href); - } - - { - const searchParams = new url.URLSearchParams('abc=123'); - - assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { - assert.equal(name, 'abc'); - assert.equal(value, '123'); - assert.equal(me, searchParams); - }); - - assert.equal(searchParams.get('abc'), '123'); - - searchParams.append('abc', 'xyz'); - - assert.deepEqual(searchParams.getAll('abc'), ['123', 'xyz']); - - const entries = searchParams.entries(); - assert.deepEqual(entries.next(), { value: ["abc", "123"], done: false }); - assert.deepEqual(entries.next(), { value: ["abc", "xyz"], done: false }); - assert.deepEqual(entries.next(), { value: undefined, done: true }); - - const keys = searchParams.keys(); - assert.deepEqual(keys.next(), { value: "abc", done: false }); - assert.deepEqual(keys.next(), { value: "abc", done: false }); - assert.deepEqual(keys.next(), { value: undefined, done: true }); - - const values = searchParams.values(); - assert.deepEqual(values.next(), { value: "123", done: false }); - assert.deepEqual(values.next(), { value: "xyz", done: false }); - assert.deepEqual(values.next(), { value: undefined, done: true }); - - searchParams.set('abc', 'b'); - assert.deepEqual(searchParams.getAll('abc'), ['b']); - - searchParams.delete('a'); - assert(!searchParams.has('a')); - assert.equal(searchParams.get('a'), null); - - searchParams.sort(); - } - - { - const searchParams = new url.URLSearchParams({ - user: 'abc', - query: ['first', 'second'] - }); - - assert.equal(searchParams.toString(), 'user=abc&query=first%2Csecond'); - assert.deepEqual(searchParams.getAll('query'), ['first,second']); - } - - { - // Using an array - let params = new url.URLSearchParams([ - ['user', 'abc'], - ['query', 'first'], - ['query', 'second'] - ]); - assert.equal(params.toString(), 'user=abc&query=first&query=second'); - } -} - -///////////////////////////////////////////////////// -/// util tests : https://nodejs.org/api/util.html /// -///////////////////////////////////////////////////// - -namespace util_tests { - { - // Old and new util.inspect APIs - util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], false, null); - util.inspect(["This is nice"], { - colors: true, - depth: 5, - customInspect: false, - showProxy: true, - maxArrayLength: 10, - breakLength: 20 - }); - util.inspect(["This is nice"], { - colors: true, - depth: null, - customInspect: false, - showProxy: true, - maxArrayLength: null, - breakLength: Infinity - }); - assert(typeof util.inspect.custom === 'symbol'); - - // util.callbackify - // tslint:disable-next-line no-unnecessary-class - class callbackifyTest { - static fn(): Promise { - assert(arguments.length === 0); - - return Promise.resolve(); - } - - static fnE(): Promise { - assert(arguments.length === 0); - - return Promise.reject(new Error('fail')); - } - - static fnT1(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.resolve(); - } - - static fnT1E(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.reject(new Error('fail')); - } - - static fnTResult(): Promise { - assert(arguments.length === 0); - - return Promise.resolve('result'); - } - - static fnTResultE(): Promise { - assert(arguments.length === 0); - - return Promise.reject(new Error('fail')); - } - - static fnT1TResult(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.resolve('result'); - } - - static fnT1TResultE(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.reject(new Error('fail')); - } - - static test(): void { - var cfn = util.callbackify(callbackifyTest.fn); - var cfnE = util.callbackify(callbackifyTest.fnE); - var cfnT1 = util.callbackify(callbackifyTest.fnT1); - var cfnT1E = util.callbackify(callbackifyTest.fnT1E); - var cfnTResult = util.callbackify(callbackifyTest.fnTResult); - var cfnTResultE = util.callbackify(callbackifyTest.fnTResultE); - var cfnT1TResult = util.callbackify(callbackifyTest.fnT1TResult); - var cfnT1TResultE = util.callbackify(callbackifyTest.fnT1TResultE); - - cfn((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); - cfnE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - cfnT1('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); - cfnT1E('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - cfnTResult((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); - cfnTResultE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - cfnT1TResult('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); - cfnT1TResultE('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - } - } - callbackifyTest.test(); - - // util.promisify - var readPromised = util.promisify(fs.readFile); - var sampleRead: Promise = readPromised(__filename).then((data: Buffer): void => { }).catch((error: Error): void => { }); - var arg0: () => Promise = util.promisify((cb: (err: Error, result: number) => void): void => { }); - var arg0NoResult: () => Promise = util.promisify((cb: (err: Error) => void): void => { }); - var arg1: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error, result: number) => void): void => { }); - var arg1NoResult: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error) => void): void => { }); - var cbOptionalError: () => Promise = util.promisify((cb: (err?: Error | null) => void): void => { cb(); }); - assert(typeof util.promisify.custom === 'symbol'); - // util.deprecate - const foo = () => {}; - // $ExpectType () => void - util.deprecate(foo, 'foo() is deprecated, use bar() instead'); - // $ExpectType (fn: T, message: string) => T - util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); - - // util.isDeepStrictEqual - util.isDeepStrictEqual({foo: 'bar'}, {foo: 'bar'}); - - // util.TextDecoder() - var td = new util.TextDecoder(); - new util.TextDecoder("utf-8"); - new util.TextDecoder("utf-8", { fatal: true }); - new util.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); - var ignoreBom: boolean = td.ignoreBOM; - var fatal: boolean = td.fatal; - var encoding: string = td.encoding; - td.decode(new Int8Array(1)); - td.decode(new Int16Array(1)); - td.decode(new Int32Array(1)); - td.decode(new Uint8Array(1)); - td.decode(new Uint16Array(1)); - td.decode(new Uint32Array(1)); - td.decode(new Uint8ClampedArray(1)); - td.decode(new Float32Array(1)); - td.decode(new Float64Array(1)); - td.decode(new DataView(new Int8Array(1).buffer)); - td.decode(new ArrayBuffer(1)); - td.decode(null); - td.decode(null, { stream: true }); - td.decode(new Int8Array(1), { stream: true }); - var decode: string = td.decode(new Int8Array(1)); - - // util.TextEncoder() - var te = new util.TextEncoder(); - var teEncoding: string = te.encoding; - var teEncodeRes: Uint8Array = te.encode("TextEncoder"); - } -} - -//////////////////////////////////////////////////// -/// Stream tests : http://nodejs.org/api/stream.html -//////////////////////////////////////////////////// - -// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options -function stream_readable_pipe_test() { - var rs = fs.createReadStream(Buffer.from('file.txt')); - var r = fs.createReadStream('file.txt'); - var z = zlib.createGzip({ finishFlush: zlib.constants.Z_FINISH }); - var w = fs.createWriteStream('file.txt.gz'); - - assert(typeof z.bytesRead === 'number'); - assert(typeof r.bytesRead === 'number'); - assert(typeof r.path === 'string'); - assert(rs.path instanceof Buffer); - - r.pipe(z).pipe(w); - - z.flush(); - r.close(); - z.close(); - rs.close(); -} - -// helpers -const compressMe = new Buffer("some data"); -const compressMeString = "compress me!"; - -zlib.deflate(compressMe, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflate(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMeString, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); -zlib.deflate(compressMeString, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflate(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -const inflated = zlib.inflateSync(zlib.deflateSync(compressMe)); -const inflatedString = zlib.inflateSync(zlib.deflateSync(compressMeString)); - -zlib.deflateRaw(compressMe, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); -zlib.deflateRaw(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -zlib.deflateRaw(compressMeString, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); -zlib.deflateRaw(compressMeString, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -const inflatedRaw: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMe)); -const inflatedRawString: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMeString)); - -zlib.gzip(compressMe, (err: Error, result: Buffer) => zlib.gunzip(result, (err: Error, result: Buffer) => result)); -zlib.gzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.gunzip(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); -const gunzipped: Buffer = zlib.gunzipSync(zlib.gzipSync(compressMe)); - -zlib.unzip(compressMe, (err: Error, result: Buffer) => result); -zlib.unzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result); -const unzipped: Buffer = zlib.unzipSync(compressMe); - -// Simplified constructors -function simplified_stream_ctor_test() { - new stream.Readable({ - read(size) { - size.toFixed(); - }, - destroy(error, cb) { - error.stack; - cb(error); - } - }); - - new stream.Writable({ - write(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); - }, - writev(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); - }, - destroy(error, cb) { - error.stack; - cb(error); - }, - final(cb) { - cb(null); - } - }); - - new stream.Duplex({ - read(size) { - size.toFixed(); - }, - write(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); - }, - writev(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); - }, - destroy(error, cb) { - error.stack; - cb(error); - }, - readableObjectMode: true, - writableObjectMode: true - }); - - new stream.Transform({ - transform(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); - }, - flush(cb) { - cb(); - }, - read(size) { - size.toFixed(); - }, - write(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); - }, - writev(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); - }, - destroy(error, cb) { - error.stack; - cb(error); - }, - allowHalfOpen: true, - readableObjectMode: true, - writableObjectMode: true - }); -} - -//////////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html /// -//////////////////////////////////////////////////////// - -namespace crypto_tests { - { - // crypto_hash_string_test - var hashResult: string = crypto.createHash('md5').update('world').digest('hex'); - } - - { - // crypto_hash_buffer_test - var hashResult: string = crypto.createHash('md5') - .update(new Buffer('world')).digest('hex'); - } - - { - // crypto_hash_dataview_test - var hashResult: string = crypto.createHash('md5') - .update(new DataView(new Buffer('world').buffer)).digest('hex'); - } - - { - // crypto_hmac_string_test - var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); - } - - { - // crypto_hmac_buffer_test - var hmacResult: string = crypto.createHmac('md5', 'hello') - .update(new Buffer('world')).digest('hex'); - } - - { - // crypto_hmac_dataview_test - var hmacResult: string = crypto.createHmac('md5', 'hello') - .update(new DataView(new Buffer('world').buffer)).digest('hex'); - } - - { - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer | string = hmac.read(); - }); - } - - { - // crypto_cipher_decipher_string_test - let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - let clearText: string = "This is the clear text."; - let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - let cipherText: string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); - - let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - let clearText2: string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); - - assert.equal(clearText2, clearText); - } - - { - // crypto_cipher_decipher_buffer_test - let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - let cipherBuffers: Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); - - let cipherText: Buffer = Buffer.concat(cipherBuffers); - - let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - let decipherBuffers: Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - let clearText2: Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); - } - - { - // crypto_cipher_decipher_dataview_test - let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - let clearText: DataView = new DataView( - new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]).buffer); - let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - let cipherBuffers: Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); - - let cipherText: DataView = new DataView(Buffer.concat(cipherBuffers).buffer); - - let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - let decipherBuffers: Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - let clearText2: Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); - } - - { - let buffer1: Buffer = new Buffer([1, 2, 3, 4, 5]); - let buffer2: Buffer = new Buffer([1, 2, 3, 4, 5]); - let buffer3: Buffer = new Buffer([5, 4, 3, 2, 1]); - - assert(crypto.timingSafeEqual(buffer1, buffer2)); - assert(!crypto.timingSafeEqual(buffer1, buffer3)); - } - - { - let buffer: Buffer = new Buffer(10); - crypto.randomFillSync(buffer); - crypto.randomFillSync(buffer, 2); - crypto.randomFillSync(buffer, 2, 3); - - crypto.randomFill(buffer, (err: Error, buf: Buffer) => void {}); - crypto.randomFill(buffer, 2, (err: Error, buf: Buffer) => void {}); - crypto.randomFill(buffer, 2, 3, (err: Error, buf: Buffer) => void {}); - - let arr: Uint8Array = new Uint8Array(10); - crypto.randomFillSync(arr); - crypto.randomFillSync(arr, 2); - crypto.randomFillSync(arr, 2, 3); - - crypto.randomFill(arr, (err: Error, buf: Uint8Array) => void {}); - crypto.randomFill(arr, 2, (err: Error, buf: Uint8Array) => void {}); - crypto.randomFill(arr, 2, 3, (err: Error, buf: Uint8Array) => void {}); - } -} - -////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html /// -////////////////////////////////////////////////// - -namespace tls_tests { - { - var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", - }); - var blah = ctx.context; - - var connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 - }; - var tlsSocket = tls.connect(connOpts); - - const ciphers: string[] = tls.getCiphers(); - const curve: string = tls.DEFAULT_ECDH_CURVE; - } - - { - let _server: tls.Server; - let _boolean: boolean; - let _func1 = (err: Error, resp: Buffer) => { }; - let _func2 = (err: Error, sessionData: any) => { }; - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - */ - - _server = _server.addListener("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.addListener("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }); - _server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }); - _server = _server.addListener("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }); - _server = _server.addListener("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - let _err: Error; - let _tlsSocket: tls.TLSSocket; - let _any: any; - let _func: Function; - let _buffer: Buffer; - _boolean = _server.emit("tlsClientError", _err, _tlsSocket); - _boolean = _server.emit("newSession", _any, _any, _func1); - _boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func); - _boolean = _server.emit("resumeSession", _any, _func2); - _boolean = _server.emit("secureConnection", _tlsSocket); - - _server = _server.on("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.on("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }); - _server = _server.on("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }); - _server = _server.on("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }); - _server = _server.on("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.once("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.once("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }); - _server = _server.once("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }); - _server = _server.once("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }); - _server = _server.once("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.prependListener("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.prependListener("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }); - _server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }); - _server = _server.prependListener("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }); - _server = _server.prependListener("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => { - let _err: Error = err; - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => { - let _sessionId: any = sessionId; - let _sessionData: any = sessionData; - let _func1 = callback; - }); - _server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => { - let _certificate: Buffer = certificate; - let _issuer: Buffer = issuer; - let _callback: Function = callback; - }); - _server = _server.prependOnceListener("resumeSession", (sessionId, callback) => { - let _sessionId: any = sessionId; - let _func2 = callback; - }); - _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { - let _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - // close callback parameter is optional - _server = _server.close(); - - // close callback parameter can be either nothing (undefined) or an error - _server = _server.close(() => { }); - _server = _server.close((err) => { - if (typeof err !== 'undefined') { const _err: Error = err; } - }); - } - - { - let _TLSSocket: tls.TLSSocket; - let _boolean: boolean; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - */ - - _TLSSocket = _TLSSocket.addListener("OCSPResponse", (response) => { - let _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.addListener("secureConnect", () => { }); - - let _buffer: Buffer; - _boolean = _TLSSocket.emit("OCSPResponse", _buffer); - _boolean = _TLSSocket.emit("secureConnect"); - - _TLSSocket = _TLSSocket.on("OCSPResponse", (response) => { - let _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.on("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.once("OCSPResponse", (response) => { - let _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.once("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependListener("OCSPResponse", (response) => { - let _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.prependListener("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependOnceListener("OCSPResponse", (response) => { - let _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.prependOnceListener("secureConnect", () => { }); - } -} - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html /// -//////////////////////////////////////////////////// - -namespace http_tests { - // http Server - { - var server: http.Server = new http.Server(); - - // test public props - const maxHeadersCount: number = server.maxHeadersCount; - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } - - // http IncomingMessage - // http ServerResponse - { - // incoming - var incoming: http.IncomingMessage = new http.IncomingMessage(new net.Socket()); - - incoming.setEncoding('utf8'); - - // stream - incoming.pause(); - incoming.resume(); - - // response - var res: http.ServerResponse = new http.ServerResponse(incoming); - - // test headers - res.setHeader('Content-Type', 'text/plain'); - var bool: boolean = res.hasHeader('Content-Type'); - var headers: string[] = res.getHeaderNames(); - - // trailers - res.addTrailers([ - ['x-fOo', 'xOxOxOx'], - ['x-foO', 'OxOxOxO'], - ['X-fOo', 'xOxOxOx'], - ['X-foO', 'OxOxOxO'] - ]); - res.addTrailers({ 'x-foo': 'bar' }); - - // writeHead - res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n'); - res.writeHead(200, { 'Transfer-Encoding': 'chunked' }); - res.writeHead(200); - - // write string - res.write('Part of my res.'); - // write buffer - const chunk = Buffer.alloc(16390, 'Й'); - req.write(chunk); - res.write(chunk, 'hex'); - - // end - res.end("end msg"); - // without msg - res.end(); - - // flush - res.flushHeaders(); - } - - // http ClientRequest - { - var req: http.ClientRequest = new http.ClientRequest("https://www.google.com"); - var req: http.ClientRequest = new http.ClientRequest(new url.URL("https://www.google.com")); - var req: http.ClientRequest = new http.ClientRequest({ path: 'http://0.0.0.0' }); - - // header - req.setHeader('Content-Type', 'text/plain'); - var bool: boolean = req.hasHeader('Content-Type'); - var headers: string[] = req.getHeaderNames(); - req.removeHeader('Date'); - - // write - const chunk = Buffer.alloc(16390, 'Й'); - req.write(chunk); - req.write('a'); - req.end(); - - // abort - req.abort(); - - // connection - req.connection.on('pause', () => { }); - - // event - req.on('data', () => { }); - } - - { - // Status codes - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; - } - - { - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); - - var agent: http.Agent = http.globalAgent; - - http.request({ agent: false }); - http.request({ agent }); - http.request({ agent: undefined }); - } - - { - http.request('http://www.example.com/xyz'); - } - - { - // Make sure .listen() and .close() return a Server instance - http.createServer().listen(0).close().address(); - net.createServer().listen(0).close().address(); - } - - { - var request = http.request({ path: 'http://0.0.0.0' }); - request.once('error', () => { }); - request.setNoDelay(true); - request.abort(); - } - - // http request options - { - const requestOpts: http.RequestOptions = { - timeout: 30000 - }; - - const clientArgs: http.ClientRequestArgs = { - timeout: 30000 - }; - } - - // http headers - { - const headers: http.IncomingHttpHeaders = { - 'content-type': 'application/json', - 'set-cookie': [ 'type=ninja', 'language=javascript' ] - }; - } -} - -////////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html /// -////////////////////////////////////////////////////// - -namespace https_tests { - var agent: https.Agent = new https.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256, - maxCachedSessions: 100 - }); - - var agent: https.Agent = https.globalAgent; - - https.request({ - agent: false - }); - https.request({ - agent - }); - https.request({ - agent: undefined - }); - - https.request('http://www.example.com/xyz'); - - https.globalAgent.options.ca = []; - - { - const server = new https.Server(); - - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } -} - -//////////////////////////////////////////////////// -/// TTY tests : http://nodejs.org/api/tty.html -//////////////////////////////////////////////////// - -namespace tty_tests { - let rs: tty.ReadStream; - let ws: tty.WriteStream; - - let rsIsRaw: boolean = rs.isRaw; - rs.setRawMode(true); - - let wsColumns: number = ws.columns; - let wsRows: number = ws.rows; - - let isTTY: boolean = tty.isatty(1); -} - -//////////////////////////////////////////////////// -/// Dgram tests : http://nodejs.org/api/dgram.html -//////////////////////////////////////////////////// - -namespace dgram_tests { - { - var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { - }); - ds.bind(); - ds.bind(41234); - ds.bind(4123, 'localhost'); - ds.bind(4123, 'localhost', () => { }); - ds.bind(4123, () => { }); - ds.bind(() => { }); - const addr: net.AddressInfo | string = ds.address(); - ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { - }); - ds.send(new Buffer("hello"), 5000, "127.0.0.1"); - ds.setMulticastInterface("127.0.0.1"); - ds = dgram.createSocket({ type: "udp4", reuseAddr: true, recvBufferSize: 1000, sendBufferSize: 1000, lookup: dns.lookup }); - } - - { - let _socket: dgram.Socket; - let _boolean: boolean; - let _err: Error; - let _str: string; - let _rinfo: net.AddressInfo; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - */ - - _socket = _socket.addListener("close", () => { }); - _socket = _socket.addListener("error", (err) => { - let _err: Error = err; - }); - _socket = _socket.addListener("listening", () => { }); - _socket = _socket.addListener("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: net.AddressInfo = rinfo; - }); - - _boolean = _socket.emit("close"); - _boolean = _socket.emit("error", _err); - _boolean = _socket.emit("listening"); - _boolean = _socket.emit("message", _str, _rinfo); - - _socket = _socket.on("close", () => { }); - _socket = _socket.on("error", (err) => { - let _err: Error = err; - }); - _socket = _socket.on("listening", () => { }); - _socket = _socket.on("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: net.AddressInfo = rinfo; - }); - - _socket = _socket.once("close", () => { }); - _socket = _socket.once("error", (err) => { - let _err: Error = err; - }); - _socket = _socket.once("listening", () => { }); - _socket = _socket.once("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: net.AddressInfo = rinfo; - }); - - _socket = _socket.prependListener("close", () => { }); - _socket = _socket.prependListener("error", (err) => { - let _err: Error = err; - }); - _socket = _socket.prependListener("listening", () => { }); - _socket = _socket.prependListener("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: net.AddressInfo = rinfo; - }); - - _socket = _socket.prependOnceListener("close", () => { }); - _socket = _socket.prependOnceListener("error", (err) => { - let _err: Error = err; - }); - _socket = _socket.prependOnceListener("listening", () => { }); - _socket = _socket.prependOnceListener("message", (msg, rinfo) => { - let _msg: Buffer = msg; - let _rinfo: net.AddressInfo = rinfo; - }); - } - - { - let ds: dgram.Socket = dgram.createSocket({ - type: 'udp4', - recvBufferSize: 10000, - sendBufferSize: 15000 - }); - - let size: number; - size = ds.getRecvBufferSize(); - ds.setRecvBufferSize(size); - size = ds.getSendBufferSize(); - ds.setSendBufferSize(size); - } -} - -//////////////////////////////////////////////////// -/// Querystring tests : https://nodejs.org/api/querystring.html -//////////////////////////////////////////////////// - -namespace querystring_tests { - interface SampleObject { a: string; b: number; } - - { - let obj: SampleObject; - let sep: string; - let eq: string; - let options: querystring.StringifyOptions; - let result: string; - - result = querystring.stringify(obj); - result = querystring.stringify(obj, sep); - result = querystring.stringify(obj, sep, eq); - result = querystring.stringify(obj, sep, eq); - result = querystring.stringify(obj, sep, eq, options); - } - - { - let str: string; - let sep: string; - let eq: string; - let options: querystring.ParseOptions; - let result: SampleObject; - - result = querystring.parse(str); - result = querystring.parse(str, sep); - result = querystring.parse(str, sep, eq); - result = querystring.parse(str, sep, eq, options); - } - - { - let str: string; - let result: string; - - result = querystring.escape(str); - result = querystring.unescape(str); - } -} - -//////////////////////////////////////////////////// -/// path tests : http://nodejs.org/api/path.html -//////////////////////////////////////////////////// - -namespace path_tests { - path.normalize('/foo/bar//baz/asdf/quux/..'); - - path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); - // returns - // '/foo/bar/baz/asdf' - - try { - path.join('foo', 'bar'); - } catch (error) { } - - path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile'); - // Is similar to: - // - // cd foo/bar - // cd /tmp/file/ - // cd .. - // cd a/../subfile - // pwd - - path.resolve('/foo/bar', './baz'); - // returns - // '/foo/bar/baz' - - path.resolve('/foo/bar', '/tmp/file/'); - // returns - // '/tmp/file' - - path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); - // if currently in /home/myself/node, it returns - // '/home/myself/node/wwwroot/static_files/gif/image.gif' - - path.isAbsolute('/foo/bar'); // true - path.isAbsolute('/baz/..'); // true - path.isAbsolute('qux/'); // false - path.isAbsolute('.'); // false - - path.isAbsolute('//server'); // true - path.isAbsolute('C:/foo/..'); // true - path.isAbsolute('bar\\baz'); // false - path.isAbsolute('.'); // false - - path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'); - // returns - // '..\\..\\impl\\bbb' - - path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); - // returns - // '../../impl/bbb' - - path.dirname('/foo/bar/baz/asdf/quux'); - // returns - // '/foo/bar/baz/asdf' - - path.basename('/foo/bar/baz/asdf/quux.html'); - // returns - // 'quux.html' - - path.basename('/foo/bar/baz/asdf/quux.html', '.html'); - // returns - // 'quux' - - path.extname('index.html'); - // returns - // '.html' - - path.extname('index.coffee.md'); - // returns - // '.md' - - path.extname('index.'); - // returns - // '.' - - path.extname('index'); - // returns - // '' - - 'foo/bar/baz'.split(path.sep); - // returns - // ['foo', 'bar', 'baz'] - - 'foo\\bar\\baz'.split(path.sep); - // returns - // ['foo', 'bar', 'baz'] - - process.env["PATH"]; // $ExpectType string - - path.parse('/home/user/dir/file.txt'); - // returns - // { - // root : "/", - // dir : "/home/user/dir", - // base : "file.txt", - // ext : ".txt", - // name : "file" - // } - - path.parse('C:\\path\\dir\\index.html'); - // returns - // { - // root : "C:\", - // dir : "C:\path\dir", - // base : "index.html", - // ext : ".html", - // name : "index" - // } - - path.format({ - root: "/", - dir: "/home/user/dir", - base: "file.txt", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - path.format({ - root: "/", - dir: "/home/user/dir", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - path.format({ - dir: "/home/user/dir", - base: "file.txt" - }); - // returns - // '/home/user/dir/file.txt' - - path.posix.format({ - root: "/", - dir: "/home/user/dir", - base: "file.txt", - ext: ".txt", - name: "file" - }); - // returns - // '/home/user/dir/file.txt' - - path.posix.format({ - dir: "/home/user/dir", - base: "file.txt" - }); - // returns - // '/home/user/dir/file.txt' - - path.win32.format({ - root: "C:\\", - dir: "C:\\home\\user\\dir", - ext: ".txt", - name: "file" - }); - // returns - // 'C:\home\user\dir\file.txt' - - path.win32.format({ - dir: "C:\\home\\user\\dir", - base: "file.txt" - }); - // returns - // 'C:\home\user\dir\file.txt' -} - -//////////////////////////////////////////////////// -/// readline tests : https://nodejs.org/api/readline.html -//////////////////////////////////////////////////// - -namespace readline_tests { - let rl: readline.ReadLine; - - { - let options: readline.ReadLineOptions; - let input: NodeJS.ReadableStream; - let output: NodeJS.WritableStream; - let completer: readline.Completer; - let terminal: boolean; - - let result: readline.ReadLine; - - result = readline.createInterface(options); - result = readline.createInterface(input); - result = readline.createInterface(input, output); - result = readline.createInterface(input, output, completer); - result = readline.createInterface(input, output, completer, terminal); - result = readline.createInterface({ - input, - completer(str: string): readline.CompleterResult { - return [['test'], 'test']; - } - }); - result = readline.createInterface({ - input, - completer(str: string, callback: (err: any, result: readline.CompleterResult) => void): any { - callback(null, [['test'], 'test']); - } - }); - } - - { - let prompt: string; - - rl.setPrompt(prompt); - } - - { - let preserveCursor: boolean; - - rl.prompt(); - rl.prompt(preserveCursor); - } - - { - let query: string; - let callback: (answer: string) => void; - - rl.question(query, callback); - } - - { - let result: readline.ReadLine; - - result = rl.pause(); - } - - { - let result: readline.ReadLine; - - result = rl.resume(); - } - - { - rl.close(); - } - - { - let data: string | Buffer; - let key: readline.Key; - - rl.write(data); - rl.write(null, key); - } - - { - let stream: NodeJS.WritableStream; - let x: number; - let y: number; - - readline.cursorTo(stream, x); - readline.cursorTo(stream, x, y); - } - - { - let stream: NodeJS.ReadableStream; - let readLineInterface: readline.ReadLine; - - readline.emitKeypressEvents(stream); - readline.emitKeypressEvents(stream, readLineInterface); - } - - { - let stream: NodeJS.WritableStream; - let dx: number | string; - let dy: number | string; - - readline.moveCursor(stream, dx, dy); - } - - { - let stream: NodeJS.WritableStream; - let dir: number; - - readline.clearLine(stream, dir); - } - - { - let stream: NodeJS.WritableStream; - - readline.clearScreenDown(stream); - } - - { - let _rl: readline.ReadLine; - let _boolean: boolean; - - _rl = _rl.addListener("close", () => { }); - _rl = _rl.addListener("line", (input) => { - let _input: any = input; - }); - _rl = _rl.addListener("pause", () => { }); - _rl = _rl.addListener("resume", () => { }); - _rl = _rl.addListener("SIGCONT", () => { }); - _rl = _rl.addListener("SIGINT", () => { }); - _rl = _rl.addListener("SIGTSTP", () => { }); - - _boolean = _rl.emit("close", () => { }); - _boolean = _rl.emit("line", () => { }); - _boolean = _rl.emit("pause", () => { }); - _boolean = _rl.emit("resume", () => { }); - _boolean = _rl.emit("SIGCONT", () => { }); - _boolean = _rl.emit("SIGINT", () => { }); - _boolean = _rl.emit("SIGTSTP", () => { }); - - _rl = _rl.on("close", () => { }); - _rl = _rl.on("line", (input) => { - let _input: any = input; - }); - _rl = _rl.on("pause", () => { }); - _rl = _rl.on("resume", () => { }); - _rl = _rl.on("SIGCONT", () => { }); - _rl = _rl.on("SIGINT", () => { }); - _rl = _rl.on("SIGTSTP", () => { }); - - _rl = _rl.once("close", () => { }); - _rl = _rl.once("line", (input) => { - let _input: any = input; - }); - _rl = _rl.once("pause", () => { }); - _rl = _rl.once("resume", () => { }); - _rl = _rl.once("SIGCONT", () => { }); - _rl = _rl.once("SIGINT", () => { }); - _rl = _rl.once("SIGTSTP", () => { }); - - _rl = _rl.prependListener("close", () => { }); - _rl = _rl.prependListener("line", (input) => { - let _input: any = input; - }); - _rl = _rl.prependListener("pause", () => { }); - _rl = _rl.prependListener("resume", () => { }); - _rl = _rl.prependListener("SIGCONT", () => { }); - _rl = _rl.prependListener("SIGINT", () => { }); - _rl = _rl.prependListener("SIGTSTP", () => { }); - - _rl = _rl.prependOnceListener("close", () => { }); - _rl = _rl.prependOnceListener("line", (input) => { - let _input: any = input; - }); - _rl = _rl.prependOnceListener("pause", () => { }); - _rl = _rl.prependOnceListener("resume", () => { }); - _rl = _rl.prependOnceListener("SIGCONT", () => { }); - _rl = _rl.prependOnceListener("SIGINT", () => { }); - _rl = _rl.prependOnceListener("SIGTSTP", () => { }); - } -} - -//////////////////////////////////////////////////// -/// string_decoder tests : https://nodejs.org/api/string_decoder.html -//////////////////////////////////////////////////// - -namespace string_decoder_tests { - const StringDecoder = string_decoder.StringDecoder; - const buffer = new Buffer('test'); - const decoder1 = new StringDecoder(); - const decoder2 = new StringDecoder('utf8'); - const part1: string = decoder1.write(new Buffer('test')); - const end1: string = decoder1.end(); - const part2: string = decoder2.write(new Buffer('test')); - const end2: string = decoder1.end(new Buffer('test')); -} - -////////////////////////////////////////////////////////////////////// -/// Child Process tests: https://nodejs.org/api/child_process.html /// -////////////////////////////////////////////////////////////////////// - -namespace child_process_tests { - { - childProcess.exec("echo test"); - childProcess.exec("echo test", { windowsHide: true }); - childProcess.spawn("echo", ["test"], { windowsHide: true }); - childProcess.spawnSync("echo test"); - childProcess.spawnSync("echo test", {windowsVerbatimArguments: false}); - } - - { - childProcess.execFile("npm", () => {}); - childProcess.execFile("npm", { windowsHide: true }, () => {}); - childProcess.execFile("npm", ["-v"], () => {}); - childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); - childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); - childProcess.execFile("npm", { encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); - childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); - } - - async function testPromisify() { - const execFile = util.promisify(childProcess.execFile); - let r: { stdout: string | Buffer, stderr: string | Buffer } = await execFile("npm"); - r = await execFile("npm", ["-v"]); - r = await execFile("npm", ["-v"], { encoding: 'utf-8' }); - r = await execFile("npm", ["-v"], { encoding: 'buffer' }); - r = await execFile("npm", { encoding: 'utf-8' }); - r = await execFile("npm", { encoding: 'buffer' }); - } - - { - let _cp: childProcess.ChildProcess; - let _socket: net.Socket; - let _server: net.Server; - let _boolean: boolean; - - _boolean = _cp.send(1); - _boolean = _cp.send('one'); - _boolean = _cp.send({ - type: 'test' - }); - - _boolean = _cp.send(1, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send('one', (error) => { - let _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, (error) => { - let _err: Error = error; - }); - - _boolean = _cp.send(1, _socket); - _boolean = _cp.send('one', _socket); - _boolean = _cp.send({ - type: 'test' - }, _socket); - - _boolean = _cp.send(1, _socket, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send('one', _socket, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, (error) => { - let _err: Error = error; - }); - - _boolean = _cp.send(1, _socket, { - keepOpen: true - }); - _boolean = _cp.send('one', _socket, { - keepOpen: true - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, { - keepOpen: true - }); - - _boolean = _cp.send(1, _socket, { - keepOpen: true - }, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send('one', _socket, { - keepOpen: true - }, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, { - keepOpen: true - }, (error) => { - let _err: Error = error; - }); - - _boolean = _cp.send(1, _server); - _boolean = _cp.send('one', _server); - _boolean = _cp.send({ - type: 'test' - }, _server); - - _boolean = _cp.send(1, _server, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send('one', _server, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _server, (error) => { - let _err: Error = error; - }); - - _boolean = _cp.send(1, _server, { - keepOpen: true - }); - _boolean = _cp.send('one', _server, { - keepOpen: true - }); - _boolean = _cp.send({ - type: 'test' - }, _server, { - keepOpen: true - }); - - _boolean = _cp.send(1, _server, { - keepOpen: true - }, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send('one', _server, { - keepOpen: true - }, (error) => { - let _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _server, { - keepOpen: true - }, (error) => { - let _err: Error = error; - }); - - _cp = _cp.addListener("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.addListener("disconnect", () => { }); - _cp = _cp.addListener("error", (err) => { - let _err: Error = err; - }); - _cp = _cp.addListener("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.addListener("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _boolean = _cp.emit("close", () => { }); - _boolean = _cp.emit("disconnect", () => { }); - _boolean = _cp.emit("error", () => { }); - _boolean = _cp.emit("exit", () => { }); - _boolean = _cp.emit("message", () => { }); - - _cp = _cp.on("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.on("disconnect", () => { }); - _cp = _cp.on("error", (err) => { - let _err: Error = err; - }); - _cp = _cp.on("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.on("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.once("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.once("disconnect", () => { }); - _cp = _cp.once("error", (err) => { - let _err: Error = err; - }); - _cp = _cp.once("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.once("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.prependListener("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.prependListener("disconnect", () => { }); - _cp = _cp.prependListener("error", (err) => { - let _err: Error = err; - }); - _cp = _cp.prependListener("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.prependListener("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.prependOnceListener("close", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.prependOnceListener("disconnect", () => { }); - _cp = _cp.prependOnceListener("error", (err) => { - let _err: Error = err; - }); - _cp = _cp.prependOnceListener("exit", (code, signal) => { - let _code: number = code; - let _signal: string = signal; - }); - _cp = _cp.prependOnceListener("message", (message, sendHandle) => { - let _message: any = message; - let _sendHandle: net.Socket | net.Server = sendHandle; - }); - } - { - process.stdin.setEncoding('utf8'); - - process.stdin.on('readable', () => { - const chunk = process.stdin.read(); - if (chunk !== null) { - process.stdout.write(`data: ${chunk}`); - } - }); - - process.stdin.on('end', () => { - process.stdout.write('end'); - }); - - process.stdin.pipe(process.stdout); - - console.log(process.stdin.isTTY); - console.log(process.stdout.isTTY); - - console.log(process.stdin instanceof net.Socket); - console.log(process.stdout instanceof fs.ReadStream); - - var stdin: stream.Readable = process.stdin; - console.log(stdin instanceof net.Socket); - console.log(stdin instanceof fs.ReadStream); - - var stdout: stream.Writable = process.stdout; - console.log(stdout instanceof net.Socket); - console.log(stdout instanceof fs.WriteStream); - } -} - -////////////////////////////////////////////////////////////////////// -/// cluster tests: https://nodejs.org/api/cluster.html /// -////////////////////////////////////////////////////////////////////// - -namespace cluster_tests { - { - cluster.fork(); - Object.keys(cluster.workers).forEach(key => { - const worker = cluster.workers[key]; - if (worker.isDead()) { - console.log('worker %d is dead', worker.process.pid); - } - }); - } -} - -//////////////////////////////////////////////////// -/// os tests : https://nodejs.org/api/os.html -//////////////////////////////////////////////////// - -namespace os_tests { - { - let result: string; - - result = os.tmpdir(); - result = os.homedir(); - result = os.endianness(); - result = os.hostname(); - result = os.type(); - result = os.arch(); - result = os.release(); - result = os.EOL; - } - - { - let result: number; - - result = os.uptime(); - result = os.totalmem(); - result = os.freemem(); - } - - { - let result: number[]; - - result = os.loadavg(); - } - - { - let result: os.CpuInfo[]; - - result = os.cpus(); - } - - { - let result: { [index: string]: os.NetworkInterfaceInfo[] }; - - result = os.networkInterfaces(); - } - - { - let result: number; - - result = os.constants.signals.SIGHUP; - result = os.constants.signals.SIGINT; - result = os.constants.signals.SIGQUIT; - result = os.constants.signals.SIGILL; - result = os.constants.signals.SIGTRAP; - result = os.constants.signals.SIGABRT; - result = os.constants.signals.SIGIOT; - result = os.constants.signals.SIGBUS; - result = os.constants.signals.SIGFPE; - result = os.constants.signals.SIGKILL; - result = os.constants.signals.SIGUSR1; - result = os.constants.signals.SIGSEGV; - result = os.constants.signals.SIGUSR2; - result = os.constants.signals.SIGPIPE; - result = os.constants.signals.SIGALRM; - result = os.constants.signals.SIGTERM; - result = os.constants.signals.SIGCHLD; - result = os.constants.signals.SIGSTKFLT; - result = os.constants.signals.SIGCONT; - result = os.constants.signals.SIGSTOP; - result = os.constants.signals.SIGTSTP; - result = os.constants.signals.SIGTTIN; - result = os.constants.signals.SIGTTOU; - result = os.constants.signals.SIGURG; - result = os.constants.signals.SIGXCPU; - result = os.constants.signals.SIGXFSZ; - result = os.constants.signals.SIGVTALRM; - result = os.constants.signals.SIGPROF; - result = os.constants.signals.SIGWINCH; - result = os.constants.signals.SIGIO; - result = os.constants.signals.SIGPOLL; - result = os.constants.signals.SIGPWR; - result = os.constants.signals.SIGSYS; - result = os.constants.signals.SIGUNUSED; - } - - { - let result: number; - - result = os.constants.errno.E2BIG; - result = os.constants.errno.EACCES; - result = os.constants.errno.EADDRINUSE; - result = os.constants.errno.EADDRNOTAVAIL; - result = os.constants.errno.EAFNOSUPPORT; - result = os.constants.errno.EAGAIN; - result = os.constants.errno.EALREADY; - result = os.constants.errno.EBADF; - result = os.constants.errno.EBADMSG; - result = os.constants.errno.EBUSY; - result = os.constants.errno.ECANCELED; - result = os.constants.errno.ECHILD; - result = os.constants.errno.ECONNABORTED; - result = os.constants.errno.ECONNREFUSED; - result = os.constants.errno.ECONNRESET; - result = os.constants.errno.EDEADLK; - result = os.constants.errno.EDESTADDRREQ; - result = os.constants.errno.EDOM; - result = os.constants.errno.EDQUOT; - result = os.constants.errno.EEXIST; - result = os.constants.errno.EFAULT; - result = os.constants.errno.EFBIG; - result = os.constants.errno.EHOSTUNREACH; - result = os.constants.errno.EIDRM; - result = os.constants.errno.EILSEQ; - result = os.constants.errno.EINPROGRESS; - result = os.constants.errno.EINTR; - result = os.constants.errno.EINVAL; - result = os.constants.errno.EIO; - result = os.constants.errno.EISCONN; - result = os.constants.errno.EISDIR; - result = os.constants.errno.ELOOP; - result = os.constants.errno.EMFILE; - result = os.constants.errno.EMLINK; - result = os.constants.errno.EMSGSIZE; - result = os.constants.errno.EMULTIHOP; - result = os.constants.errno.ENAMETOOLONG; - result = os.constants.errno.ENETDOWN; - result = os.constants.errno.ENETRESET; - result = os.constants.errno.ENETUNREACH; - result = os.constants.errno.ENFILE; - result = os.constants.errno.ENOBUFS; - result = os.constants.errno.ENODATA; - result = os.constants.errno.ENODEV; - result = os.constants.errno.ENOENT; - result = os.constants.errno.ENOEXEC; - result = os.constants.errno.ENOLCK; - result = os.constants.errno.ENOLINK; - result = os.constants.errno.ENOMEM; - result = os.constants.errno.ENOMSG; - result = os.constants.errno.ENOPROTOOPT; - result = os.constants.errno.ENOSPC; - result = os.constants.errno.ENOSR; - result = os.constants.errno.ENOSTR; - result = os.constants.errno.ENOSYS; - result = os.constants.errno.ENOTCONN; - result = os.constants.errno.ENOTDIR; - result = os.constants.errno.ENOTEMPTY; - result = os.constants.errno.ENOTSOCK; - result = os.constants.errno.ENOTSUP; - result = os.constants.errno.ENOTTY; - result = os.constants.errno.ENXIO; - result = os.constants.errno.EOPNOTSUPP; - result = os.constants.errno.EOVERFLOW; - result = os.constants.errno.EPERM; - result = os.constants.errno.EPIPE; - result = os.constants.errno.EPROTO; - result = os.constants.errno.EPROTONOSUPPORT; - result = os.constants.errno.EPROTOTYPE; - result = os.constants.errno.ERANGE; - result = os.constants.errno.EROFS; - result = os.constants.errno.ESPIPE; - result = os.constants.errno.ESRCH; - result = os.constants.errno.ESTALE; - result = os.constants.errno.ETIME; - result = os.constants.errno.ETIMEDOUT; - result = os.constants.errno.ETXTBSY; - result = os.constants.errno.EWOULDBLOCK; - result = os.constants.errno.EXDEV; - } -} - -//////////////////////////////////////////////////// -/// vm tests : https://nodejs.org/api/vm.html -//////////////////////////////////////////////////// - -namespace vm_tests { - { - const sandbox = { - animal: 'cat', - count: 2 - }; - - const context = vm.createContext(sandbox); - console.log(vm.isContext(context)); - const script = new vm.Script('count += 1; name = "kitty"'); - - for (let i = 0; i < 10; ++i) { - script.runInContext(context); - } - - console.log(util.inspect(sandbox)); - - vm.runInNewContext('count += 1; name = "kitty"', sandbox); - console.log(util.inspect(sandbox)); - } - - { - const sandboxes = [{}, {}, {}]; - - const script = new vm.Script('globalVar = "set"'); - - sandboxes.forEach((sandbox) => { - script.runInNewContext(sandbox); - script.runInThisContext(); - }); - - console.log(util.inspect(sandboxes)); - - var localVar = 'initial value'; - vm.runInThisContext('localVar = "vm";'); - - console.log(localVar); - } - - { - const Debug = vm.runInDebugContext('Debug'); - Debug.scripts().forEach((script: any) => { console.log(script.name); }); - } - - { - vm.runInThisContext('console.log("hello world"', './my-file.js'); - } -} - -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - -namespace timers_tests { - { - let immediateId = timers.setImmediate(() => { console.log("immediate"); }); - timers.clearImmediate(immediateId); - } - { - let counter = 0; - let timeout = timers.setInterval(() => { console.log("interval"); }, 20); - timeout.unref(); - timeout.ref(); - timers.clearInterval(timeout); - } - { - let counter = 0; - let timeout = timers.setTimeout(() => { console.log("timeout"); }, 20); - timeout.unref(); - timeout.ref(); - timers.clearTimeout(timeout); - } - async function testPromisify() { - const setTimeout = util.promisify(timers.setTimeout); - let v: void = await setTimeout(100); // tslint:disable-line no-void-expression void-return - let s: string = await setTimeout(100, ""); - - const setImmediate = util.promisify(timers.setImmediate); - v = await setImmediate(); // tslint:disable-line no-void-expression - s = await setImmediate(""); - } -} - -///////////////////////////////////////////////////////// -/// Errors Tests : https://nodejs.org/api/errors.html /// -///////////////////////////////////////////////////////// - -namespace errors_tests { - { - Error.stackTraceLimit = Infinity; - } - { - const myObject = {}; - Error.captureStackTrace(myObject); - } - { - let frames: NodeJS.CallSite[] = []; - Error.prepareStackTrace(new Error(), frames); - } - { - let frame: NodeJS.CallSite = null; - let frameThis: any = frame.getThis(); - let typeName: string = frame.getTypeName(); - let func: Function = frame.getFunction(); - let funcName: string = frame.getFunctionName(); - let meth: string = frame.getMethodName(); - let fname: string = frame.getFileName(); - let lineno: number = frame.getLineNumber(); - let colno: number = frame.getColumnNumber(); - let evalOrigin: string = frame.getEvalOrigin(); - let isTop: boolean = frame.isToplevel(); - let isEval: boolean = frame.isEval(); - let isNative: boolean = frame.isNative(); - let isConstr: boolean = frame.isConstructor(); - } -} - -/////////////////////////////////////////////////////////// -/// Process Tests : https://nodejs.org/api/process.html /// -/////////////////////////////////////////////////////////// - -import * as p from "process"; -namespace process_tests { - { - var eventEmitter: events.EventEmitter; - eventEmitter = process; // Test that process implements EventEmitter... - - var _p: NodeJS.Process = process; - _p = p; - } - { - assert(process.argv[0] === process.argv0); - } - { - var module: NodeModule | undefined; - module = process.mainModule; - } - { - process.on("message", (req: any) => { }); - process.addListener("beforeExit", (code: number) => { }); - process.once("disconnect", () => { }); - process.prependListener("exit", (code: number) => { }); - process.prependOnceListener("rejectionHandled", (promise: Promise) => { }); - process.on("uncaughtException", (error: Error) => { }); - process.addListener("unhandledRejection", (reason: any, promise: Promise) => { }); - process.once("warning", (warning: Error) => { }); - process.prependListener("message", (message: any, sendHandle: any) => { }); - process.prependOnceListener("SIGBREAK", () => { }); - process.on("newListener", (event: string | symbol, listener: Function) => { }); - process.once("removeListener", (event: string | symbol, listener: Function) => { }); - - const listeners = process.listeners('uncaughtException'); - const oldHandler = listeners[listeners.length - 1]; - process.addListener('uncaughtException', oldHandler); - } - { - function myCb(err: Error): void { - } - process.setUncaughtExceptionCaptureCallback(myCb); - process.setUncaughtExceptionCaptureCallback(null); - const b: boolean = process.hasUncaughtExceptionCaptureCallback(); - } -} - -/////////////////////////////////////////////////////////// -/// Console Tests : https://nodejs.org/api/console.html /// -/////////////////////////////////////////////////////////// - -import * as c from "console"; -namespace console_tests { - { - var _c: Console = console; - _c = c; - } - { - var writeStream = fs.createWriteStream('./index.d.ts'); - var consoleInstance = new console.Console(writeStream); - } - { - console.assert('value'); - console.assert('value', 'message'); - console.assert('value', 'message', 'foo', 'bar'); - console.clear(); - console.count(); - console.count('label'); - console.countReset(); - console.countReset('label'); - console.debug(); - console.debug('message'); - console.debug('message', 'foo', 'bar'); - console.dir('obj'); - console.dir('obj', { depth: 1 }); - console.error(); - console.error('message'); - console.error('message', 'foo', 'bar'); - console.group(); - console.group('label'); - console.group('label1', 'label2'); - console.groupCollapsed(); - console.groupEnd(); - console.info(); - console.info('message'); - console.info('message', 'foo', 'bar'); - console.log(); - console.log('message'); - console.log('message', 'foo', 'bar'); - console.time('label'); - console.timeEnd('label'); - console.trace(); - console.trace('message'); - console.trace('message', 'foo', 'bar'); - console.warn(); - console.warn('message'); - console.warn('message', 'foo', 'bar'); - - // --- Inspector mode only --- - console.markTimeline(); - console.markTimeline('label'); - console.profile(); - console.profile('label'); - console.profileEnd(); - console.profileEnd('label'); - console.table({ foo: 'bar' }); - console.table([{ foo: 'bar' }]); - console.table([{ foo: 'bar' }], ['foo']); - console.timeStamp(); - console.timeStamp('label'); - console.timeline(); - console.timeline('label'); - console.timelineEnd(); - console.timelineEnd('label'); - } -} - -/////////////////////////////////////////////////// -/// Net Tests : https://nodejs.org/api/net.html /// -/////////////////////////////////////////////////// - -namespace net_tests { - { - const connectOpts: net.NetConnectOpts = { - allowHalfOpen: true, - family: 4, - host: "localhost", - port: 443, - timeout: 10E3 - }; - const socket: net.Socket = net.createConnection(connectOpts, (): void => { - // nothing - }); - } - - { - let server = net.createServer(); - // Check methods which return server instances by chaining calls - server = server.listen(0) - .close() - .ref() - .unref(); - - // close callback parameter can be either nothing (undefined) or an error - server = server.close(() => { }); - server = server.close((err) => { - if (typeof err !== 'undefined') { const _err: Error = err; } - }); - - // test the types of the address object fields - let address: net.AddressInfo | string = server.address(); - } - - { - const constructorOpts: net.SocketConstructorOpts = { - fd: 1, - allowHalfOpen: false, - readable: false, - writable: false - }; - - /** - * net.Socket - events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout - */ - let _socket: net.Socket = new net.Socket(constructorOpts); - - let bool: boolean; - let buffer: Buffer; - let error: Error; - let str: string; - let num: number; - - let ipcConnectOpts: net.IpcSocketConnectOpts = { - path: "/" - }; - let tcpConnectOpts: net.TcpSocketConnectOpts = { - family: 4, - hints: 0, - host: "localhost", - localAddress: "10.0.0.1", - localPort: 1234, - lookup: (_hostname: string, _options: dns.LookupOneOptions, _callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void => { - // nothing - }, - port: 80 - }; - _socket = _socket.connect(ipcConnectOpts); - _socket = _socket.connect(ipcConnectOpts, (): void => {}); - _socket = _socket.connect(tcpConnectOpts); - _socket = _socket.connect(tcpConnectOpts, (): void => {}); - _socket = _socket.connect(80, "localhost"); - _socket = _socket.connect(80, "localhost", (): void => {}); - _socket = _socket.connect(80); - _socket = _socket.connect(80, (): void => {}); - - /// addListener - - _socket = _socket.addListener("close", had_error => { - bool = had_error; - }); - _socket = _socket.addListener("connect", () => { }); - _socket = _socket.addListener("data", data => { - buffer = data; - }); - _socket = _socket.addListener("drain", () => { }); - _socket = _socket.addListener("end", () => { }); - _socket = _socket.addListener("error", err => { - error = err; - }); - _socket = _socket.addListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.addListener("timeout", () => { }); - - /// emit - bool = _socket.emit("close", bool); - bool = _socket.emit("connect"); - bool = _socket.emit("data", buffer); - bool = _socket.emit("drain"); - bool = _socket.emit("end"); - bool = _socket.emit("error", error); - bool = _socket.emit("lookup", error, str, str, str); - bool = _socket.emit("lookup", error, str, num, str); - bool = _socket.emit("timeout"); - - /// on - _socket = _socket.on("close", had_error => { - bool = had_error; - }); - _socket = _socket.on("connect", () => { }); - _socket = _socket.on("data", data => { - buffer = data; - }); - _socket = _socket.on("drain", () => { }); - _socket = _socket.on("end", () => { }); - _socket = _socket.on("error", err => { - error = err; - }); - _socket = _socket.on("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.on("timeout", () => { }); - - /// once - _socket = _socket.once("close", had_error => { - bool = had_error; - }); - _socket = _socket.once("connect", () => { }); - _socket = _socket.once("data", data => { - buffer = data; - }); - _socket = _socket.once("drain", () => { }); - _socket = _socket.once("end", () => { }); - _socket = _socket.once("error", err => { - error = err; - }); - _socket = _socket.once("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.once("timeout", () => { }); - - /// prependListener - _socket = _socket.prependListener("close", had_error => { - bool = had_error; - }); - _socket = _socket.prependListener("connect", () => { }); - _socket = _socket.prependListener("data", data => { - buffer = data; - }); - _socket = _socket.prependListener("drain", () => { }); - _socket = _socket.prependListener("end", () => { }); - _socket = _socket.prependListener("error", err => { - error = err; - }); - _socket = _socket.prependListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.prependListener("timeout", () => { }); - - /// prependOnceListener - _socket = _socket.prependOnceListener("close", had_error => { - bool = had_error; - }); - _socket = _socket.prependOnceListener("connect", () => { }); - _socket = _socket.prependOnceListener("data", data => { - buffer = data; - }); - _socket = _socket.prependOnceListener("drain", () => { }); - _socket = _socket.prependOnceListener("end", () => { }); - _socket = _socket.prependOnceListener("error", err => { - error = err; - }); - _socket = _socket.prependOnceListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.prependOnceListener("timeout", () => { }); - - bool = _socket.connecting; - bool = _socket.destroyed; - _socket.destroy(); - } - - { - /** - * net.Server - events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - */ - let _server: net.Server; - - let _socket: net.Socket; - let bool: boolean; - let error: Error; - - /// addListener - _server = _server.addListener("close", () => { }); - _server = _server.addListener("connection", socket => { - _socket = socket; - }); - _server = _server.addListener("error", err => { - error = err; - }); - _server = _server.addListener("listening", () => { }); - - /// emit - bool = _server.emit("close"); - bool = _server.emit("connection", _socket); - bool = _server.emit("error", error); - bool = _server.emit("listening"); - - /// once - _server = _server.once("close", () => { }); - _server = _server.once("connection", socket => { - _socket = socket; - }); - _server = _server.once("error", err => { - error = err; - }); - _server = _server.once("listening", () => { }); - - /// prependListener - _server = _server.prependListener("close", () => { }); - _server = _server.prependListener("connection", socket => { - _socket = socket; - }); - _server = _server.prependListener("error", err => { - error = err; - }); - _server = _server.prependListener("listening", () => { }); - - /// prependOnceListener - _server = _server.prependOnceListener("close", () => { }); - _server = _server.prependOnceListener("connection", socket => { - _socket = socket; - }); - _server = _server.prependOnceListener("error", err => { - error = err; - }); - _server = _server.prependOnceListener("listening", () => { }); - } -} - -///////////////////////////////////////////////////// -/// repl Tests : https://nodejs.org/api/repl.html /// -///////////////////////////////////////////////////// - -namespace repl_tests { - { - let _server: repl.REPLServer; - let _boolean: boolean; - const _ctx: vm.Context = {}; - - _server = _server.addListener("exit", () => { }); - _server = _server.addListener("reset", () => { }); - - _boolean = _server.emit("exit", () => { }); - _boolean = _server.emit("reset", _ctx); - - _server = _server.on("exit", () => { }); - _server = _server.on("reset", () => { }); - - _server = _server.once("exit", () => { }); - _server = _server.once("reset", () => { }); - - _server = _server.prependListener("exit", () => { }); - _server = _server.prependListener("reset", () => { }); - - _server = _server.prependOnceListener("exit", () => { }); - _server = _server.prependOnceListener("reset", () => { }); - - _server.outputStream.write("test"); - const line = _server.inputStream.read(); - - _server.clearBufferedCommand(); - _server.displayPrompt(); - _server.displayPrompt(true); - _server.defineCommand("cmd", function(text) { - // $ExpectType string - text; - // $ExpectType REPLServer - this; - }); - _server.defineCommand("cmd", { - help: "", - action(text) { - // $ExpectType string - text; - // $ExpectType REPLServer - this; - } - }); - - repl.start({ - eval() { - // $ExpectType REPLServer - this; - }, - writer() { - // $ExpectType REPLServer - this; - return ""; - } - }); - - function test() { - throw new repl.Recoverable(new Error("test")); - } - } -} - -/////////////////////////////////////////////////// -/// DNS Tests : https://nodejs.org/api/dns.html /// -/////////////////////////////////////////////////// - -namespace dns_tests { - dns.lookup("nodejs.org", (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 4, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 6, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", {}, (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup( - "nodejs.org", - { - family: 4, - hints: dns.ADDRCONFIG | dns.V4MAPPED, - all: false - }, - (err, address, family) => { - const _err: NodeJS.ErrnoException = err; - const _address: string = address; - const _family: number = family; - } - ); - dns.lookup("nodejs.org", { all: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException = err; - const _address: dns.LookupAddress[] = addresses; - }); - - function trueOrFalse(): boolean { - return Math.random() > 0.5 ? true : false; - } - dns.lookup("nodejs.org", { all: trueOrFalse() }, (err, addresses, family) => { - const _err: NodeJS.ErrnoException = err; - const _addresses: string | dns.LookupAddress[] = addresses; - const _family: number | undefined = family; - }); - - dns.lookupService("127.0.0.1", 0, (err, hostname, service) => { - const _err: NodeJS.ErrnoException = err; - const _hostname: string = hostname; - const _service: string = service; - }); - - dns.resolve("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "A", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "AAAA", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve("nodejs.org", "MX", (err, addresses) => { - const _addresses: dns.MxRecord[] = addresses; - }); - - dns.resolve4("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve4("nodejs.org", { ttl: true }, (err, addresses) => { - const _addresses: dns.RecordWithTtl[] = addresses; - }); - { - const ttl = false; - dns.resolve4("nodejs.org", { ttl }, (err, addresses) => { - const _addresses: string[] | dns.RecordWithTtl[] = addresses; - }); - } - - dns.resolve6("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - dns.resolve6("nodejs.org", { ttl: true }, (err, addresses) => { - const _addresses: dns.RecordWithTtl[] = addresses; - }); - { - const ttl = false; - dns.resolve6("nodejs.org", { ttl }, (err, addresses) => { - const _addresses: string[] | dns.RecordWithTtl[] = addresses; - }); - } - { - const resolver = new dns.Resolver(); - resolver.setServers(["4.4.4.4"]); - resolver.resolve("nodejs.org", (err, addresses) => { - const _addresses: string[] = addresses; - }); - resolver.cancel(); - } -} - -/***************************************************************************** - * * - * The following tests are the modules not mentioned in document but existed * - * * - *****************************************************************************/ - -/////////////////////////////////////////////////////////// -/// Constants Tests /// -/////////////////////////////////////////////////////////// - -import * as constants from 'constants'; -import { PerformanceObserver, PerformanceObserverCallback } from "perf_hooks"; -namespace constants_tests { - var str: string; - var num: number; - num = constants.SIGHUP; - num = constants.SIGINT; - num = constants.SIGQUIT; - num = constants.SIGILL; - num = constants.SIGTRAP; - num = constants.SIGABRT; - num = constants.SIGIOT; - num = constants.SIGBUS; - num = constants.SIGFPE; - num = constants.SIGKILL; - num = constants.SIGUSR1; - num = constants.SIGSEGV; - num = constants.SIGUSR2; - num = constants.SIGPIPE; - num = constants.SIGALRM; - num = constants.SIGTERM; - num = constants.SIGCHLD; - num = constants.SIGSTKFLT; - num = constants.SIGCONT; - num = constants.SIGSTOP; - num = constants.SIGTSTP; - num = constants.SIGTTIN; - num = constants.SIGTTOU; - num = constants.SIGURG; - num = constants.SIGXCPU; - num = constants.SIGXFSZ; - num = constants.SIGVTALRM; - num = constants.SIGPROF; - num = constants.SIGWINCH; - num = constants.SIGIO; - num = constants.SIGPOLL; - num = constants.SIGPWR; - num = constants.SIGSYS; - num = constants.SIGUNUSED; - num = constants.O_RDONLY; - num = constants.O_WRONLY; - num = constants.O_RDWR; - num = constants.S_IFMT; - num = constants.S_IFREG; - num = constants.S_IFDIR; - num = constants.S_IFCHR; - num = constants.S_IFBLK; - num = constants.S_IFIFO; - num = constants.S_IFLNK; - num = constants.S_IFSOCK; - num = constants.O_CREAT; - num = constants.O_EXCL; - num = constants.O_NOCTTY; - num = constants.O_TRUNC; - num = constants.O_APPEND; - num = constants.O_DIRECTORY; - num = constants.O_NOATIME; - num = constants.O_NOFOLLOW; - num = constants.O_SYNC; - num = constants.O_DSYNC; - num = constants.O_DIRECT; - num = constants.O_NONBLOCK; - num = constants.S_IRWXU; - num = constants.S_IRUSR; - num = constants.S_IWUSR; - num = constants.S_IXUSR; - num = constants.S_IRWXG; - num = constants.S_IRGRP; - num = constants.S_IWGRP; - num = constants.S_IXGRP; - num = constants.S_IRWXO; - num = constants.S_IROTH; - num = constants.S_IWOTH; - num = constants.S_IXOTH; - num = constants.F_OK; - num = constants.R_OK; - num = constants.W_OK; - num = constants.X_OK; - num = constants.SSL_OP_ALL; - num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION; - num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE; - num = constants.SSL_OP_CISCO_ANYCONNECT; - num = constants.SSL_OP_COOKIE_EXCHANGE; - num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG; - num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; - num = constants.SSL_OP_EPHEMERAL_RSA; - num = constants.SSL_OP_LEGACY_SERVER_CONNECT; - num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER; - num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG; - num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING; - num = constants.SSL_OP_NETSCAPE_CA_DN_BUG; - num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG; - num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG; - num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; - num = constants.SSL_OP_NO_COMPRESSION; - num = constants.SSL_OP_NO_QUERY_MTU; - num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION; - num = constants.SSL_OP_NO_SSLv2; - num = constants.SSL_OP_NO_SSLv3; - num = constants.SSL_OP_NO_TICKET; - num = constants.SSL_OP_NO_TLSv1; - num = constants.SSL_OP_NO_TLSv1_1; - num = constants.SSL_OP_NO_TLSv1_2; - num = constants.SSL_OP_PKCS1_CHECK_1; - num = constants.SSL_OP_PKCS1_CHECK_2; - num = constants.SSL_OP_SINGLE_DH_USE; - num = constants.SSL_OP_SINGLE_ECDH_USE; - num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG; - num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG; - num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG; - num = constants.SSL_OP_TLS_D5_BUG; - num = constants.SSL_OP_TLS_ROLLBACK_BUG; - num = constants.ENGINE_METHOD_RSA; - num = constants.ENGINE_METHOD_DSA; - num = constants.ENGINE_METHOD_DH; - num = constants.ENGINE_METHOD_RAND; - num = constants.ENGINE_METHOD_ECDH; - num = constants.ENGINE_METHOD_ECDSA; - num = constants.ENGINE_METHOD_CIPHERS; - num = constants.ENGINE_METHOD_DIGESTS; - num = constants.ENGINE_METHOD_STORE; - num = constants.ENGINE_METHOD_PKEY_METHS; - num = constants.ENGINE_METHOD_PKEY_ASN1_METHS; - num = constants.ENGINE_METHOD_ALL; - num = constants.ENGINE_METHOD_NONE; - num = constants.DH_CHECK_P_NOT_SAFE_PRIME; - num = constants.DH_CHECK_P_NOT_PRIME; - num = constants.DH_UNABLE_TO_CHECK_GENERATOR; - num = constants.DH_NOT_SUITABLE_GENERATOR; - num = constants.NPN_ENABLED; - num = constants.ALPN_ENABLED; - num = constants.RSA_PKCS1_PADDING; - num = constants.RSA_SSLV23_PADDING; - num = constants.RSA_NO_PADDING; - num = constants.RSA_PKCS1_OAEP_PADDING; - num = constants.RSA_X931_PADDING; - num = constants.RSA_PKCS1_PSS_PADDING; - num = constants.POINT_CONVERSION_COMPRESSED; - num = constants.POINT_CONVERSION_UNCOMPRESSED; - num = constants.POINT_CONVERSION_HYBRID; - str = constants.defaultCoreCipherList; - str = constants.defaultCipherList; -} - -//////////////////////////////////////////////////// -/// v8 tests : https://nodejs.org/api/v8.html -//////////////////////////////////////////////////// - -namespace v8_tests { - const heapStats = v8.getHeapStatistics(); - const heapSpaceStats = v8.getHeapSpaceStatistics(); - - const zapsGarbage: number = heapStats.does_zap_garbage; - - v8.setFlagsFromString('--collect_maps'); -} - -//////////////////////////////////////////////////// -/// PerfHooks tests : https://nodejs.org/api/perf_hooks.html -//////////////////////////////////////////////////// -namespace perf_hooks_tests { - perf_hooks.performance.mark('start'); - ( - () => {} - )(); - perf_hooks.performance.mark('end'); - - const { duration } = perf_hooks.performance.getEntriesByName('discover')[0]; - const timeOrigin = perf_hooks.performance.timeOrigin; - - const performanceObserverCallback: PerformanceObserverCallback = (list, obs) => { - const { - duration, - entryType, - name, - startTime, - } = list.getEntries()[0]; - obs.disconnect(); - perf_hooks.performance.clearFunctions(); - }; - const obs = new perf_hooks.PerformanceObserver(performanceObserverCallback); - obs.observe({ - entryTypes: ['function'], - buffered: true, - }); -} - -//////////////////////////////////////////////////// -/// AsyncHooks tests : https://nodejs.org/api/async_hooks.html -//////////////////////////////////////////////////// -namespace async_hooks_tests { - const hooks: async_hooks.HookCallbacks = { - init() {}, - before() {}, - after() {}, - destroy() {}, - promiseResolve() {}, - }; - - const asyncHook = async_hooks.createHook(hooks); - - asyncHook.enable().disable().enable(); - - const tId: number = async_hooks.triggerAsyncId(); - const eId: number = async_hooks.executionAsyncId(); - - class TestResource extends async_hooks.AsyncResource { - constructor() { - super('TEST_RESOURCE'); - } - } - - class AnotherTestResource extends async_hooks.AsyncResource { - constructor() { - super('TEST_RESOURCE', 42); - const aId: number = this.asyncId(); - const tId: number = this.triggerAsyncId(); - } - run() { - this.runInAsyncScope(() => {}); - this.runInAsyncScope(Array.prototype.find, [], () => true); - } - destroy() { - this.emitDestroy(); - } - } - - // check AsyncResource constructor options. - new async_hooks.AsyncResource(''); - new async_hooks.AsyncResource('', 0); - new async_hooks.AsyncResource('', {}); - new async_hooks.AsyncResource('', { triggerAsyncId: 0 }); - new async_hooks.AsyncResource('', { - triggerAsyncId: 0, - requireManualDestroy: true - }); -} - -//////////////////////////////////////////////////// -/// zlib tests : http://nodejs.org/api/zlib.html /// -//////////////////////////////////////////////////// - -namespace zlib_tests { - { - const gzipped = zlib.gzipSync('test'); - const unzipped = zlib.gunzipSync(gzipped.toString()); - } - - { - const deflate = zlib.deflateSync('test'); - const inflate = zlib.inflateSync(deflate.toString()); - } -} - -/////////////////////////////////////////////////////////// -/// HTTP/2 Tests /// -/////////////////////////////////////////////////////////// - -namespace http2_tests { - // Headers & Settings - { - let headers: http2.OutgoingHttpHeaders = { - ':status': 200, - 'content-type': 'text-plain', - ABC: ['has', 'more', 'than', 'one', 'value'], - undef: undefined - }; - - let settings: http2.Settings = { - headerTableSize: 0, - enablePush: true, - initialWindowSize: 0, - maxFrameSize: 0, - maxConcurrentStreams: 0, - maxHeaderListSize: 0 - }; - } - - // Http2Session - { - let http2Session: http2.Http2Session; - let ee: events.EventEmitter = http2Session; - - http2Session.on('close', () => {}); - http2Session.on('connect', (session: http2.Http2Session, socket: net.Socket) => {}); - http2Session.on('error', (err: Error) => {}); - http2Session.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); - http2Session.on('goaway', (errorCode: number, lastStreamID: number, opaqueData: Buffer) => {}); - http2Session.on('localSettings', (settings: http2.Settings) => {}); - http2Session.on('remoteSettings', (settings: http2.Settings) => {}); - http2Session.on('stream', (stream: http2.Http2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - http2Session.on('timeout', () => {}); - - http2Session.destroy(); - - let alpnProtocol: string = http2Session.alpnProtocol; - let destroyed: boolean = http2Session.destroyed; - let encrypted: boolean = http2Session.encrypted; - let originSet: string[] = http2Session.originSet; - let pendingSettingsAck: boolean = http2Session.pendingSettingsAck; - let settings: http2.Settings = http2Session.localSettings; - let closed: boolean = http2Session.closed; - settings = http2Session.remoteSettings; - - http2Session.ref(); - http2Session.unref(); - - let headers: http2.OutgoingHttpHeaders; - let options: http2.ClientSessionRequestOptions = { - endStream: true, - exclusive: true, - parent: 0, - weight: 0, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {} - }; - (http2Session as http2.ClientHttp2Session).request(); - (http2Session as http2.ClientHttp2Session).request(headers); - (http2Session as http2.ClientHttp2Session).request(headers, options); - - let stream: http2.Http2Stream; - http2Session.rstStream(stream); - http2Session.rstStream(stream, 0); - - http2Session.setTimeout(100, () => {}); - http2Session.close(() => {}); - - let socket: net.Socket | tls.TLSSocket = http2Session.socket; - let state: http2.SessionState = http2Session.state; - state = { - effectiveLocalWindowSize: 0, - effectiveRecvDataLength: 0, - nextStreamID: 0, - localWindowSize: 0, - lastProcStreamID: 0, - remoteWindowSize: 0, - outboundQueueSize: 0, - deflateDynamicTableSize: 0, - inflateDynamicTableSize: 0 - }; - - http2Session.priority(stream, { - exclusive: true, - parent: 0, - weight: 0, - silent: true - }); - - http2Session.settings(settings); - } - - // Http2Stream - { - let http2Stream: http2.Http2Stream; - let duplex: stream.Duplex = http2Stream; - - http2Stream.on('aborted', () => {}); - http2Stream.on('error', (err: Error) => {}); - http2Stream.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); - http2Stream.on('streamClosed', (code: number) => {}); - http2Stream.on('timeout', () => {}); - http2Stream.on('trailers', (trailers: http2.IncomingHttpHeaders, flags: number) => {}); - - let aborted: boolean = http2Stream.aborted; - let closed: boolean = http2Stream.closed; - let destroyed: boolean = http2Stream.destroyed; - let pending: boolean = http2Stream.pending; - - http2Stream.priority({ - exclusive: true, - parent: 0, - weight: 0, - silent: true - }); - - let sesh: http2.Http2Session = http2Stream.session; - - http2Stream.setTimeout(100, () => {}); - - let state: http2.StreamState = http2Stream.state; - state = { - localWindowSize: 0, - state: 0, - streamLocalClose: 0, - streamRemoteClose: 0, - sumDependencyWeight: 0, - weight: 0 - }; - - // ClientHttp2Stream - let clientHttp2Stream: http2.ClientHttp2Stream; - clientHttp2Stream.on('headers', (headers: http2.IncomingHttpHeaders, flags: number) => {}); - clientHttp2Stream.on('push', (headers: http2.IncomingHttpHeaders, flags: number) => {}); - clientHttp2Stream.on('response', (headers: http2.IncomingHttpHeaders, flags: number) => {}); - - // ServerHttp2Stream - let serverHttp2Stream: http2.ServerHttp2Stream; - let headers: http2.OutgoingHttpHeaders; - - serverHttp2Stream.additionalHeaders(headers); - let headerSent: boolean = serverHttp2Stream.headersSent; - let pushAllowed: boolean = serverHttp2Stream.pushAllowed; - serverHttp2Stream.pushStream(headers, (err: Error | null, pushStream: http2.ServerHttp2Stream, headers: http2.OutgoingHttpHeaders) => {}); - - let options: http2.ServerStreamResponseOptions = { - endStream: true, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {} - }; - serverHttp2Stream.respond(); - serverHttp2Stream.respond(headers); - serverHttp2Stream.respond(headers, options); - - let options2: http2.ServerStreamFileResponseOptions = { - statCheck: (stats: fs.Stats, headers: http2.OutgoingHttpHeaders, statOptions: http2.StatOptions) => {}, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {}, - offset: 0, - length: 0 - }; - serverHttp2Stream.respondWithFD(0); - serverHttp2Stream.respondWithFD(0, headers); - serverHttp2Stream.respondWithFD(0, headers, options2); - serverHttp2Stream.respondWithFD(0, headers, {statCheck: () => false}); - let options3: http2.ServerStreamFileResponseOptionsWithError = { - onError: (err: NodeJS.ErrnoException) => {}, - statCheck: (stats: fs.Stats, headers: http2.OutgoingHttpHeaders, statOptions: http2.StatOptions) => {}, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {}, - offset: 0, - length: 0 - }; - serverHttp2Stream.respondWithFile(''); - serverHttp2Stream.respondWithFile('', headers); - serverHttp2Stream.respondWithFile('', headers, options3); - serverHttp2Stream.respondWithFile('', headers, {statCheck: () => false}); - } - - // Http2Server / Http2SecureServer - { - let http2Server: http2.Http2Server; - let http2SecureServer: http2.Http2SecureServer; - let s1: net.Server = http2Server; - let s2: tls.Server = http2SecureServer; - [http2Server, http2SecureServer].forEach((server) => { - server.on('sessionError', (err: Error) => {}); - server.on('checkContinue', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - server.on('stream', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - server.on('request', (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => {}); - server.on('timeout', () => {}); - }); - - http2SecureServer.on('unknownProtocol', (socket: tls.TLSSocket) => {}); - } - - // Public API (except constants) - { - let settings: http2.Settings; - let serverOptions: http2.ServerOptions = { - maxDeflateDynamicTableSize: 0, - maxReservedRemoteStreams: 0, - maxSendHeaderBlockLength: 0, - paddingStrategy: 0, - peerMaxConcurrentStreams: 0, - selectPadding: (frameLen: number, maxFrameLen: number) => 0, - settings - }; - // tslint:disable-next-line prefer-object-spread (ts2.1 feature) - let secureServerOptions: http2.SecureServerOptions = Object.assign({}, serverOptions); - secureServerOptions.ca = ''; - let onRequestHandler = (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => { - // Http2ServerRequest - - let readable: stream.Readable = request; - let incomingHeaders: http2.IncomingHttpHeaders = request.headers; - incomingHeaders = request.trailers; - let httpVersion: string = request.httpVersion; - let method: string = request.method; - let rawHeaders: string[] = request.rawHeaders; - rawHeaders = request.rawTrailers; - let socket: net.Socket | tls.TLSSocket = request.socket; - let stream: http2.ServerHttp2Stream = request.stream; - let url: string = request.url; - - request.setTimeout(0, () => {}); - request.on('aborted', (hadError: boolean, code: number) => {}); - - // Http2ServerResponse - - let outgoingHeaders: http2.OutgoingHttpHeaders; - response.addTrailers(outgoingHeaders); - socket = response.connection; - let finished: boolean = response.finished; - response.sendDate = true; - response.statusCode = 200; - response.statusMessage = ''; - socket = response.socket; - stream = response.stream; - - method = response.getHeader(':method'); - let headers: string[] = response.getHeaderNames(); - outgoingHeaders = response.getHeaders(); - let hasMethod = response.hasHeader(':method'); - response.removeHeader(':method'); - response.setHeader(':method', 'GET'); - response.setHeader(':status', 200); - response.setHeader('some-list', ['', '']); - let headersSent: boolean = response.headersSent; - - response.setTimeout(0, () => {}); - response.createPushResponse(outgoingHeaders, (err: Error | null, res: http2.Http2ServerResponse) => {}); - - response.writeContinue(); - response.writeHead(200); - response.writeHead(200, outgoingHeaders); - response.writeHead(200, 'OK', outgoingHeaders); - response.writeHead(200, 'OK'); - response.write(''); - response.write('', (err: Error) => {}); - response.write('', 'utf8'); - response.write('', 'utf8', (err: Error) => {}); - response.write(Buffer.from([])); - response.write(Buffer.from([]), (err: Error) => {}); - response.write(Buffer.from([]), 'utf8'); - response.write(Buffer.from([]), 'utf8', (err: Error) => {}); - response.end(); - response.end(() => {}); - response.end(''); - response.end('', () => {}); - response.end('', 'utf8'); - response.end('', 'utf8', () => {}); - response.end(Buffer.from([])); - response.end(Buffer.from([]), () => {}); - response.end(Buffer.from([]), 'utf8'); - response.end(Buffer.from([]), 'utf8', () => {}); - - request.on('aborted', (hadError: boolean, code: number) => {}); - request.on('close', () => {}); - request.on('drain', () => {}); - request.on('error', (error: Error) => {}); - request.on('finish', () => {}); - }; - - let http2Server: http2.Http2Server; - let http2SecureServer: http2.Http2SecureServer; - - http2Server = http2.createServer(); - http2Server = http2.createServer(serverOptions); - http2Server = http2.createServer(onRequestHandler); - http2Server = http2.createServer(serverOptions, onRequestHandler); - - http2SecureServer = http2.createSecureServer(); - http2SecureServer = http2.createSecureServer(secureServerOptions); - http2SecureServer = http2.createSecureServer(onRequestHandler); - http2SecureServer = http2.createSecureServer(secureServerOptions, onRequestHandler); - - let clientSessionOptions: http2.ClientSessionOptions = { - maxDeflateDynamicTableSize: 0, - maxReservedRemoteStreams: 0, - maxSendHeaderBlockLength: 0, - paddingStrategy: 0, - peerMaxConcurrentStreams: 0, - selectPadding: (frameLen: number, maxFrameLen: number) => 0, - settings - }; - // tslint:disable-next-line prefer-object-spread (ts2.1 feature) - let secureClientSessionOptions: http2.SecureClientSessionOptions = Object.assign({}, clientSessionOptions); - secureClientSessionOptions.ca = ''; - let onConnectHandler = (session: http2.Http2Session, socket: net.Socket) => {}; - - let serverHttp2Session: http2.ServerHttp2Session; - - serverHttp2Session.altsvc('', ''); - serverHttp2Session.altsvc('', 0); - serverHttp2Session.altsvc('', new url.URL('')); - serverHttp2Session.altsvc('', { origin: '' }); - serverHttp2Session.altsvc('', { origin: 0 }); - serverHttp2Session.altsvc('', { origin: new url.URL('') }); - - let clientHttp2Session: http2.ClientHttp2Session; - - clientHttp2Session = http2.connect(''); - clientHttp2Session = http2.connect('', onConnectHandler); - clientHttp2Session = http2.connect('', clientSessionOptions); - clientHttp2Session = http2.connect('', clientSessionOptions, onConnectHandler); - clientHttp2Session = http2.connect('', secureClientSessionOptions); - clientHttp2Session = http2.connect('', secureClientSessionOptions, onConnectHandler); - clientHttp2Session.on('altsvc', (alt: string, origin: string, number: number) => {}); - - settings = http2.getDefaultSettings(); - settings = http2.getPackedSettings(settings); - settings = http2.getUnpackedSettings(Buffer.from([])); - settings = http2.getUnpackedSettings(Uint8Array.from([])); - } - - // constants - { - const constants = http2.constants; - let num: number; - let str: string; - num = constants.NGHTTP2_SESSION_SERVER; - num = constants.NGHTTP2_SESSION_CLIENT; - num = constants.NGHTTP2_STREAM_STATE_IDLE; - num = constants.NGHTTP2_STREAM_STATE_OPEN; - num = constants.NGHTTP2_STREAM_STATE_RESERVED_LOCAL; - num = constants.NGHTTP2_STREAM_STATE_RESERVED_REMOTE; - num = constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL; - num = constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE; - num = constants.NGHTTP2_STREAM_STATE_CLOSED; - num = constants.NGHTTP2_NO_ERROR; - num = constants.NGHTTP2_PROTOCOL_ERROR; - num = constants.NGHTTP2_INTERNAL_ERROR; - num = constants.NGHTTP2_FLOW_CONTROL_ERROR; - num = constants.NGHTTP2_SETTINGS_TIMEOUT; - num = constants.NGHTTP2_STREAM_CLOSED; - num = constants.NGHTTP2_FRAME_SIZE_ERROR; - num = constants.NGHTTP2_REFUSED_STREAM; - num = constants.NGHTTP2_CANCEL; - num = constants.NGHTTP2_COMPRESSION_ERROR; - num = constants.NGHTTP2_CONNECT_ERROR; - num = constants.NGHTTP2_ENHANCE_YOUR_CALM; - num = constants.NGHTTP2_INADEQUATE_SECURITY; - num = constants.NGHTTP2_HTTP_1_1_REQUIRED; - num = constants.NGHTTP2_ERR_FRAME_SIZE_ERROR; - num = constants.NGHTTP2_FLAG_NONE; - num = constants.NGHTTP2_FLAG_END_STREAM; - num = constants.NGHTTP2_FLAG_END_HEADERS; - num = constants.NGHTTP2_FLAG_ACK; - num = constants.NGHTTP2_FLAG_PADDED; - num = constants.NGHTTP2_FLAG_PRIORITY; - num = constants.DEFAULT_SETTINGS_HEADER_TABLE_SIZE; - num = constants.DEFAULT_SETTINGS_ENABLE_PUSH; - num = constants.DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE; - num = constants.DEFAULT_SETTINGS_MAX_FRAME_SIZE; - num = constants.MAX_MAX_FRAME_SIZE; - num = constants.MIN_MAX_FRAME_SIZE; - num = constants.MAX_INITIAL_WINDOW_SIZE; - num = constants.NGHTTP2_DEFAULT_WEIGHT; - num = constants.NGHTTP2_SETTINGS_HEADER_TABLE_SIZE; - num = constants.NGHTTP2_SETTINGS_ENABLE_PUSH; - num = constants.NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; - num = constants.NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; - num = constants.NGHTTP2_SETTINGS_MAX_FRAME_SIZE; - num = constants.NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE; - num = constants.PADDING_STRATEGY_NONE; - num = constants.PADDING_STRATEGY_MAX; - num = constants.PADDING_STRATEGY_CALLBACK; - num = constants.HTTP_STATUS_CONTINUE; - num = constants.HTTP_STATUS_SWITCHING_PROTOCOLS; - num = constants.HTTP_STATUS_PROCESSING; - num = constants.HTTP_STATUS_OK; - num = constants.HTTP_STATUS_CREATED; - num = constants.HTTP_STATUS_ACCEPTED; - num = constants.HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION; - num = constants.HTTP_STATUS_NO_CONTENT; - num = constants.HTTP_STATUS_RESET_CONTENT; - num = constants.HTTP_STATUS_PARTIAL_CONTENT; - num = constants.HTTP_STATUS_MULTI_STATUS; - num = constants.HTTP_STATUS_ALREADY_REPORTED; - num = constants.HTTP_STATUS_IM_USED; - num = constants.HTTP_STATUS_MULTIPLE_CHOICES; - num = constants.HTTP_STATUS_MOVED_PERMANENTLY; - num = constants.HTTP_STATUS_FOUND; - num = constants.HTTP_STATUS_SEE_OTHER; - num = constants.HTTP_STATUS_NOT_MODIFIED; - num = constants.HTTP_STATUS_USE_PROXY; - num = constants.HTTP_STATUS_TEMPORARY_REDIRECT; - num = constants.HTTP_STATUS_PERMANENT_REDIRECT; - num = constants.HTTP_STATUS_BAD_REQUEST; - num = constants.HTTP_STATUS_UNAUTHORIZED; - num = constants.HTTP_STATUS_PAYMENT_REQUIRED; - num = constants.HTTP_STATUS_FORBIDDEN; - num = constants.HTTP_STATUS_NOT_FOUND; - num = constants.HTTP_STATUS_METHOD_NOT_ALLOWED; - num = constants.HTTP_STATUS_NOT_ACCEPTABLE; - num = constants.HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED; - num = constants.HTTP_STATUS_REQUEST_TIMEOUT; - num = constants.HTTP_STATUS_CONFLICT; - num = constants.HTTP_STATUS_GONE; - num = constants.HTTP_STATUS_LENGTH_REQUIRED; - num = constants.HTTP_STATUS_PRECONDITION_FAILED; - num = constants.HTTP_STATUS_PAYLOAD_TOO_LARGE; - num = constants.HTTP_STATUS_URI_TOO_LONG; - num = constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE; - num = constants.HTTP_STATUS_RANGE_NOT_SATISFIABLE; - num = constants.HTTP_STATUS_EXPECTATION_FAILED; - num = constants.HTTP_STATUS_TEAPOT; - num = constants.HTTP_STATUS_MISDIRECTED_REQUEST; - num = constants.HTTP_STATUS_UNPROCESSABLE_ENTITY; - num = constants.HTTP_STATUS_LOCKED; - num = constants.HTTP_STATUS_FAILED_DEPENDENCY; - num = constants.HTTP_STATUS_UNORDERED_COLLECTION; - num = constants.HTTP_STATUS_UPGRADE_REQUIRED; - num = constants.HTTP_STATUS_PRECONDITION_REQUIRED; - num = constants.HTTP_STATUS_TOO_MANY_REQUESTS; - num = constants.HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE; - num = constants.HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS; - num = constants.HTTP_STATUS_INTERNAL_SERVER_ERROR; - num = constants.HTTP_STATUS_NOT_IMPLEMENTED; - num = constants.HTTP_STATUS_BAD_GATEWAY; - num = constants.HTTP_STATUS_SERVICE_UNAVAILABLE; - num = constants.HTTP_STATUS_GATEWAY_TIMEOUT; - num = constants.HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED; - num = constants.HTTP_STATUS_VARIANT_ALSO_NEGOTIATES; - num = constants.HTTP_STATUS_INSUFFICIENT_STORAGE; - num = constants.HTTP_STATUS_LOOP_DETECTED; - num = constants.HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED; - num = constants.HTTP_STATUS_NOT_EXTENDED; - num = constants.HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED; - str = constants.HTTP2_HEADER_STATUS; - str = constants.HTTP2_HEADER_METHOD; - str = constants.HTTP2_HEADER_AUTHORITY; - str = constants.HTTP2_HEADER_SCHEME; - str = constants.HTTP2_HEADER_PATH; - str = constants.HTTP2_HEADER_ACCEPT_CHARSET; - str = constants.HTTP2_HEADER_ACCEPT_ENCODING; - str = constants.HTTP2_HEADER_ACCEPT_LANGUAGE; - str = constants.HTTP2_HEADER_ACCEPT_RANGES; - str = constants.HTTP2_HEADER_ACCEPT; - str = constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN; - str = constants.HTTP2_HEADER_AGE; - str = constants.HTTP2_HEADER_ALLOW; - str = constants.HTTP2_HEADER_AUTHORIZATION; - str = constants.HTTP2_HEADER_CACHE_CONTROL; - str = constants.HTTP2_HEADER_CONNECTION; - str = constants.HTTP2_HEADER_CONTENT_DISPOSITION; - str = constants.HTTP2_HEADER_CONTENT_ENCODING; - str = constants.HTTP2_HEADER_CONTENT_LANGUAGE; - str = constants.HTTP2_HEADER_CONTENT_LENGTH; - str = constants.HTTP2_HEADER_CONTENT_LOCATION; - str = constants.HTTP2_HEADER_CONTENT_MD5; - str = constants.HTTP2_HEADER_CONTENT_RANGE; - str = constants.HTTP2_HEADER_CONTENT_TYPE; - str = constants.HTTP2_HEADER_COOKIE; - str = constants.HTTP2_HEADER_DATE; - str = constants.HTTP2_HEADER_ETAG; - str = constants.HTTP2_HEADER_EXPECT; - str = constants.HTTP2_HEADER_EXPIRES; - str = constants.HTTP2_HEADER_FROM; - str = constants.HTTP2_HEADER_HOST; - str = constants.HTTP2_HEADER_IF_MATCH; - str = constants.HTTP2_HEADER_IF_MODIFIED_SINCE; - str = constants.HTTP2_HEADER_IF_NONE_MATCH; - str = constants.HTTP2_HEADER_IF_RANGE; - str = constants.HTTP2_HEADER_IF_UNMODIFIED_SINCE; - str = constants.HTTP2_HEADER_LAST_MODIFIED; - str = constants.HTTP2_HEADER_LINK; - str = constants.HTTP2_HEADER_LOCATION; - str = constants.HTTP2_HEADER_MAX_FORWARDS; - str = constants.HTTP2_HEADER_PREFER; - str = constants.HTTP2_HEADER_PROXY_AUTHENTICATE; - str = constants.HTTP2_HEADER_PROXY_AUTHORIZATION; - str = constants.HTTP2_HEADER_RANGE; - str = constants.HTTP2_HEADER_REFERER; - str = constants.HTTP2_HEADER_REFRESH; - str = constants.HTTP2_HEADER_RETRY_AFTER; - str = constants.HTTP2_HEADER_SERVER; - str = constants.HTTP2_HEADER_SET_COOKIE; - str = constants.HTTP2_HEADER_STRICT_TRANSPORT_SECURITY; - str = constants.HTTP2_HEADER_TRANSFER_ENCODING; - str = constants.HTTP2_HEADER_TE; - str = constants.HTTP2_HEADER_UPGRADE; - str = constants.HTTP2_HEADER_USER_AGENT; - str = constants.HTTP2_HEADER_VARY; - str = constants.HTTP2_HEADER_VIA; - str = constants.HTTP2_HEADER_WWW_AUTHENTICATE; - str = constants.HTTP2_HEADER_HTTP2_SETTINGS; - str = constants.HTTP2_HEADER_KEEP_ALIVE; - str = constants.HTTP2_HEADER_PROXY_CONNECTION; - str = constants.HTTP2_METHOD_ACL; - str = constants.HTTP2_METHOD_BASELINE_CONTROL; - str = constants.HTTP2_METHOD_BIND; - str = constants.HTTP2_METHOD_CHECKIN; - str = constants.HTTP2_METHOD_CHECKOUT; - str = constants.HTTP2_METHOD_CONNECT; - str = constants.HTTP2_METHOD_COPY; - str = constants.HTTP2_METHOD_DELETE; - str = constants.HTTP2_METHOD_GET; - str = constants.HTTP2_METHOD_HEAD; - str = constants.HTTP2_METHOD_LABEL; - str = constants.HTTP2_METHOD_LINK; - str = constants.HTTP2_METHOD_LOCK; - str = constants.HTTP2_METHOD_MERGE; - str = constants.HTTP2_METHOD_MKACTIVITY; - str = constants.HTTP2_METHOD_MKCALENDAR; - str = constants.HTTP2_METHOD_MKCOL; - str = constants.HTTP2_METHOD_MKREDIRECTREF; - str = constants.HTTP2_METHOD_MKWORKSPACE; - str = constants.HTTP2_METHOD_MOVE; - str = constants.HTTP2_METHOD_OPTIONS; - str = constants.HTTP2_METHOD_ORDERPATCH; - str = constants.HTTP2_METHOD_PATCH; - str = constants.HTTP2_METHOD_POST; - str = constants.HTTP2_METHOD_PRI; - str = constants.HTTP2_METHOD_PROPFIND; - str = constants.HTTP2_METHOD_PROPPATCH; - str = constants.HTTP2_METHOD_PUT; - str = constants.HTTP2_METHOD_REBIND; - str = constants.HTTP2_METHOD_REPORT; - str = constants.HTTP2_METHOD_SEARCH; - str = constants.HTTP2_METHOD_TRACE; - str = constants.HTTP2_METHOD_UNBIND; - str = constants.HTTP2_METHOD_UNCHECKOUT; - str = constants.HTTP2_METHOD_UNLINK; - str = constants.HTTP2_METHOD_UNLOCK; - str = constants.HTTP2_METHOD_UPDATE; - str = constants.HTTP2_METHOD_UPDATEREDIRECTREF; - str = constants.HTTP2_METHOD_VERSION_CONTROL; - } -} - -/////////////////////////////////////////////////////////// -/// Inspector Tests /// -/////////////////////////////////////////////////////////// - -namespace inspector_tests { - { - inspector.open(); - inspector.open(0); - inspector.open(0, 'localhost'); - inspector.open(0, 'localhost', true); - inspector.close(); - const inspectorUrl: string | undefined = inspector.url(); - - const session = new inspector.Session(); - session.connect(); - session.disconnect(); - - // Unknown post method - session.post('A.b', { key: 'value' }, (err, params) => {}); - // TODO: parameters are implicitly 'any' and need type annotation - session.post('A.b', (err: Error | null, params?: {}) => {}); - session.post('A.b'); - // Known post method - const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; - session.post('Runtime.evaluate', parameter, - (err: Error, params: inspector.Runtime.EvaluateReturnType) => {}); - session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { - const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails; - const resultClassName: string = params.result.className; - }); - session.post('Runtime.evaluate'); - - // General event - session.on('inspectorNotification', message => { - message; // $ExpectType InspectorNotification<{}> - }); - // Known events - session.on('Debugger.paused', (message: inspector.InspectorNotification) => { - const method: string = message.method; - const pauseReason: string = message.params.reason; - }); - session.on('Debugger.resumed', () => {}); - } -} - -//////////////////////////////////////////////////// -/// module tests : http://nodejs.org/api/modules.html -//////////////////////////////////////////////////// - -namespace module_tests { - require.extensions[".ts"] = () => ""; - - Module.runMain(); - const s: string = Module.wrap("some code"); - - const m1: Module = new Module("moduleId"); - const m2: Module = new Module.Module("moduleId"); - const b: string[] = Module.builtinModules; - let paths: string[] = module.paths; - paths = m1.paths; -} - -//////////////////////////////////////////////////// -/// Node.js ESNEXT Support -//////////////////////////////////////////////////// - -namespace esnext_string_tests { - const s: string = 'foo'; - const s1: string = s.trimLeft(); - const s2: string = s.trimRight(); -} diff --git a/types/node/v9/ts3.1/tsconfig.json b/types/node/v9/ts3.1/tsconfig.json deleted file mode 100644 index 82d7fbcc7f..0000000000 --- a/types/node/v9/ts3.1/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "files": [ - "index.d.ts", - "node-tests.ts" - ], - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": true, - "baseUrl": "../../../", - "typeRoots": [ - "../../../" - ], - "paths": { - "node": [ - "node/v9" - ] - }, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - } -} diff --git a/types/node/v9/ts3.1/tslint.json b/types/node/v9/ts3.1/tslint.json deleted file mode 100644 index 8f9cf3a592..0000000000 --- a/types/node/v9/ts3.1/tslint.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "dt-header": false, - "max-line-length": false, - "no-empty-interface": false, - "no-internal-module": false, - "no-redundant-jsdoc": false, - "no-single-declare-module": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-var-keyword": false, - "prefer-method-signature": false, - "strict-export-declare-modifiers": false, - "unified-signatures": false - } -}