text
stringlengths
2
4k
er(event: "end", listener: () => void): this; addListener(event: "readable", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; emit(event: "aborted", hadError: boolean, code: number): boolean; emit(event: "close"): boolean; emit(event: "data", chunk: Buffer | string): boolean; emit(event: "end"): boolean; emit(event: "readable"): boolean; emit(event: "error", err: Error): boolean; emit(event: string | symbol, ...args: any[]): boolean; on(event: "aborted", listener: (hadError: boolean, code: number) => 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: "readable", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; once(event: "aborted", listener: (hadError: boolean, code: number) => 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: "readable", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: "aborted", listener: (hadError: boolean, code: number) => 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: "readable", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => 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: "readable", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } /** * This object is created internally by an HTTP server, not by the user. It is * passed as the second parameter to the `'request'` event. * @since v8.4.0 */ export class Http2ServerResponse extends stream.Writable { constructor(stream: ServerHttp2Stream); /** * See `response.socket`. * @since v8.4.0 * @deprecated Since v13.0.0 - Use `socket`. */ readonly connection: net.Socket | tls.TLSSocket; /** * Boolean value that indicates whether the response has completed. Starts * as `false`. After `response.end()` executes, the value will be `true`. * @since v8.4.0 * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. */ readonly finished: boolean; /** * True if headers were sent, false otherwise (read-only). * @since v8.4.0 */ readonly headersSent: boolean; /** * A reference to the original HTTP2 `request` object. * @since v15.7.0 */ readonly req: Http2ServerRequest; /** * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocke
t`) but * applies getters, setters, and methods based on HTTP/2 logic. * * `destroyed`, `readable`, and `writable` properties will be retrieved from and * set on `response.stream`. * * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`. * * `setTimeout` method will be called on `response.stream.session`. * * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for * more information. * * All other interactions will be routed directly to the socket. * * ```js * const http2 = require('node:http2'); * const server = http2.createServer((req, res) => { * const ip = req.socket.remoteAddress; * const port = req.socket.remotePort; * res.end(`Your IP address is ${ip} and your source port is ${port}.`); * }).listen(3000); * ``` * @since v8.4.0 */ readonly socket: net.Socket | tls.TLSSocket; /** * The `Http2Stream` object backing the response. * @since v8.4.0 */ readonly stream: ServerHttp2Stream; /** * When true, the Date header will be automatically generated and sent in * the response if it is not already present in the headers. Defaults to true. * * This should only be disabled for testing; HTTP requires the Date header * in responses. * @since v8.4.0 */ sendDate: boolean; /** * When using implicit headers (not calling `response.writeHead()` explicitly), * this property controls the status code that will be sent to the client when * the headers get flushed. * * ```js * response.statusCode = 404; * ``` * * After response header was sent to the client, this property indicates the * status code which was sent out. * @since v8.4.0 */ statusCode: number; /** * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns * an empty string. * @since v8.4.0 */ statusMessage: ""; /** * This method adds HTTP trailing headers (a header but at the end of the * message) to the response. * * Attempting to set a header field name or value that contains invalid characters * will result in a `TypeError` being thrown. * @since v8.4.0 */ addTrailers(trailers: OutgoingHttpHeaders): void; /** * This method signals to the server that all of the response headers and body * have been sent; that server should consider this message complete. * The method, `response.end()`, MUST be called on each response. * * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. * * If `callback` is specified, it will be called when the response stream * is finished. * @since v8.4.0 */ end(callback?: () => void): this; end(data: string | Uint8Array, callback?: () => void): this; end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; /** * Reads out a header that has already been queued but not sent to the client. * The name is case-insensitive. * * ```js * const contentType = response.getHeader('content-type'); * ``` * @since v8.4.0 */ getHeader(name: string): string; /** * Returns an array containing the unique names of the current outgoing headers. * All header names are lowercase. * * ```js * re
sponse.setHeader('Foo', 'bar'); * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); * * const headerNames = response.getHeaderNames(); * // headerNames === ['foo', 'set-cookie'] * ``` * @since v8.4.0 */ getHeaderNames(): string[]; /** * Returns a shallow copy of the current outgoing headers. Since a shallow copy * is used, array values may be mutated without additional calls to various * header-related http module methods. The keys of the returned object are the * header names and the values are the respective header values. All header names * are lowercase. * * The object returned by the `response.getHeaders()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, * `obj.hasOwnProperty()`, and others * are not defined and _will not work_. * * ```js * response.setHeader('Foo', 'bar'); * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); * * const headers = response.getHeaders(); * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } * ``` * @since v8.4.0 */ getHeaders(): OutgoingHttpHeaders; /** * Returns `true` if the header identified by `name` is currently set in the * outgoing headers. The header name matching is case-insensitive. * * ```js * const hasContentType = response.hasHeader('content-type'); * ``` * @since v8.4.0 */ hasHeader(name: string): boolean; /** * Removes a header that has been queued for implicit sending. * * ```js * response.removeHeader('Content-Encoding'); * ``` * @since v8.4.0 */ removeHeader(name: string): void; /** * Sets a single header value for implicit headers. If this header already exists * in the to-be-sent headers, its value will be replaced. Use an array of strings * here to send multiple headers with the same name. * * ```js * response.setHeader('Content-Type', 'text/html; charset=utf-8'); * ``` * * or * * ```js * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); * ``` * * Attempting to set a header field name or value that contains invalid characters * will result in a `TypeError` being thrown. * * When headers have been set with `response.setHeader()`, they will be merged * with any headers passed to `response.writeHead()`, with the headers passed * to `response.writeHead()` given precedence. * * ```js * // Returns content-type = text/plain * const server = http2.createServer((req, res) => { * res.setHeader('Content-Type', 'text/html; charset=utf-8'); * res.setHeader('X-Foo', 'bar'); * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); * res.end('ok'); * }); * ``` * @since v8.4.0 */ setHeader(name: string, value: number | string | readonly string[]): void; /** * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is * provided, then it is added as a listener on the `'timeout'` event on * the response object. * * If no `'timeout'` listener is added to the request, the response, or * the server, then `Http2Stream` s are destroyed when they time out. If a * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. * @since v8.4.0 */ setTi
meout(msecs: number, callback?: () => void): void; /** * If this method is called and `response.writeHead()` has not been called, * it will switch to implicit header mode and flush the implicit headers. * * This sends a chunk of the response body. This method may * be called multiple times to provide successive parts of the body. * * In the `node:http` module, the response body is omitted when the * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. * * `chunk` can be a string or a buffer. If `chunk` is a string, * the second parameter specifies how to encode it into a byte stream. * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk * of data is flushed. * * This is the raw HTTP body and has nothing to do with higher-level multi-part * body encodings that may be used. * * The first time `response.write()` is called, it will send the buffered * header information and the first chunk of the body to the client. The second * time `response.write()` is called, Node.js assumes data will be streamed, * and sends the new data separately. That is, the response is buffered up to the * first chunk of the body. * * Returns `true` if the entire data was flushed successfully to the kernel * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. * @since v8.4.0 */ write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; /** * Sends a status `100 Continue` to the client, indicating that the request body * should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`. * @since v8.4.0 */ writeContinue(): void; /** * Sends a status `103 Early Hints` to the client with a Link header, * indicating that the user agent can preload/preconnect the linked resources. * The `hints` is an object containing the values of headers to be sent with * early hints message. * * **Example** * * ```js * const earlyHintsLink = '</styles.css>; rel=preload; as=style'; * response.writeEarlyHints({ * 'link': earlyHintsLink, * }); * * const earlyHintsLinks = [ * '</styles.css>; rel=preload; as=style', * '</scripts.js>; rel=preload; as=script', * ]; * response.writeEarlyHints({ * 'link': earlyHintsLinks, * }); * ``` * @since v18.11.0 */ writeEarlyHints(hints: Record<string, string | string[]>): void; /** * Sends a response header to the request. The status code is a 3-digit HTTP * status code, like `404`. The last argument, `headers`, are the response headers. * * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. * * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be * passed as the second argument. However, because the `statusMessage` has no * meaning within HTTP/2, the argument will have no effect and a process warning * will be emitted. * * ```js * const body = 'hello world'; * response.writeHead(200, { * 'Content-Length': Buffer.byteLength(body), * 'Content-Type': 'text/plain; charset=utf-8', * }); * ``` * * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be
used to determine the number of bytes in a * given encoding. On outbound messages, Node.js does not check if Content-Length * and the length of the body being transmitted are equal or not. However, when * receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size. * * This method may be called at most one time on a message before `response.end()` is called. * * If `response.write()` or `response.end()` are called before calling * this, the implicit/mutable headers will be calculated and call this function. * * When headers have been set with `response.setHeader()`, they will be merged * with any headers passed to `response.writeHead()`, with the headers passed * to `response.writeHead()` given precedence. * * ```js * // Returns content-type = text/plain * const server = http2.createServer((req, res) => { * res.setHeader('Content-Type', 'text/html; charset=utf-8'); * res.setHeader('X-Foo', 'bar'); * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); * res.end('ok'); * }); * ``` * * Attempting to set a header field name or value that contains invalid characters * will result in a `TypeError` being thrown. * @since v8.4.0 */ writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; /** * Call `http2stream.pushStream()` with the given headers, and wrap the * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback * parameter if successful. When `Http2ServerRequest` is closed, the callback is * called with an error `ERR_HTTP2_INVALID_STREAM`. * @since v8.4.0 * @param headers An object describing the headers * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method */ createPushResponse( headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void, ): void; addListener(event: "close", listener: () => void): this; addListener(event: "drain", listener: () => void): this; addListener(event: "error", listener: (error: Error) => void): this; addListener(event: "finish", listener: () => void): this; addListener(event: "pipe", listener: (src: stream.Readable) => void): this; addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; emit(event: "close"): boolean; emit(event: "drain"): boolean; emit(event: "error", error: Error): boolean; emit(event: "finish"): boolean; emit(event: "pipe", src: stream.Readable): boolean; emit(event: "unpipe", src: stream.Readable): boolean; emit(event: string | symbol, ...args: any[]): boolean; on(event: "close", listener: () => void): this; on(event: "drain", listener: () => void): this; on(event: "error", listener: (error: Error) => void): this; on(event: "finish", listener: () => void): this; on(event: "pipe", listener: (src: stream.Readable) => 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: (error: Error) => void): this; once(event: "finish", listener: () => void): this; once(event: "pipe", listener: (src: stream.Readable) => 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: (error: Error) => void): this; prependListener(event: "finish", listener: () => void): this; prependListener(event: "pipe", listener: (src: stream.Readable) => 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: (error: Error) => void): this; prependOnceListener(event: "finish", listener: () => void): this; prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } export namespace constants { const NGHTTP2_SESSION_SERVER: number; const NGHTTP2_SESSION_CLIENT: number; const NGHTTP2_STREAM_STATE_IDLE: number; const NGHTTP2_STREAM_STATE_OPEN: number; const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; const NGHTTP2_STREAM_STATE_CLOSED: number; const NGHTTP2_NO_ERROR: number; const NGHTTP2_PROTOCOL_ERROR: number; const NGHTTP2_INTERNAL_ERROR: number; const NGHTTP2_FLOW_CONTROL_ERROR: number; const NGHTTP2_SETTINGS_TIMEOUT: number; const NGHTTP2_STREAM_CLOSED: number; const NGHTTP2_FRAME_SIZE_ERROR: number; const NGHTTP2_REFUSED_STREAM: number; const NGHTTP2_CANCEL: number; const NGHTTP2_COMPRESSION_ERROR: number; const NGHTTP2_CONNECT_ERROR: number; const NGHTTP2_ENHANCE_YOUR_CALM: number; const NGHTTP2_INADEQUATE_SECURITY: number; const NGHTTP2_HTTP_1_1_REQUIRED: number; const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; const NGHTTP2_FLAG_NONE: number; const NGHTTP2_FLAG_END_STREAM: number; const NGHTTP2_FLAG_END_HEADERS: number; const NGHTTP2_FLAG_ACK: number; const NGHTTP2_FLAG_PADDED: number; const NGHTTP2_FLAG_PRIORITY: number; const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; const DEFAULT_SETTINGS_ENABLE_PUSH: number; const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; const MAX_MAX_FRAME_SIZE: number; const MIN_MAX_FRAME_SIZE: number; const MAX_INITIAL_WINDOW_SIZE: number; const NGHTTP2_DEFAULT_WEIGHT: number; const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; const NGHTTP2_SETTINGS_ENABLE_PUSH: number; const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; const PADDING_STRATEGY_NONE: number; const PADDING_STRATEGY_MAX: number; const PADDING_STRATEGY_CALLBACK: number; const HTTP2_HEADER_STATUS: string; const HTTP2_HEADER_METHOD: string; const HTTP2_HEADER_A
UTHORITY: string; const HTTP2_HEADER_SCHEME: string; const HTTP2_HEADER_PATH: string; const HTTP2_HEADER_ACCEPT_CHARSET: string; const HTTP2_HEADER_ACCEPT_ENCODING: string; const HTTP2_HEADER_ACCEPT_LANGUAGE: string; const HTTP2_HEADER_ACCEPT_RANGES: string; const HTTP2_HEADER_ACCEPT: string; const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; const HTTP2_HEADER_AGE: string; const HTTP2_HEADER_ALLOW: string; const HTTP2_HEADER_AUTHORIZATION: string; const HTTP2_HEADER_CACHE_CONTROL: string; const HTTP2_HEADER_CONNECTION: string; const HTTP2_HEADER_CONTENT_DISPOSITION: string; const HTTP2_HEADER_CONTENT_ENCODING: string; const HTTP2_HEADER_CONTENT_LANGUAGE: string; const HTTP2_HEADER_CONTENT_LENGTH: string; const HTTP2_HEADER_CONTENT_LOCATION: string; const HTTP2_HEADER_CONTENT_MD5: string; const HTTP2_HEADER_CONTENT_RANGE: string; const HTTP2_HEADER_CONTENT_TYPE: string; const HTTP2_HEADER_COOKIE: string; const HTTP2_HEADER_DATE: string; const HTTP2_HEADER_ETAG: string; const HTTP2_HEADER_EXPECT: string; const HTTP2_HEADER_EXPIRES: string; const HTTP2_HEADER_FROM: string; const HTTP2_HEADER_HOST: string; const HTTP2_HEADER_IF_MATCH: string; const HTTP2_HEADER_IF_MODIFIED_SINCE: string; const HTTP2_HEADER_IF_NONE_MATCH: string; const HTTP2_HEADER_IF_RANGE: string; const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; const HTTP2_HEADER_LAST_MODIFIED: string; const HTTP2_HEADER_LINK: string; const HTTP2_HEADER_LOCATION: string; const HTTP2_HEADER_MAX_FORWARDS: string; const HTTP2_HEADER_PREFER: string; const HTTP2_HEADER_PROXY_AUTHENTICATE: string; const HTTP2_HEADER_PROXY_AUTHORIZATION: string; const HTTP2_HEADER_RANGE: string; const HTTP2_HEADER_REFERER: string; const HTTP2_HEADER_REFRESH: string; const HTTP2_HEADER_RETRY_AFTER: string; const HTTP2_HEADER_SERVER: string; const HTTP2_HEADER_SET_COOKIE: string; const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; const HTTP2_HEADER_TRANSFER_ENCODING: string; const HTTP2_HEADER_TE: string; const HTTP2_HEADER_UPGRADE: string; const HTTP2_HEADER_USER_AGENT: string; const HTTP2_HEADER_VARY: string; const HTTP2_HEADER_VIA: string; const HTTP2_HEADER_WWW_AUTHENTICATE: string; const HTTP2_HEADER_HTTP2_SETTINGS: string; const HTTP2_HEADER_KEEP_ALIVE: string; const HTTP2_HEADER_PROXY_CONNECTION: string; const HTTP2_METHOD_ACL: string; const HTTP2_METHOD_BASELINE_CONTROL: string; const HTTP2_METHOD_BIND: string; const HTTP2_METHOD_CHECKIN: string; const HTTP2_METHOD_CHECKOUT: string; const HTTP2_METHOD_CONNECT: string; const HTTP2_METHOD_COPY: string; const HTTP2_METHOD_DELETE: string; const HTTP2_METHOD_GET: string; const HTTP2_METHOD_HEAD: string; const HTTP2_METHOD_LABEL: string; const HTTP2_METHOD_LINK: string; const HTTP2_METHOD_LOCK: string; const HTTP2_METHOD_MERGE: string; const HTTP2_METHOD_MKACTIVITY: string; const HTTP2_METHOD_MKCALENDAR: string; const HTTP2_METHOD_MKCOL: string; const HTTP2_METHOD_MKREDIRECTREF: string; const HTTP2_METHOD_MKWORKSPACE: string; const HTTP2_METHOD_MOVE: string; const HTTP2_METHOD_OPTIONS: string; const HTTP2_METHOD_ORDERPATCH: string; const HTTP2_METHOD_PATCH: string; const HTTP2_METHOD_POST: string; const HTTP2_METHOD_PRI: string; const HTTP2_METHOD_PROPFIND: string; const HTTP2_METHOD_PROPPATCH: string; const HTTP2_METHOD_PUT: string; const HTTP2_METHOD_REBIND: string;
const HTTP2_METHOD_REPORT: string; const HTTP2_METHOD_SEARCH: string; const HTTP2_METHOD_TRACE: string; const HTTP2_METHOD_UNBIND: string; const HTTP2_METHOD_UNCHECKOUT: string; const HTTP2_METHOD_UNLINK: string; const HTTP2_METHOD_UNLOCK: string; const HTTP2_METHOD_UPDATE: string; const HTTP2_METHOD_UPDATEREDIRECTREF: string; const HTTP2_METHOD_VERSION_CONTROL: string; const HTTP_STATUS_CONTINUE: number; const HTTP_STATUS_SWITCHING_PROTOCOLS: number; const HTTP_STATUS_PROCESSING: number; const HTTP_STATUS_OK: number; const HTTP_STATUS_CREATED: number; const HTTP_STATUS_ACCEPTED: number; const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; const HTTP_STATUS_NO_CONTENT: number; const HTTP_STATUS_RESET_CONTENT: number; const HTTP_STATUS_PARTIAL_CONTENT: number; const HTTP_STATUS_MULTI_STATUS: number; const HTTP_STATUS_ALREADY_REPORTED: number; const HTTP_STATUS_IM_USED: number; const HTTP_STATUS_MULTIPLE_CHOICES: number; const HTTP_STATUS_MOVED_PERMANENTLY: number; const HTTP_STATUS_FOUND: number; const HTTP_STATUS_SEE_OTHER: number; const HTTP_STATUS_NOT_MODIFIED: number; const HTTP_STATUS_USE_PROXY: number; const HTTP_STATUS_TEMPORARY_REDIRECT: number; const HTTP_STATUS_PERMANENT_REDIRECT: number; const HTTP_STATUS_BAD_REQUEST: number; const HTTP_STATUS_UNAUTHORIZED: number; const HTTP_STATUS_PAYMENT_REQUIRED: number; const HTTP_STATUS_FORBIDDEN: number; const HTTP_STATUS_NOT_FOUND: number; const HTTP_STATUS_METHOD_NOT_ALLOWED: number; const HTTP_STATUS_NOT_ACCEPTABLE: number; const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; const HTTP_STATUS_REQUEST_TIMEOUT: number; const HTTP_STATUS_CONFLICT: number; const HTTP_STATUS_GONE: number; const HTTP_STATUS_LENGTH_REQUIRED: number; const HTTP_STATUS_PRECONDITION_FAILED: number; const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; const HTTP_STATUS_URI_TOO_LONG: number; const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; const HTTP_STATUS_EXPECTATION_FAILED: number; const HTTP_STATUS_TEAPOT: number; const HTTP_STATUS_MISDIRECTED_REQUEST: number; const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; const HTTP_STATUS_LOCKED: number; const HTTP_STATUS_FAILED_DEPENDENCY: number; const HTTP_STATUS_UNORDERED_COLLECTION: number; const HTTP_STATUS_UPGRADE_REQUIRED: number; const HTTP_STATUS_PRECONDITION_REQUIRED: number; const HTTP_STATUS_TOO_MANY_REQUESTS: number; const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; const HTTP_STATUS_NOT_IMPLEMENTED: number; const HTTP_STATUS_BAD_GATEWAY: number; const HTTP_STATUS_SERVICE_UNAVAILABLE: number; const HTTP_STATUS_GATEWAY_TIMEOUT: number; const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; const HTTP_STATUS_INSUFFICIENT_STORAGE: number; const HTTP_STATUS_LOOP_DETECTED: number; const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; const HTTP_STATUS_NOT_EXTENDED: number; const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; } /** * This symbol can be set as a property on the HTTP/2 headers object with * an array value in order to provide a list of headers considered sensitive. */ export const sensitiveHeaders: symbol; /** * Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object i
nstance every time it is called * so instances returned may be safely modified for use. * @since v8.4.0 */ export function getDefaultSettings(): Settings; /** * Returns a `Buffer` instance containing serialized representation of the given * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended * for use with the `HTTP2-Settings` header field. * * ```js * const http2 = require('node:http2'); * * const packed = http2.getPackedSettings({ enablePush: false }); * * console.log(packed.toString('base64')); * // Prints: AAIAAAAA * ``` * @since v8.4.0 */ export function getPackedSettings(settings: Settings): Buffer; /** * Returns a `HTTP/2 Settings Object` containing the deserialized settings from * the given `Buffer` as generated by `http2.getPackedSettings()`. * @since v8.4.0 * @param buf The packed settings. */ export function getUnpackedSettings(buf: Uint8Array): Settings; /** * Returns a `net.Server` instance that creates and manages `Http2Session`instances. * * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when * communicating * with browser clients. * * ```js * const http2 = require('node:http2'); * * // Create an unencrypted HTTP/2 server. * // Since there are no browsers known that support * // unencrypted HTTP/2, the use of `http2.createSecureServer()` * // is necessary when communicating with browser clients. * const server = http2.createServer(); * * server.on('stream', (stream, headers) => { * stream.respond({ * 'content-type': 'text/html; charset=utf-8', * ':status': 200, * }); * stream.end('<h1>Hello World</h1>'); * }); * * server.listen(8000); * ``` * @since v8.4.0 * @param onRequestHandler See `Compatibility API` */ export function createServer( onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, ): Http2Server; export function createServer( options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, ): Http2Server; /** * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. * * ```js * const http2 = require('node:http2'); * const fs = require('node:fs'); * * const options = { * key: fs.readFileSync('server-key.pem'), * cert: fs.readFileSync('server-cert.pem'), * }; * * // Create a secure HTTP/2 server * const server = http2.createSecureServer(options); * * server.on('stream', (stream, headers) => { * stream.respond({ * 'content-type': 'text/html; charset=utf-8', * ':status': 200, * }); * stream.end('<h1>Hello World</h1>'); * }); * * server.listen(8443); * ``` * @since v8.4.0 * @param onRequestHandler See `Compatibility API` */ export function createSecureServer( onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, ): Http2SecureServer; export function createSecureServer( options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, ): Http2SecureServer; /** * Returns a `ClientHttp2Session` instance. * * ```js * const http2 = require('node:http2'); * const client = http2.connect('https://localhost:1234'); * * // Use the client * * client.close(); * ``` * @since v8.4.0 * @param authority The remote HTTP/2 server to connect to. This must be in th
e form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. */ export function connect( authority: string | url.URL, listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, ): ClientHttp2Session; export function connect( authority: string | url.URL, options?: ClientSessionOptions | SecureClientSessionOptions, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, ): ClientHttp2Session; } declare module "node:http2" { export * from "http2"; }
/** * A stream is an abstract interface for working with streaming data in Node.js. * The `node:stream` module provides an API for implementing the stream interface. * * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. * * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. * * To access the `node:stream` module: * * ```js * const stream = require('node:stream'); * ``` * * The `node:stream` module is useful for creating new types of stream instances. * It is usually not necessary to use the `node:stream` module to consume streams. * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/stream.js) */ declare module "stream" { import { Abortable, EventEmitter } from "node:events"; import { Blob as NodeBlob } from "node:buffer"; import * as streamPromises from "node:stream/promises"; import * as streamConsumers from "node:stream/consumers"; import * as streamWeb from "node:stream/web"; type ComposeFnParam = (source: any) => void; class internal extends EventEmitter { pipe<T extends NodeJS.WritableStream>( destination: T, options?: { end?: boolean | undefined; }, ): T; compose<T extends NodeJS.ReadableStream>( stream: T | ComposeFnParam | Iterable<T> | AsyncIterable<T>, options?: { signal: AbortSignal }, ): T; } import Stream = internal.Stream; import Readable = internal.Readable; import ReadableOptions = internal.ReadableOptions; interface ArrayOptions { /** the maximum concurrent invocations of `fn` to call on the stream at once. **Default: 1**. */ concurrency?: number; /** allows destroying the stream if the signal is aborted. */ signal?: AbortSignal; } class ReadableBase extends Stream implements NodeJS.ReadableStream { /** * A utility method for creating Readable Streams out of iterators. */ static from(iterable: Iterable<any> | AsyncIterable<any>, options?: ReadableOptions): Readable; /** * Returns whether the stream has been read from or cancelled. * @since v16.8.0 */ static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; /** * Returns whether the stream was destroyed or errored before emitting `'end'`. * @since v16.8.0 * @experimental */ readonly readableAborted: boolean; /** * Is `true` if it is safe to call `readable.read()`, which means * the stream has not been destroyed or emitted `'error'` or `'end'`. * @since v11.4.0 */ readable: boolean; /** * Returns whether `'data'` has been emitted. * @since v16.7.0, v14.18.0 * @experimental */ readonly readableDidRead: boolean; /** * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. * @since v12.7.0 */ readonly readableEncoding: BufferEncoding | null; /** * Becomes `true` when `'end'` event is emitted. * @since v12.9.0 */ readonly readableEnded: boolean; /** * This property reflects the current state of a `Readable` stream as described * in the `Three states` section. * @since v9.4.0 */ readonly readableFlowing: boolean | null; /** * Returns the value of `highWaterMark` passed when creating this `Readable`. * @since v9.3.0 */ readonly readableHighWaterMark: number; /** * This property contains the number of bytes (or objects) in the queue * ready to be read. The value provides introspection da
ta regarding * the status of the `highWaterMark`. * @since v9.4.0 */ readonly readableLength: number; /** * Getter for the property `objectMode` of a given `Readable` stream. * @since v12.3.0 */ readonly readableObjectMode: boolean; /** * Is `true` after `readable.destroy()` has been called. * @since v8.0.0 */ destroyed: boolean; /** * Is `true` after `'close'` has been emitted. * @since v18.0.0 */ readonly closed: boolean; /** * Returns error if the stream has been destroyed with an error. * @since v18.0.0 */ readonly errored: Error | null; constructor(opts?: ReadableOptions); _construct?(callback: (error?: Error | null) => void): void; _read(size: number): void; /** * The `readable.read()` method reads data out of the internal buffer and * returns it. If no data is available to be read, `null` is returned. By default, * the data is returned as a `Buffer` object unless an encoding has been * specified using the `readable.setEncoding()` method or the stream is operating * in object mode. * * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which * case all of the data remaining in the internal * buffer will be returned. * * If the `size` argument is not specified, all of the data contained in the * internal buffer will be returned. * * The `size` argument must be less than or equal to 1 GiB. * * The `readable.read()` method should only be called on `Readable` streams * operating in paused mode. In flowing mode, `readable.read()` is called * automatically until the internal buffer is fully drained. * * ```js * const readable = getReadableStreamSomehow(); * * // 'readable' may be triggered multiple times as data is buffered in * readable.on('readable', () => { * let chunk; * console.log('Stream is readable (new data received in buffer)'); * // Use a loop to make sure we read all currently available data * while (null !== (chunk = readable.read())) { * console.log(`Read ${chunk.length} bytes of data...`); * } * }); * * // 'end' will be triggered once when there is no more data available * readable.on('end', () => { * console.log('Reached end of stream.'); * }); * ``` * * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks * are not concatenated. A `while` loop is necessary to consume all data * currently in the buffer. When reading a large file `.read()` may return `null`, * having consumed all buffered content so far, but there is still more data to * come not yet buffered. In this case a new `'readable'` event will be emitted * when there is more data in the buffer. Finally the `'end'` event will be * emitted when there is no more data to come. * * Therefore to read a file's whole contents from a `readable`, it is necessary * to collect chunks across multiple `'readable'` events: * * ```js * const chunks = []; * * readable.on('readable', () => { * let chunk; * while (null !== (chunk = readable.read())) { * chunks.push(chunk); * } * }); * * readable.on('end', () => { * const content = chunks.join(''); * }); * ``` * * A `Readable` stream in ob
ject mode will always return a single item from * a call to `readable.read(size)`, regardless of the value of the`size` argument. * * If the `readable.read()` method returns a chunk of data, a `'data'` event will * also be emitted. * * Calling {@link read} after the `'end'` event has * been emitted will return `null`. No runtime error will be raised. * @since v0.9.4 * @param size Optional argument to specify how much data to read. */ read(size?: number): any; /** * The `readable.setEncoding()` method sets the character encoding for * data read from the `Readable` stream. * * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal * string format. * * The `Readable` stream will properly handle multi-byte characters delivered * through the stream that would otherwise become improperly decoded if simply * pulled from the stream as `Buffer` objects. * * ```js * const readable = getReadableStreamSomehow(); * readable.setEncoding('utf8'); * readable.on('data', (chunk) => { * assert.equal(typeof chunk, 'string'); * console.log('Got %d characters of string data:', chunk.length); * }); * ``` * @since v0.9.4 * @param encoding The encoding to use. */ setEncoding(encoding: BufferEncoding): this; /** * The `readable.pause()` method will cause a stream in flowing mode to stop * emitting `'data'` events, switching out of flowing mode. Any data that * becomes available will remain in the internal buffer. * * ```js * const readable = getReadableStreamSomehow(); * readable.on('data', (chunk) => { * console.log(`Received ${chunk.length} bytes of data.`); * readable.pause(); * console.log('There will be no additional data for 1 second.'); * setTimeout(() => { * console.log('Now data will start flowing again.'); * readable.resume(); * }, 1000); * }); * ``` * * The `readable.pause()` method has no effect if there is a `'readable'`event listener. * @since v0.9.4 */ pause(): this; /** * The `readable.resume()` method causes an explicitly paused `Readable` stream to * resume emitting `'data'` events, switching the stream into flowing mode. * * The `readable.resume()` method can be used to fully consume the data from a * stream without actually processing any of that data: * * ```js * getReadableStreamSomehow() * .resume() * .on('end', () => { * console.log('Reached the end, but did not read anything.'); * }); * ``` * * The `readable.resume()` method has no effect if there is a `'readable'`event listener. * @since v0.9.4 */ resume(): this; /** * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most * typical cases, there will be no reason to * use this method directly. * * ```js * const readable = new stream.Readable(); * * readable.isPaused(); // === false *
readable.pause(); * readable.isPaused(); // === true * readable.resume(); * readable.isPaused(); // === false * ``` * @since v0.11.14 */ isPaused(): boolean; /** * The `readable.unpipe()` method detaches a `Writable` stream previously attached * using the {@link pipe} method. * * If the `destination` is not specified, then _all_ pipes are detached. * * If the `destination` is specified, but no pipe is set up for it, then * the method does nothing. * * ```js * const fs = require('node:fs'); * const readable = getReadableStreamSomehow(); * const writable = fs.createWriteStream('file.txt'); * // All the data from readable goes into 'file.txt', * // but only for the first second. * readable.pipe(writable); * setTimeout(() => { * console.log('Stop writing to file.txt.'); * readable.unpipe(writable); * console.log('Manually close the file stream.'); * writable.end(); * }, 1000); * ``` * @since v0.9.4 * @param destination Optional specific stream to unpipe */ unpipe(destination?: NodeJS.WritableStream): this; /** * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the * same as `readable.push(null)`, after which no more data can be written. The EOF * signal is put at the end of the buffer and any buffered data will still be * flushed. * * The `readable.unshift()` method pushes a chunk of data back into the internal * buffer. This is useful in certain situations where a stream is being consumed by * code that needs to "un-consume" some amount of data that it has optimistically * pulled out of the source, so that the data can be passed on to some other party. * * The `stream.unshift(chunk)` method cannot be called after the `'end'` event * has been emitted or a runtime error will be thrown. * * Developers using `stream.unshift()` often should consider switching to * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. * * ```js * // Pull off a header delimited by \n\n. * // Use unshift() if we get too much. * // Call the callback with (error, header, stream). * const { StringDecoder } = require('node:string_decoder'); * function parseHeader(stream, callback) { * stream.on('error', callback); * stream.on('readable', onReadable); * const decoder = new StringDecoder('utf8'); * let header = ''; * function onReadable() { * let chunk; * while (null !== (chunk = stream.read())) { * const str = decoder.write(chunk); * if (str.includes('\n\n')) { * // Found the header boundary. * const split = str.split(/\n\n/); * header += split.shift(); * const remaining = split.join('\n\n'); * const buf = Buffer.from(remaining, 'utf8'); * stream.removeListener('error', callback); * // Remove the 'readable' listener before unshifting. * stream.removeListener('readable', onReadable); * if (buf.length) * stream.unshift(buf); * // Now the body of the message can be read from the stream. * callback(null, header, stream); * return; * } * // Still reading the header. * header += str; * } * } * } * ``` * * Unlike {@link push}, `stream.unshift(chunk)` wil
l not * end the reading process by resetting the internal reading state of the stream. * This can cause unexpected results if `readable.unshift()` is called during a * read (i.e. from within a {@link _read} implementation on a * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, * however it is best to simply avoid calling `readable.unshift()` while in the * process of performing a read. * @since v0.9.11 * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array`, or `null`. For object mode * streams, `chunk` may be any JavaScript value. * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. */ unshift(chunk: any, encoding?: BufferEncoding): void; /** * Prior to Node.js 0.10, streams did not implement the entire `node:stream`module API as it is currently defined. (See `Compatibility` for more * information.) * * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` * stream that uses * the old stream as its data source. * * It will rarely be necessary to use `readable.wrap()` but the method has been * provided as a convenience for interacting with older Node.js applications and * libraries. * * ```js * const { OldReader } = require('./old-api-module.js'); * const { Readable } = require('node:stream'); * const oreader = new OldReader(); * const myReader = new Readable().wrap(oreader); * * myReader.on('readable', () => { * myReader.read(); // etc. * }); * ``` * @since v0.9.4 * @param stream An "old style" readable stream */ wrap(stream: NodeJS.ReadableStream): this; push(chunk: any, encoding?: BufferEncoding): boolean; /** * The iterator created by this method gives users the option to cancel the destruction * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, * or if the iterator should destroy the stream if the stream emitted an error during iteration. * @since v16.3.0 * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. * **Default: `true`**. */ iterator(options?: { destroyOnReturn?: boolean }): AsyncIterableIterator<any>; /** * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. * @since v17.4.0, v16.14.0 * @param fn a function to map over every chunk in the stream. Async or not. * @returns a stream mapped with the function *fn*. */ map(fn: (data: any, options?: Pick<ArrayOptions, "signal">) => any, options?: ArrayOptions): Readable; /** * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called * and if it returns a truthy value, the chunk will be passed to the result stream. * If the *fn* function returns a promise - that promise will be `await`ed. * @since v17.4.0, v16.14.0 * @param fn a function to filter chunks from the stream. Async or not. * @returns a stream filtered with the predicate *fn*. */ f
ilter( fn: (data: any, options?: Pick<ArrayOptions, "signal">) => boolean | Promise<boolean>, options?: ArrayOptions, ): Readable; /** * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. * If the *fn* function returns a promise - that promise will be `await`ed. * * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. * In either case the stream will be destroyed. * * This method is different from listening to the `'data'` event in that it uses the `readable` event * in the underlying machinary and can limit the number of concurrent *fn* calls. * @since v17.5.0 * @param fn a function to call on each chunk of the stream. Async or not. * @returns a promise for when the stream has finished. */ forEach( fn: (data: any, options?: Pick<ArrayOptions, "signal">) => void | Promise<void>, options?: ArrayOptions, ): Promise<void>; /** * This method allows easily obtaining the contents of a stream. * * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended * for interoperability and convenience, not as the primary way to consume streams. * @since v17.5.0 * @returns a promise containing an array with the contents of the stream. */ toArray(options?: Pick<ArrayOptions, "signal">): Promise<any[]>; /** * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. * @since v17.5.0 * @param fn a function to call on each chunk of the stream. Async or not. * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. */ some( fn: (data: any, options?: Pick<ArrayOptions, "signal">) => boolean | Promise<boolean>, options?: ArrayOptions, ): Promise<boolean>; /** * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. * @since v17.5.0 * @param fn a function to call on each chunk of the stream. Async or not. * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, * or `undefined` if no element was found. */ find<T>( fn: (data: any, options?: Pick<ArrayOptions, "signal">) => data is T, options?: ArrayOptions, ): Promise<T | undefined>; find( fn: (data: any, options?: Pick<ArrayOptions, "signal">) => boolean | Promise<boolean>, options?: ArrayOptions, ): Promise<any>; /** * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk
* `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. * @since v17.5.0 * @param fn a function to call on each chunk of the stream. Async or not. * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. */ every( fn: (data: any, options?: Pick<ArrayOptions, "signal">) => boolean | Promise<boolean>, options?: ArrayOptions, ): Promise<boolean>; /** * This method returns a new stream by applying the given callback to each chunk of the stream * and then flattening the result. * * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams * will be merged (flattened) into the returned stream. * @since v17.5.0 * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. * @returns a stream flat-mapped with the function *fn*. */ flatMap(fn: (data: any, options?: Pick<ArrayOptions, "signal">) => any, options?: ArrayOptions): Readable; /** * This method returns a new stream with the first *limit* chunks dropped from the start. * @since v17.5.0 * @param limit the number of chunks to drop from the readable. * @returns a stream with *limit* chunks dropped from the start. */ drop(limit: number, options?: Pick<ArrayOptions, "signal">): Readable; /** * This method returns a new stream with the first *limit* chunks. * @since v17.5.0 * @param limit the number of chunks to take from the readable. * @returns a stream with *limit* chunks taken. */ take(limit: number, options?: Pick<ArrayOptions, "signal">): Readable; /** * This method returns a new stream with chunks of the underlying stream paired with a counter * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. * @since v17.5.0 * @returns a stream of indexed pairs. */ asIndexedPairs(options?: Pick<ArrayOptions, "signal">): Readable; /** * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation * on the previous element. It returns a promise for the final value of the reduction. * * If no *initial* value is supplied the first chunk of the stream is used as the initial value. * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. * * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. * @since v17.5.0 * @param fn a reducer function to call over every chunk in the stream. Async or not. * @param initial the initial value to use in the reduction. * @returns a promise for the final value of the reduction. */ reduce<T = any>( fn: (previous: any, data: any, options?: Pick<ArrayOptions, "signal">) => T, initial?: undefined, options?: Pick<ArrayOptions, "signal">, ): Promise<T>; reduce<T = any>( fn: (previous: T, data: any, options?: Pick<ArrayOptions, "signal">) => T, initial: T, options?: Pick<ArrayOptions, "signal">, ): Promise<T>; _destroy(error: Error | null, callback: (error?: Error | null) => void): void; /** * Destroy the stream. Optionally emit an `'error'` event, and emit a `'
close'`event (unless `emitClose` is set to `false`). After this call, the readable * stream will release any internal resources and subsequent calls to `push()`will be ignored. * * Once `destroy()` has been called any further calls will be a no-op and no * further errors except from `_destroy()` may be emitted as `'error'`. * * Implementors should not override this method, but instead implement `readable._destroy()`. * @since v8.0.0 * @param error Error which will be passed as payload in `'error'` event */ destroy(error?: Error): this; /** * Event emitter * The defined events on documents including: * 1. close * 2. data * 3. end * 4. error * 5. pause * 6. readable * 7. resume */ addListener(event: "close", listener: () => void): this; addListener(event: "data", listener: (chunk: any) => void): this; addListener(event: "end", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "pause", listener: () => void): this; addListener(event: "readable", listener: () => void): this; addListener(event: "resume", listener: () => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; emit(event: "close"): boolean; emit(event: "data", chunk: any): boolean; emit(event: "end"): boolean; emit(event: "error", err: Error): boolean; emit(event: "pause"): boolean; emit(event: "readable"): boolean; emit(event: "resume"): boolean; emit(event: string | symbol, ...args: any[]): boolean; on(event: "close", listener: () => void): this; on(event: "data", listener: (chunk: any) => void): this; on(event: "end", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "pause", listener: () => void): this; on(event: "readable", 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: any) => void): this; once(event: "end", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "pause", listener: () => void): this; once(event: "readable", 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: any) => void): this; prependListener(event: "end", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "pause", listener: () => void): this; prependListener(event: "readable", 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: any) => void): this; prependOnceListener(event: "end", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "pause", listener: () => void): this; prependOnceListener(event: "readable", listener: () => void): this; prependOnceListener(event: "resume", listener: () => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[
]) => void): this; removeListener(event: "close", listener: () => void): this; removeListener(event: "data", listener: (chunk: any) => void): this; removeListener(event: "end", listener: () => void): this; removeListener(event: "error", listener: (err: Error) => void): this; removeListener(event: "pause", listener: () => void): this; removeListener(event: "readable", listener: () => void): this; removeListener(event: "resume", listener: () => void): this; removeListener(event: string | symbol, listener: (...args: any[]) => void): this; [Symbol.asyncIterator](): AsyncIterableIterator<any>; /** * Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished. * @since v20.4.0 */ [Symbol.asyncDispose](): Promise<void>; } import WritableOptions = internal.WritableOptions; class WritableBase extends Stream implements NodeJS.WritableStream { /** * Is `true` if it is safe to call `writable.write()`, which means * the stream has not been destroyed, errored, or ended. * @since v11.4.0 */ readonly writable: boolean; /** * Is `true` after `writable.end()` has been called. This property * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. * @since v12.9.0 */ readonly writableEnded: boolean; /** * Is set to `true` immediately before the `'finish'` event is emitted. * @since v12.6.0 */ readonly writableFinished: boolean; /** * Return the value of `highWaterMark` passed when creating this `Writable`. * @since v9.3.0 */ readonly writableHighWaterMark: number; /** * This property contains the number of bytes (or objects) in the queue * ready to be written. The value provides introspection data regarding * the status of the `highWaterMark`. * @since v9.4.0 */ readonly writableLength: number; /** * Getter for the property `objectMode` of a given `Writable` stream. * @since v12.3.0 */ readonly writableObjectMode: boolean; /** * Number of times `writable.uncork()` needs to be * called in order to fully uncork the stream. * @since v13.2.0, v12.16.0 */ readonly writableCorked: number; /** * Is `true` after `writable.destroy()` has been called. * @since v8.0.0 */ destroyed: boolean; /** * Is `true` after `'close'` has been emitted. * @since v18.0.0 */ readonly closed: boolean; /** * Returns error if the stream has been destroyed with an error. * @since v18.0.0 */ readonly errored: Error | null; /** * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. * @since v15.2.0, v14.17.0 */ readonly writableNeedDrain: boolean; constructor(opts?: WritableOptions); _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; _writev?( chunks: Array<{ chunk: any; encoding: BufferEncoding; }>, callback: (error?: Error | null) => void, ): void; _construct?(callback: (error?: Error | null) => void): void; _destroy(error: Error | null, callback: (error?: Error | null) => void): void; _final(callback: (error?: Error | null) => void): void; /** * The `writable.write()` method writes some data to the stream, and calls the * supplied `callback` once the data has been fully handled. If an error * occurs, the `callback` will b
e called with the error as its * first argument. The `callback` is called asynchronously and before `'error'` is * emitted. * * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. * If `false` is returned, further attempts to write data to the stream should * stop until the `'drain'` event is emitted. * * While a stream is not draining, calls to `write()` will buffer `chunk`, and * return false. Once all currently buffered chunks are drained (accepted for * delivery by the operating system), the `'drain'` event will be emitted. * Once `write()` returns false, do not write more chunks * until the `'drain'` event is emitted. While calling `write()` on a stream that * is not draining is allowed, Node.js will buffer all written chunks until * maximum memory usage occurs, at which point it will abort unconditionally. * Even before it aborts, high memory usage will cause poor garbage collector * performance and high RSS (which is not typically released back to the system, * even after the memory is no longer required). Since TCP sockets may never * drain if the remote peer does not read the data, writing a socket that is * not draining may lead to a remotely exploitable vulnerability. * * Writing data while the stream is not draining is particularly * problematic for a `Transform`, because the `Transform` streams are paused * by default until they are piped or a `'data'` or `'readable'` event handler * is added. * * If the data to be written can be generated or fetched on demand, it is * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is * possible to respect backpressure and avoid memory issues using the `'drain'` event: * * ```js * function write(data, cb) { * if (!stream.write(data)) { * stream.once('drain', cb); * } else { * process.nextTick(cb); * } * } * * // Wait for cb to be called before doing any other write. * write('hello', () => { * console.log('Write completed, do more writes now.'); * }); * ``` * * A `Writable` stream in object mode will always ignore the `encoding` argument. * @since v0.9.4 * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any * JavaScript value other than `null`. * @param [encoding='utf8'] The encoding, if `chunk` is a string. * @param callback Callback for when this chunk of data is flushed. * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. */ write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; /** * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. * @since v0.11.15 * @param encoding The new default encoding */ setDefaultEncoding(encoding: BufferEncoding): this; /** * Calling the `writable.end()` method signals that no more data will be written * to the `Writable`. The optional `chunk` and `encoding` arguments allow one * final additional chunk of data to be written immediately before closing the * stream. * * C
alling the {@link write} method after calling {@link end} will raise an error. * * ```js * // Write 'hello, ' and then end with 'world!'. * const fs = require('node:fs'); * const file = fs.createWriteStream('example.txt'); * file.write('hello, '); * file.end('world!'); * // Writing more now is not allowed! * ``` * @since v0.9.4 * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any * JavaScript value other than `null`. * @param encoding The encoding if `chunk` is a string * @param callback Callback for when the stream is finished. */ end(cb?: () => void): this; end(chunk: any, cb?: () => void): this; end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; /** * The `writable.cork()` method forces all written data to be buffered in memory. * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. * * The primary intent of `writable.cork()` is to accommodate a situation in which * several small chunks are written to the stream in rapid succession. Instead of * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them * all to `writable._writev()`, if present. This prevents a head-of-line blocking * situation where data is being buffered while waiting for the first small chunk * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. * * See also: `writable.uncork()`, `writable._writev()`. * @since v0.11.2 */ cork(): void; /** * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. * * When using `writable.cork()` and `writable.uncork()` to manage the buffering * of writes to a stream, defer calls to `writable.uncork()` using`process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event * loop phase. * * ```js * stream.cork(); * stream.write('some '); * stream.write('data '); * process.nextTick(() => stream.uncork()); * ``` * * If the `writable.cork()` method is called multiple times on a stream, the * same number of calls to `writable.uncork()` must be called to flush the buffered * data. * * ```js * stream.cork(); * stream.write('some '); * stream.cork(); * stream.write('data '); * process.nextTick(() => { * stream.uncork(); * // The data will not be flushed until uncork() is called a second time. * stream.uncork(); * }); * ``` * * See also: `writable.cork()`. * @since v0.11.2 */ uncork(): void; /** * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable * stream has ended and subsequent calls to `write()` or `end()` will result in * an `ERR_STREAM_DESTROYED` error. * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. * Use `end()` instead of destroy if data should flush before close, or wait for * the `'drain'` event before destroying the stream. * * Once `destroy()` has been called any further calls will be a no-op and no
* further errors except from `_destroy()` may be emitted as `'error'`. * * Implementors should not override this method, * but instead implement `writable._destroy()`. * @since v8.0.0 * @param error Optional, an error to emit with `'error'` event. */ destroy(error?: Error): this; /** * Event emitter * The defined events on documents including: * 1. close * 2. drain * 3. error * 4. finish * 5. pipe * 6. unpipe */ addListener(event: "close", listener: () => void): this; addListener(event: "drain", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "finish", listener: () => void): this; addListener(event: "pipe", listener: (src: Readable) => void): this; addListener(event: "unpipe", listener: (src: Readable) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; emit(event: "close"): boolean; emit(event: "drain"): boolean; emit(event: "error", err: Error): boolean; emit(event: "finish"): boolean; emit(event: "pipe", src: Readable): boolean; emit(event: "unpipe", src: Readable): boolean; emit(event: string | symbol, ...args: any[]): boolean; on(event: "close", listener: () => void): this; on(event: "drain", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "finish", listener: () => void): this; on(event: "pipe", listener: (src: Readable) => void): this; on(event: "unpipe", listener: (src: Readable) => void): this; 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: "pipe", listener: (src: Readable) => void): this; once(event: "unpipe", listener: (src: 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: "pipe", listener: (src: Readable) => void): this; prependListener(event: "unpipe", listener: (src: 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: "pipe", listener: (src: Readable) => void): this; prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; removeListener(event: "close", listener: () => void): this; removeListener(event: "drain", listener: () => void): this; removeListener(event: "error", listener: (err: Error) => void): this; removeListener(event: "finish", listener: () => void): this; removeListener(event: "pipe", listener: (src: Readable) => void): this; removeListener(event: "unpipe", listener: (src: Readable) => void): this; removeListener(event: string | symbol, listener: (...args: any[]) => void): this; }
namespace internal { class Stream extends internal { constructor(opts?: ReadableOptions); } interface StreamOptions<T extends Stream> extends Abortable { emitClose?: boolean | undefined; highWaterMark?: number | undefined; objectMode?: boolean | undefined; construct?(this: T, callback: (error?: Error | null) => void): void; destroy?(this: T, error: Error | null, callback: (error?: Error | null) => void): void; autoDestroy?: boolean | undefined; } interface ReadableOptions extends StreamOptions<Readable> { encoding?: BufferEncoding | undefined; read?(this: Readable, size: number): void; } /** * @since v0.9.4 */ class Readable extends ReadableBase { /** * A utility method for creating a `Readable` from a web `ReadableStream`. * @since v17.0.0 * @experimental */ static fromWeb( readableStream: streamWeb.ReadableStream, options?: Pick<ReadableOptions, "encoding" | "highWaterMark" | "objectMode" | "signal">, ): Readable; /** * A utility method for creating a web `ReadableStream` from a `Readable`. * @since v17.0.0 * @experimental */ static toWeb(streamReadable: Readable): streamWeb.ReadableStream; } interface WritableOptions extends StreamOptions<Writable> { decodeStrings?: boolean | undefined; defaultEncoding?: BufferEncoding | undefined; write?( this: Writable, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void, ): void; writev?( this: Writable, chunks: Array<{ chunk: any; encoding: BufferEncoding; }>, callback: (error?: Error | null) => void, ): void; final?(this: Writable, callback: (error?: Error | null) => void): void; } /** * @since v0.9.4 */ class Writable extends WritableBase { /** * A utility method for creating a `Writable` from a web `WritableStream`. * @since v17.0.0 * @experimental */ static fromWeb( writableStream: streamWeb.WritableStream, options?: Pick<WritableOptions, "decodeStrings" | "highWaterMark" | "objectMode" | "signal">, ): Writable; /** * A utility method for creating a web `WritableStream` from a `Writable`. * @since v17.0.0 * @experimental */ static toWeb(streamWritable: Writable): streamWeb.WritableStream; } interface DuplexOptions extends ReadableOptions, WritableOptions { allowHalfOpen?: boolean | undefined; readableObjectMode?: boolean | undefined; writableObjectMode?: boolean | undefined; readableHighWaterMark?: number | undefined; writableHighWaterMark?: number | undefined; writableCorked?: number | undefined; construct?(this: Duplex, callback: (error?: Error | null) => void): void; read?(this: Duplex, size: number): void; write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; writev?( this: Duplex, chunks: Array<{ chunk: any; encoding: BufferEncoding; }>, callback: (error?: Error | null) => void, ): void; final?(this: Duplex, callback: (error?: Error | null) => void): void;
destroy?(this: Duplex, error: Error | null, callback: (error?: Error | null) => void): void; } /** * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. * * Examples of `Duplex` streams include: * * * `TCP sockets` * * `zlib streams` * * `crypto streams` * @since v0.9.4 */ class Duplex extends ReadableBase implements WritableBase { readonly writable: boolean; readonly writableEnded: boolean; readonly writableFinished: boolean; readonly writableHighWaterMark: number; readonly writableLength: number; readonly writableObjectMode: boolean; readonly writableCorked: number; readonly writableNeedDrain: boolean; readonly closed: boolean; readonly errored: Error | null; /** * If `false` then the stream will automatically end the writable side when the * readable side ends. Set initially by the `allowHalfOpen` constructor option, * which defaults to `true`. * * This can be changed manually to change the half-open behavior of an existing`Duplex` stream instance, but must be changed before the `'end'` event is * emitted. * @since v0.9.4 */ allowHalfOpen: boolean; constructor(opts?: DuplexOptions); /** * A utility method for creating duplex streams. * * - `Stream` converts writable stream into writable `Duplex` and readable stream * to `Duplex`. * - `Blob` converts into readable `Duplex`. * - `string` converts into readable `Duplex`. * - `ArrayBuffer` converts into readable `Duplex`. * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. * - `AsyncGeneratorFunction` converts into a readable/writable transform * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield * `null`. * - `AsyncFunction` converts into a writable `Duplex`. Must return * either `null` or `undefined` * - `Object ({ writable, readable })` converts `readable` and * `writable` into `Stream` and then combines them into `Duplex` where the * `Duplex` will write to the `writable` and read from the `readable`. * - `Promise` converts into readable `Duplex`. Value `null` is ignored. * * @since v16.8.0 */ static from( src: | Stream | NodeBlob | ArrayBuffer | string | Iterable<any> | AsyncIterable<any> | AsyncGeneratorFunction | Promise<any> | Object, ): Duplex; _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; _writev?( chunks: Array<{ chunk: any; encoding: BufferEncoding; }>, callback: (error?: Error | null) => void, ): void; _destroy(error: Error | null, callback: (error?: Error | null) => void): void; _final(callback: (error?: Error | null) => void): void; write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; setDefaultEncoding(encoding: BufferEncoding): this; end(cb?: () => void): this; end(chunk: any, cb?: () => void): this; end(chunk: any, encoding?: Bu
fferEncoding, cb?: () => void): this; cork(): void; uncork(): void; /** * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. * @since v17.0.0 * @experimental */ static toWeb(streamDuplex: Duplex): { readable: streamWeb.ReadableStream; writable: streamWeb.WritableStream; }; /** * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. * @since v17.0.0 * @experimental */ static fromWeb( duplexStream: { readable: streamWeb.ReadableStream; writable: streamWeb.WritableStream; }, options?: Pick< DuplexOptions, "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" >, ): Duplex; /** * Event emitter * The defined events on documents including: * 1. close * 2. data * 3. drain * 4. end * 5. error * 6. finish * 7. pause * 8. pipe * 9. readable * 10. resume * 11. unpipe */ addListener(event: "close", listener: () => void): this; addListener(event: "data", listener: (chunk: any) => void): this; addListener(event: "drain", listener: () => void): this; addListener(event: "end", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "finish", listener: () => void): this; addListener(event: "pause", listener: () => void): this; addListener(event: "pipe", listener: (src: Readable) => void): this; addListener(event: "readable", listener: () => void): this; addListener(event: "resume", listener: () => void): this; addListener(event: "unpipe", listener: (src: Readable) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; emit(event: "close"): boolean; emit(event: "data", chunk: any): boolean; emit(event: "drain"): boolean; emit(event: "end"): boolean; emit(event: "error", err: Error): boolean; emit(event: "finish"): boolean; emit(event: "pause"): boolean; emit(event: "pipe", src: Readable): boolean; emit(event: "readable"): boolean; emit(event: "resume"): boolean; emit(event: "unpipe", src: Readable): boolean; emit(event: string | symbol, ...args: any[]): boolean; on(event: "close", listener: () => void): this; on(event: "data", listener: (chunk: any) => void): this; on(event: "drain", listener: () => void): this; on(event: "end", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "finish", listener: () => void): this; on(event: "pause", listener: () => void): this; on(event: "pipe", listener: (src: Readable) => void): this; on(event: "readable", listener: () => void): this; on(event: "resume", listener: () => void): this; on(event: "unpipe", listener: (src: Readable) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "data", listener: (chunk: any) => void): this; once(event: "drain", listener: () => void): this; once(event: "end", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this; once(event: "finish", listener: () => void): this; once(event: "pause", listener: () => void): this; once(event: "pipe", listener: (src: Readable) => void): this; once(event: "readable", listener: () => void): this; once(event: "resume", listener: () => void): this; once(event: "unpipe", listener: (src: Readable) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "data", listener: (chunk: any) => void): this; prependListener(event: "drain", listener: () => void): this; prependListener(event: "end", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "finish", listener: () => void): this; prependListener(event: "pause", listener: () => void): this; prependListener(event: "pipe", listener: (src: Readable) => void): this; prependListener(event: "readable", listener: () => void): this; prependListener(event: "resume", listener: () => void): this; prependListener(event: "unpipe", listener: (src: Readable) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "data", listener: (chunk: any) => void): this; prependOnceListener(event: "drain", listener: () => void): this; prependOnceListener(event: "end", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "finish", listener: () => void): this; prependOnceListener(event: "pause", listener: () => void): this; prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; prependOnceListener(event: "readable", listener: () => void): this; prependOnceListener(event: "resume", listener: () => void): this; prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; removeListener(event: "close", listener: () => void): this; removeListener(event: "data", listener: (chunk: any) => void): this; removeListener(event: "drain", listener: () => void): this; removeListener(event: "end", listener: () => void): this; removeListener(event: "error", listener: (err: Error) => void): this; removeListener(event: "finish", listener: () => void): this; removeListener(event: "pause", listener: () => void): this; removeListener(event: "pipe", listener: (src: Readable) => void): this; removeListener(event: "readable", listener: () => void): this; removeListener(event: "resume", listener: () => void): this; removeListener(event: "unpipe", listener: (src: Readable) => void): this; removeListener(event: string | symbol, listener: (...args: any[]) => void): this; } type TransformCallback = (error?: Error | null, data?: any) => void; interface TransformOptions extends DuplexOptions { construct?(this: Transform, callback: (error?: Error | null) => void): void; read?(this: Transform, size: number): void; write?( this: Transform, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void, ): void; writev?( this: Transform, chu
nks: Array<{ chunk: any; encoding: BufferEncoding; }>, callback: (error?: Error | null) => void, ): void; final?(this: Transform, callback: (error?: Error | null) => void): void; destroy?(this: Transform, error: Error | null, callback: (error?: Error | null) => void): void; transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; flush?(this: Transform, callback: TransformCallback): void; } /** * Transform streams are `Duplex` streams where the output is in some way * related to the input. Like all `Duplex` streams, `Transform` streams * implement both the `Readable` and `Writable` interfaces. * * Examples of `Transform` streams include: * * * `zlib streams` * * `crypto streams` * @since v0.9.4 */ class Transform extends Duplex { constructor(opts?: TransformOptions); _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; _flush(callback: TransformCallback): void; } /** * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. */ class PassThrough extends Transform {} /** * A stream to attach a signal to. * * Attaches an AbortSignal to a readable or writeable stream. This lets code * control stream destruction using an `AbortController`. * * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream, and `controller.error(new * AbortError())` for webstreams. * * ```js * const fs = require('node:fs'); * * const controller = new AbortController(); * const read = addAbortSignal( * controller.signal, * fs.createReadStream(('object.json')), * ); * // Later, abort the operation closing the stream * controller.abort(); * ``` * * Or using an `AbortSignal` with a readable stream as an async iterable: * * ```js * const controller = new AbortController(); * setTimeout(() => controller.abort(), 10_000); // set a timeout * const stream = addAbortSignal( * controller.signal, * fs.createReadStream(('object.json')), * ); * (async () => { * try { * for await (const chunk of stream) { * await process(chunk); * } * } catch (e) { * if (e.name === 'AbortError') { * // The operation was cancelled * } else { * throw e; * } * } * })(); * ``` * * Or using an `AbortSignal` with a ReadableStream: * * ```js * const controller = new AbortController(); * const rs = new ReadableStream({ * start(controller) { * controller.enqueue('hello'); * controller.enqueue('world'); * controller.close(); * }, * }); * * addAbortSignal(controller.signal, rs); * * finished(rs, (err) => { * if (err) { * if (err.name === 'AbortError') { * // The operation was cancelled * } * } * }); * * const reader = rs.getReader(); * * reader.rea
d().then(({ value, done }) => { * console.log(value); // hello * console.log(done); // false * controller.abort(); * }); * ``` * @since v15.4.0 * @param signal A signal representing possible cancellation * @param stream a stream to attach a signal to */ function addAbortSignal<T extends Stream>(signal: AbortSignal, stream: T): T; /** * Returns the default highWaterMark used by streams. * Defaults to `16384` (16 KiB), or `16` for `objectMode`. * @since v19.9.0 * @param objectMode */ function getDefaultHighWaterMark(objectMode: boolean): number; /** * Sets the default highWaterMark used by streams. * @since v19.9.0 * @param objectMode * @param value highWaterMark value */ function setDefaultHighWaterMark(objectMode: boolean, value: number): void; interface FinishedOptions extends Abortable { error?: boolean | undefined; readable?: boolean | undefined; writable?: boolean | undefined; } /** * A readable and/or writable stream/webstream. * * A function to get notified when a stream is no longer readable, writable * or has experienced an error or a premature close event. * * ```js * const { finished } = require('node:stream'); * const fs = require('node:fs'); * * const rs = fs.createReadStream('archive.tar'); * * finished(rs, (err) => { * if (err) { * console.error('Stream failed.', err); * } else { * console.log('Stream is done reading.'); * } * }); * * rs.resume(); // Drain the stream. * ``` * * Especially useful in error handling scenarios where a stream is destroyed * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. * * The `finished` API provides `promise version`. * * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been * invoked. The reason for this is so that unexpected `'error'` events (due to * incorrect stream implementations) do not cause unexpected crashes. * If this is unwanted behavior then the returned cleanup function needs to be * invoked in the callback: * * ```js * const cleanup = finished(rs, (err) => { * cleanup(); * // ... * }); * ``` * @since v10.0.0 * @param stream A readable and/or writable stream. * @param callback A callback function that takes an optional error argument. * @return A cleanup function which removes all registered listeners. */ function finished( stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options: FinishedOptions, callback: (err?: NodeJS.ErrnoException | null) => void, ): () => void; function finished( stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException | null) => void, ): () => void; namespace finished { function __promisify__( stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions, ): Promise<void>; } type PipelineSourceFunction<T> = () => Iterable<T> | AsyncIterable<T>; type PipelineSource<T> = Iterable<T> | AsyncIterable<T> | NodeJS.ReadableStream | PipelineSourceFunction<T>; type PipelineTransform<S extends PipelineTransformSource<any>, U> =
| NodeJS.ReadWriteStream | (( source: S extends (...args: any[]) => Iterable<infer ST> | AsyncIterable<infer ST> ? AsyncIterable<ST> : S, ) => AsyncIterable<U>); type PipelineTransformSource<T> = PipelineSource<T> | PipelineTransform<any, T>; type PipelineDestinationIterableFunction<T> = (source: AsyncIterable<T>) => AsyncIterable<any>; type PipelineDestinationPromiseFunction<T, P> = (source: AsyncIterable<T>) => Promise<P>; type PipelineDestination<S extends PipelineTransformSource<any>, P> = S extends PipelineTransformSource<infer ST> ? | NodeJS.WritableStream | PipelineDestinationIterableFunction<ST> | PipelineDestinationPromiseFunction<ST, P> : never; type PipelineCallback<S extends PipelineDestination<any, any>> = S extends PipelineDestinationPromiseFunction<any, infer P> ? (err: NodeJS.ErrnoException | null, value: P) => void : (err: NodeJS.ErrnoException | null) => void; type PipelinePromise<S extends PipelineDestination<any, any>> = S extends PipelineDestinationPromiseFunction<any, infer P> ? Promise<P> : Promise<void>; interface PipelineOptions { signal?: AbortSignal | undefined; end?: boolean | undefined; } /** * A module method to pipe between streams and generators forwarding errors and * properly cleaning up and provide a callback when the pipeline is complete. * * ```js * const { pipeline } = require('node:stream'); * const fs = require('node:fs'); * const zlib = require('node:zlib'); * * // Use the pipeline API to easily pipe a series of streams * // together and get notified when the pipeline is fully done. * * // A pipeline to gzip a potentially huge tar file efficiently: * * pipeline( * fs.createReadStream('archive.tar'), * zlib.createGzip(), * fs.createWriteStream('archive.tar.gz'), * (err) => { * if (err) { * console.error('Pipeline failed.', err); * } else { * console.log('Pipeline succeeded.'); * } * }, * ); * ``` * * The `pipeline` API provides a `promise version`. * * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: * * * `Readable` streams which have emitted `'end'` or `'close'`. * * `Writable` streams which have emitted `'finish'` or `'close'`. * * `stream.pipeline()` leaves dangling event listeners on the streams * after the `callback` has been invoked. In the case of reuse of streams after * failure, this can cause event listener leaks and swallowed errors. If the last * stream is readable, dangling event listeners will be removed so that the last * stream can be consumed later. * * `stream.pipeline()` closes all the streams when an error is raised. * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior * once it would destroy the socket without sending the expected response. * See the example below: * * ```js * const fs = require('node:fs'); * const http = require('node:http'); * const { pipeline } = require('node:stream'); * * const server = http.createServer((req, res) => { * const fileStream = fs.createReadStream('./fileNotExist.txt'); * pipeline(fileStream, res, (err) => { * if (err) { * console.log(err); // No such file * // this message can't be sent once `pipeline` already destroyed the socket * return res.end('error!
!!'); * } * }); * }); * ``` * @since v10.0.0 * @param callback Called when the pipeline is fully done. */ function pipeline<A extends PipelineSource<any>, B extends PipelineDestination<A, any>>( source: A, destination: B, callback?: PipelineCallback<B>, ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; function pipeline< A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, B extends PipelineDestination<T1, any>, >( source: A, transform1: T1, destination: B, callback?: PipelineCallback<B>, ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; function pipeline< A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, B extends PipelineDestination<T2, any>, >( source: A, transform1: T1, transform2: T2, destination: B, callback?: PipelineCallback<B>, ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; function pipeline< A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, T3 extends PipelineTransform<T2, any>, B extends PipelineDestination<T3, any>, >( source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, callback?: PipelineCallback<B>, ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; function pipeline< A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, T3 extends PipelineTransform<T2, any>, T4 extends PipelineTransform<T3, any>, B extends PipelineDestination<T4, any>, >( source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, callback?: PipelineCallback<B>, ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; function pipeline( streams: ReadonlyArray<NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream>, callback?: (err: NodeJS.ErrnoException | null) => void, ): NodeJS.WritableStream; function pipeline( stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, ...streams: Array< NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) > ): NodeJS.WritableStream; namespace pipeline { function __promisify__<A extends PipelineSource<any>, B extends PipelineDestination<A, any>>( source: A, destination: B, options?: PipelineOptions, ): PipelinePromise<B>; function __promisify__< A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, B extends PipelineDestination<T1, any>, >( source: A, transform1: T1, destination: B, options?: PipelineOptions, ): PipelinePromise<B>; function __promisify__< A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, B extends PipelineDestination<T2, any>, >( source: A, transform1: T1, transform2: T2,
destination: B, options?: PipelineOptions, ): PipelinePromise<B>; function __promisify__< A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, T3 extends PipelineTransform<T2, any>, B extends PipelineDestination<T3, any>, >( source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions, ): PipelinePromise<B>; function __promisify__< A extends PipelineSource<any>, T1 extends PipelineTransform<A, any>, T2 extends PipelineTransform<T1, any>, T3 extends PipelineTransform<T2, any>, T4 extends PipelineTransform<T3, any>, B extends PipelineDestination<T4, any>, >( source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions, ): PipelinePromise<B>; function __promisify__( streams: ReadonlyArray<NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream>, options?: PipelineOptions, ): Promise<void>; function __promisify__( stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, ...streams: Array<NodeJS.ReadWriteStream | NodeJS.WritableStream | PipelineOptions> ): Promise<void>; } interface Pipe { close(): void; hasRef(): boolean; ref(): void; unref(): void; } /** * Returns whether the stream has encountered an error. * @since v17.3.0, v16.14.0 * @experimental */ function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; /** * Returns whether the stream is readable. * @since v17.4.0, v16.14.0 * @experimental */ function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; const promises: typeof streamPromises; const consumers: typeof streamConsumers; } export = internal; } declare module "node:stream" { import stream = require("stream"); export = stream; }
// Type definitions for inspector // These definitions are auto-generated. // Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 // for more information. /** * The `node:inspector` module provides an API for interacting with the V8 * inspector. * * It can be accessed using: * * ```js * import * as inspector from 'node:inspector/promises'; * ``` * * or * * ```js * import * as inspector from 'node:inspector'; * ``` * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/inspector.js) */ declare module 'inspector' { import EventEmitter = require('node:events'); interface InspectorNotification<T> { method: string; params: T; } namespace Schema { /** * Description of the protocol domain. */ interface Domain { /** * Domain name. */ name: string; /** * Domain version. */ version: string; } interface GetDomainsReturnType { /** * List of supported domains. */ domains: Domain[]; } } namespace Runtime { /** * Unique script identifier. */ type ScriptId = string; /** * Unique object identifier. */ type RemoteObjectId = string; /** * Primitive value which cannot be JSON-stringified. */ type UnserializableValue = string; /** * Mirror object referencing original JavaScript object. */ interface RemoteObject { /** * Object type. */ type: string; /** * Object subtype hint. Specified for <code>object</code> type values only. */ subtype?: string | undefined; /** * Object class (constructor) name. Specified for <code>object</code> type values only. */ className?: string | undefined; /** * Remote object value in case of primitive values or JSON values (if it was requested). */ value?: any; /** * Primitive value which can not be JSON-stringified does not have <code>value</code>, but gets this property. */ unserializableValue?: UnserializableValue | undefined; /** * String representation of the object. */ description?: string | undefined; /** * Unique object identifier (for non-primitive values). */ objectId?: RemoteObjectId | undefined; /** * Preview containing abbreviated property values. Specified for <code>object</code> type values only. * @experimental */ preview?: ObjectPreview | undefined; /** * @experimental */ customPreview?: CustomPreview | undefined; } /** * @experimental */ interface CustomPreview { header: string; hasBody: boolean; formatterObjectId: RemoteObjectId; bindRemoteObjectFunctionId: RemoteObjectId; configObjectId?: RemoteObjectId | undefined; } /** * Object containing abbreviated remote object value. * @experimental */ interface ObjectPreview { /** * Object type. */ type: string; /** * Object subtype hint. Specified for <code>object</code> type values only. */ subtype?: string | undefined; /** * String representation of the object. */ description?: string | undefined; /** * True iff some of the properties or entries of the orig
inal object did not fit. */ overflow: boolean; /** * List of the properties. */ properties: PropertyPreview[]; /** * List of the entries. Specified for <code>map</code> and <code>set</code> subtype values only. */ entries?: EntryPreview[] | undefined; } /** * @experimental */ interface PropertyPreview { /** * Property name. */ name: string; /** * Object type. Accessor means that the property itself is an accessor property. */ type: string; /** * User-friendly property value string. */ value?: string | undefined; /** * Nested value preview. */ valuePreview?: ObjectPreview | undefined; /** * Object subtype hint. Specified for <code>object</code> type values only. */ subtype?: string | undefined; } /** * @experimental */ interface EntryPreview { /** * Preview of the key. Specified for map-like collection entries. */ key?: ObjectPreview | undefined; /** * Preview of the value. */ value: ObjectPreview; } /** * Object property descriptor. */ interface PropertyDescriptor { /** * Property name or symbol description. */ name: string; /** * The value associated with the property. */ value?: RemoteObject | undefined; /** * True if the value associated with the property may be changed (data descriptors only). */ writable?: boolean | undefined; /** * A function which serves as a getter for the property, or <code>undefined</code> if there is no getter (accessor descriptors only). */ get?: RemoteObject | undefined; /** * A function which serves as a setter for the property, or <code>undefined</code> if there is no setter (accessor descriptors only). */ set?: RemoteObject | undefined; /** * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. */ configurable: boolean; /** * True if this property shows up during enumeration of the properties on the corresponding object. */ enumerable: boolean; /** * True if the result was thrown during the evaluation. */ wasThrown?: boolean | undefined; /** * True if the property is owned for the object. */ isOwn?: boolean | undefined; /** * Property symbol object, if the property is of the <code>symbol</code> type. */ symbol?: RemoteObject | undefined; } /** * Object internal property descriptor. This property isn't normally visible in JavaScript code. */ interface InternalPropertyDescriptor { /** * Conventional property name. */ name: string; /** * The value associated with the property. */ value?: RemoteObject | undefined; } /** * Represents function call argument. Either remote object id <code>objectId</code>, primitive <code>value</code>, unserializable primitive value or neither of (for undefined) them should be specified. */ interface CallArgument { /**
* Primitive value or serializable javascript object. */ value?: any; /** * Primitive value which can not be JSON-stringified. */ unserializableValue?: UnserializableValue | undefined; /** * Remote object handle. */ objectId?: RemoteObjectId | undefined; } /** * Id of an execution context. */ type ExecutionContextId = number; /** * Description of an isolated world. */ interface ExecutionContextDescription { /** * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. */ id: ExecutionContextId; /** * Execution context origin. */ origin: string; /** * Human readable name describing given context. */ name: string; /** * Embedder-specific auxiliary data. */ auxData?: {} | undefined; } /** * Detailed information about exception (or error) that was thrown during script compilation or execution. */ interface ExceptionDetails { /** * Exception id. */ exceptionId: number; /** * Exception text, which should be used together with exception object when available. */ text: string; /** * Line number of the exception location (0-based). */ lineNumber: number; /** * Column number of the exception location (0-based). */ columnNumber: number; /** * Script ID of the exception location. */ scriptId?: ScriptId | undefined; /** * URL of the exception location, to be used when the script was not reported. */ url?: string | undefined; /** * JavaScript stack trace if available. */ stackTrace?: StackTrace | undefined; /** * Exception object if available. */ exception?: RemoteObject | undefined; /** * Identifier of the context where exception happened. */ executionContextId?: ExecutionContextId | undefined; } /** * Number of milliseconds since epoch. */ type Timestamp = number; /** * Stack entry for runtime errors and assertions. */ interface CallFrame { /** * JavaScript function name. */ functionName: string; /** * JavaScript script id. */ scriptId: ScriptId; /** * JavaScript script name or url. */ url: string; /** * JavaScript script line number (0-based). */ lineNumber: number; /** * JavaScript script column number (0-based). */ columnNumber: number; } /** * Call frames for assertions or error messages. */ interface StackTrace { /** * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. */ description?: string | undefined; /** * JavaScript function name. */ callFrames: CallFrame[]; /** * Asynchronous JavaScript stack trace that preceded this stack, if available. */ parent?: StackTrace | undefined; /**
* Asynchronous JavaScript stack trace that preceded this stack, if available. * @experimental */ parentId?: StackTraceId | undefined; } /** * Unique identifier of current debugger. * @experimental */ type UniqueDebuggerId = string; /** * If <code>debuggerId</code> is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See <code>Runtime.StackTrace</code> and <code>Debugger.paused</code> for usages. * @experimental */ interface StackTraceId { id: string; debuggerId?: UniqueDebuggerId | undefined; } interface EvaluateParameterType { /** * Expression to evaluate. */ expression: string; /** * Symbolic group name that can be used to release multiple objects. */ objectGroup?: string | undefined; /** * Determines whether Command Line API should be available during the evaluation. */ includeCommandLineAPI?: boolean | undefined; /** * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. */ silent?: boolean | undefined; /** * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. */ contextId?: ExecutionContextId | undefined; /** * Whether the result is expected to be a JSON object that should be sent by value. */ returnByValue?: boolean | undefined; /** * Whether preview should be generated for the result. * @experimental */ generatePreview?: boolean | undefined; /** * Whether execution should be treated as initiated by user in the UI. */ userGesture?: boolean | undefined; /** * Whether execution should <code>await</code> for resulting value and return once awaited promise is resolved. */ awaitPromise?: boolean | undefined; } interface AwaitPromiseParameterType { /** * Identifier of the promise. */ promiseObjectId: RemoteObjectId; /** * Whether the result is expected to be a JSON object that should be sent by value. */ returnByValue?: boolean | undefined; /** * Whether preview should be generated for the result. */ generatePreview?: boolean | undefined; } interface CallFunctionOnParameterType { /** * Declaration of the function to call. */ functionDeclaration: string; /** * Identifier of the object to call function on. Either objectId or executionContextId should be specified. */ objectId?: RemoteObjectId | undefined; /** * Call arguments. All call arguments must belong to the same JavaScript world as the target object. */ arguments?: CallArgument[] | undefined; /** * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. */ silent?: boolean | undefined; /** * Whether the result is expected to be a JSON object which should be sent by value. */ returnByValue?: boolean | undefined; /** * Whether preview should be generated f
or the result. * @experimental */ generatePreview?: boolean | undefined; /** * Whether execution should be treated as initiated by user in the UI. */ userGesture?: boolean | undefined; /** * Whether execution should <code>await</code> for resulting value and return once awaited promise is resolved. */ awaitPromise?: boolean | undefined; /** * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. */ executionContextId?: ExecutionContextId | undefined; /** * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. */ objectGroup?: string | undefined; } interface GetPropertiesParameterType { /** * Identifier of the object to return properties for. */ objectId: RemoteObjectId; /** * If true, returns properties belonging only to the element itself, not to its prototype chain. */ ownProperties?: boolean | undefined; /** * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. * @experimental */ accessorPropertiesOnly?: boolean | undefined; /** * Whether preview should be generated for the results. * @experimental */ generatePreview?: boolean | undefined; } interface ReleaseObjectParameterType { /** * Identifier of the object to release. */ objectId: RemoteObjectId; } interface ReleaseObjectGroupParameterType { /** * Symbolic object group name. */ objectGroup: string; } interface SetCustomObjectFormatterEnabledParameterType { enabled: boolean; } interface CompileScriptParameterType { /** * Expression to compile. */ expression: string; /** * Source url to be set for the script. */ sourceURL: string; /** * Specifies whether the compiled script should be persisted. */ persistScript: boolean; /** * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. */ executionContextId?: ExecutionContextId | undefined; } interface RunScriptParameterType { /** * Id of the script to run. */ scriptId: ScriptId; /** * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. */ executionContextId?: ExecutionContextId | undefined; /** * Symbolic group name that can be used to release multiple objects. */ objectGroup?: string | undefined; /** * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. */ silent?: boolean | undefined; /** * Determines whether Command Line API should be available during the evaluation. */ includeCommandLineAPI?: boolean | undefined; /** * Whether the result is expected to be
a JSON object which should be sent by value. */ returnByValue?: boolean | undefined; /** * Whether preview should be generated for the result. */ generatePreview?: boolean | undefined; /** * Whether execution should <code>await</code> for resulting value and return once awaited promise is resolved. */ awaitPromise?: boolean | undefined; } interface QueryObjectsParameterType { /** * Identifier of the prototype to return objects for. */ prototypeObjectId: RemoteObjectId; } interface GlobalLexicalScopeNamesParameterType { /** * Specifies in which execution context to lookup global scope variables. */ executionContextId?: ExecutionContextId | undefined; } interface EvaluateReturnType { /** * Evaluation result. */ result: RemoteObject; /** * Exception details. */ exceptionDetails?: ExceptionDetails | undefined; } interface AwaitPromiseReturnType { /** * Promise result. Will contain rejected value if promise was rejected. */ result: RemoteObject; /** * Exception details if stack strace is available. */ exceptionDetails?: ExceptionDetails | undefined; } interface CallFunctionOnReturnType { /** * Call result. */ result: RemoteObject; /** * Exception details. */ exceptionDetails?: ExceptionDetails | undefined; } interface GetPropertiesReturnType { /** * Object properties. */ result: PropertyDescriptor[]; /** * Internal object properties (only of the element itself). */ internalProperties?: InternalPropertyDescriptor[] | undefined; /** * Exception details. */ exceptionDetails?: ExceptionDetails | undefined; } interface CompileScriptReturnType { /** * Id of the script. */ scriptId?: ScriptId | undefined; /** * Exception details. */ exceptionDetails?: ExceptionDetails | undefined; } interface RunScriptReturnType { /** * Run result. */ result: RemoteObject; /** * Exception details. */ exceptionDetails?: ExceptionDetails | undefined; } interface QueryObjectsReturnType { /** * Array with objects. */ objects: RemoteObject; } interface GlobalLexicalScopeNamesReturnType { names: string[]; } interface ExecutionContextCreatedEventDataType { /** * A newly created execution context. */ context: ExecutionContextDescription; } interface ExecutionContextDestroyedEventDataType { /** * Id of the destroyed context */ executionContextId: ExecutionContextId; } interface ExceptionThrownEventDataType { /** * Timestamp of the exception. */ timestamp: Timestamp; exceptionDetails: ExceptionDetails; } interface ExceptionRevokedEventDataType { /** * Reason describing why exception was revoked. */ reason: string; /** * The id of revoked exception, as reported in <code>exceptionThrown</code>.
*/ exceptionId: number; } interface ConsoleAPICalledEventDataType { /** * Type of the call. */ type: string; /** * Call arguments. */ args: RemoteObject[]; /** * Identifier of the context where the call was made. */ executionContextId: ExecutionContextId; /** * Call timestamp. */ timestamp: Timestamp; /** * Stack trace captured when the call was made. */ stackTrace?: StackTrace | undefined; /** * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. * @experimental */ context?: string | undefined; } interface InspectRequestedEventDataType { object: RemoteObject; hints: {}; } } namespace Debugger { /** * Breakpoint identifier. */ type BreakpointId = string; /** * Call frame identifier. */ type CallFrameId = string; /** * Location in the source code. */ interface Location { /** * Script identifier as reported in the <code>Debugger.scriptParsed</code>. */ scriptId: Runtime.ScriptId; /** * Line number in the script (0-based). */ lineNumber: number; /** * Column number in the script (0-based). */ columnNumber?: number | undefined; } /** * Location in the source code. * @experimental */ interface ScriptPosition { lineNumber: number; columnNumber: number; } /** * JavaScript call frame. Array of call frames form the call stack. */ interface CallFrame { /** * Call frame identifier. This identifier is only valid while the virtual machine is paused. */ callFrameId: CallFrameId; /** * Name of the JavaScript function called on this call frame. */ functionName: string; /** * Location in the source code. */ functionLocation?: Location | undefined; /** * Location in the source code. */ location: Location; /** * JavaScript script name or url. */ url: string; /** * Scope chain for this call frame. */ scopeChain: Scope[]; /** * <code>this</code> object for this call frame. */ this: Runtime.RemoteObject; /** * The value being returned, if the function is at return point. */ returnValue?: Runtime.RemoteObject | undefined; } /** * Scope description. */ interface Scope { /** * Scope type. */ type: string; /** * Object representing the scope. For <code>global</code> and <code>with</code> scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. */ object: Runtime.RemoteObject; name?: string | undefined; /** * Location in the source code where scope starts */ startLocation?: Location | undefined; /** * Location in the source code where scope en
ds */ endLocation?: Location | undefined; } /** * Search match for resource. */ interface SearchMatch { /** * Line number in resource content. */ lineNumber: number; /** * Line with match content. */ lineContent: string; } interface BreakLocation { /** * Script identifier as reported in the <code>Debugger.scriptParsed</code>. */ scriptId: Runtime.ScriptId; /** * Line number in the script (0-based). */ lineNumber: number; /** * Column number in the script (0-based). */ columnNumber?: number | undefined; type?: string | undefined; } interface SetBreakpointsActiveParameterType { /** * New value for breakpoints active state. */ active: boolean; } interface SetSkipAllPausesParameterType { /** * New value for skip pauses state. */ skip: boolean; } interface SetBreakpointByUrlParameterType { /** * Line number to set breakpoint at. */ lineNumber: number; /** * URL of the resources to set breakpoint on. */ url?: string | undefined; /** * Regex pattern for the URLs of the resources to set breakpoints on. Either <code>url</code> or <code>urlRegex</code> must be specified. */ urlRegex?: string | undefined; /** * Script hash of the resources to set breakpoint on. */ scriptHash?: string | undefined; /** * Offset in the line to set breakpoint at. */ columnNumber?: number | undefined; /** * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. */ condition?: string | undefined; } interface SetBreakpointParameterType { /** * Location to set breakpoint in. */ location: Location; /** * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. */ condition?: string | undefined; } interface RemoveBreakpointParameterType { breakpointId: BreakpointId; } interface GetPossibleBreakpointsParameterType { /** * Start of range to search possible breakpoint locations in. */ start: Location; /** * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. */ end?: Location | undefined; /** * Only consider locations which are in the same (non-nested) function as start. */ restrictToFunction?: boolean | undefined; } interface ContinueToLocationParameterType { /** * Location to continue to. */ location: Location; targetCallFrames?: string | undefined; } interface PauseOnAsyncCallParameterType { /** * Debugger will pause when async call with given stack trace is started. */ parentStackTraceId: Runtime.StackTraceId; } interface StepIntoParameterType { /** * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause
. * @experimental */ breakOnAsyncCall?: boolean | undefined; } interface GetStackTraceParameterType { stackTraceId: Runtime.StackTraceId; } interface SearchInContentParameterType { /** * Id of the script to search in. */ scriptId: Runtime.ScriptId; /** * String to search for. */ query: string; /** * If true, search is case sensitive. */ caseSensitive?: boolean | undefined; /** * If true, treats string parameter as regex. */ isRegex?: boolean | undefined; } interface SetScriptSourceParameterType { /** * Id of the script to edit. */ scriptId: Runtime.ScriptId; /** * New content of the script. */ scriptSource: string; /** * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. */ dryRun?: boolean | undefined; } interface RestartFrameParameterType { /** * Call frame identifier to evaluate on. */ callFrameId: CallFrameId; } interface GetScriptSourceParameterType { /** * Id of the script to get source for. */ scriptId: Runtime.ScriptId; } interface SetPauseOnExceptionsParameterType { /** * Pause on exceptions mode. */ state: string; } interface EvaluateOnCallFrameParameterType { /** * Call frame identifier to evaluate on. */ callFrameId: CallFrameId; /** * Expression to evaluate. */ expression: string; /** * String object group name to put result into (allows rapid releasing resulting object handles using <code>releaseObjectGroup</code>). */ objectGroup?: string | undefined; /** * Specifies whether command line API should be available to the evaluated expression, defaults to false. */ includeCommandLineAPI?: boolean | undefined; /** * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. */ silent?: boolean | undefined; /** * Whether the result is expected to be a JSON object that should be sent by value. */ returnByValue?: boolean | undefined; /** * Whether preview should be generated for the result. * @experimental */ generatePreview?: boolean | undefined; /** * Whether to throw an exception if side effect cannot be ruled out during evaluation. */ throwOnSideEffect?: boolean | undefined; } interface SetVariableValueParameterType { /** * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. */ scopeNumber: number; /** * Variable name. */ variableName: string; /** * New variable value. */ newValue: Runtime.CallArgument; /** * Id of callframe that holds variable. */ callFrameId: CallFrameId; } interface SetReturnValueParameterType { /** * New return value.
*/ newValue: Runtime.CallArgument; } interface SetAsyncCallStackDepthParameterType { /** * Maximum depth of async call stacks. Setting to <code>0</code> will effectively disable collecting async call stacks (default). */ maxDepth: number; } interface SetBlackboxPatternsParameterType { /** * Array of regexps that will be used to check script url for blackbox state. */ patterns: string[]; } interface SetBlackboxedRangesParameterType { /** * Id of the script. */ scriptId: Runtime.ScriptId; positions: ScriptPosition[]; } interface EnableReturnType { /** * Unique identifier of the debugger. * @experimental */ debuggerId: Runtime.UniqueDebuggerId; } interface SetBreakpointByUrlReturnType { /** * Id of the created breakpoint for further reference. */ breakpointId: BreakpointId; /** * List of the locations this breakpoint resolved into upon addition. */ locations: Location[]; } interface SetBreakpointReturnType { /** * Id of the created breakpoint for further reference. */ breakpointId: BreakpointId; /** * Location this breakpoint resolved into. */ actualLocation: Location; } interface GetPossibleBreakpointsReturnType { /** * List of the possible breakpoint locations. */ locations: BreakLocation[]; } interface GetStackTraceReturnType { stackTrace: Runtime.StackTrace; } interface SearchInContentReturnType { /** * List of search matches. */ result: SearchMatch[]; } interface SetScriptSourceReturnType { /** * New stack trace in case editing has happened while VM was stopped. */ callFrames?: CallFrame[] | undefined; /** * Whether current call stack was modified after applying the changes. */ stackChanged?: boolean | undefined; /** * Async stack trace, if any. */ asyncStackTrace?: Runtime.StackTrace | undefined; /** * Async stack trace, if any. * @experimental */ asyncStackTraceId?: Runtime.StackTraceId | undefined; /** * Exception details if any. */ exceptionDetails?: Runtime.ExceptionDetails | undefined; } interface RestartFrameReturnType { /** * New stack trace. */ callFrames: CallFrame[]; /** * Async stack trace, if any. */ asyncStackTrace?: Runtime.StackTrace | undefined; /** * Async stack trace, if any. * @experimental */ asyncStackTraceId?: Runtime.StackTraceId | undefined; } interface GetScriptSourceReturnType { /** * Script source. */ scriptSource: string; } interface EvaluateOnCallFrameReturnType { /** * Object wrapper for the evaluation result. */ result: Runtime.RemoteObject; /** * Exception details. */ exceptionDetails?: Runtime.ExceptionDetails | undefined; } interface ScriptParsedEventDataType { /** * Identifier of the script parsed. */ sc
riptId: Runtime.ScriptId; /** * URL or name of the script parsed (if any). */ url: string; /** * Line offset of the script within the resource with given URL (for script tags). */ startLine: number; /** * Column offset of the script within the resource with given URL. */ startColumn: number; /** * Last line of the script. */ endLine: number; /** * Length of the last line of the script. */ endColumn: number; /** * Specifies script creation context. */ executionContextId: Runtime.ExecutionContextId; /** * Content hash of the script. */ hash: string; /** * Embedder-specific auxiliary data. */ executionContextAuxData?: {} | undefined; /** * True, if this script is generated as a result of the live edit operation. * @experimental */ isLiveEdit?: boolean | undefined; /** * URL of source map associated with script (if any). */ sourceMapURL?: string | undefined; /** * True, if this script has sourceURL. */ hasSourceURL?: boolean | undefined; /** * True, if this script is ES6 module. */ isModule?: boolean | undefined; /** * This script length. */ length?: number | undefined; /** * JavaScript top stack frame of where the script parsed event was triggered if available. * @experimental */ stackTrace?: Runtime.StackTrace | undefined; } interface ScriptFailedToParseEventDataType { /** * Identifier of the script parsed. */ scriptId: Runtime.ScriptId; /** * URL or name of the script parsed (if any). */ url: string; /** * Line offset of the script within the resource with given URL (for script tags). */ startLine: number; /** * Column offset of the script within the resource with given URL. */ startColumn: number; /** * Last line of the script. */ endLine: number; /** * Length of the last line of the script. */ endColumn: number; /** * Specifies script creation context. */ executionContextId: Runtime.ExecutionContextId; /** * Content hash of the script. */ hash: string; /** * Embedder-specific auxiliary data. */ executionContextAuxData?: {} | undefined; /** * URL of source map associated with script (if any). */ sourceMapURL?: string | undefined; /** * True, if this script has sourceURL. */ hasSourceURL?: boolean | undefined; /** * True, if this script is ES6 module. */ isModule?: boolean | undefined; /** * This script length. */ length?: number | undefined; /** * JavaScript top stack frame of where the script parsed event was triggered if available. * @experimental */ stackTrace?: Runtime.StackTrace | undefined; } interface BreakpointResolvedEventDataType { /** * Breakpoint u
nique identifier. */ breakpointId: BreakpointId; /** * Actual breakpoint location. */ location: Location; } interface PausedEventDataType { /** * Call stack the virtual machine stopped on. */ callFrames: CallFrame[]; /** * Pause reason. */ reason: string; /** * Object containing break-specific auxiliary properties. */ data?: {} | undefined; /** * Hit breakpoints IDs */ hitBreakpoints?: string[] | undefined; /** * Async stack trace, if any. */ asyncStackTrace?: Runtime.StackTrace | undefined; /** * Async stack trace, if any. * @experimental */ asyncStackTraceId?: Runtime.StackTraceId | undefined; /** * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after <code>Debugger.stepInto</code> call with <code>breakOnAsynCall</code> flag. * @experimental */ asyncCallStackTraceId?: Runtime.StackTraceId | undefined; } } namespace Console { /** * Console message. */ interface ConsoleMessage { /** * Message source. */ source: string; /** * Message severity. */ level: string; /** * Message text. */ text: string; /** * URL of the message origin. */ url?: string | undefined; /** * Line number in the resource that generated this message (1-based). */ line?: number | undefined; /** * Column number in the resource that generated this message (1-based). */ column?: number | undefined; } interface MessageAddedEventDataType { /** * Console message that has been added. */ message: ConsoleMessage; } } namespace Profiler { /** * Profile node. Holds callsite information, execution statistics and child nodes. */ interface ProfileNode { /** * Unique id of the node. */ id: number; /** * Function location. */ callFrame: Runtime.CallFrame; /** * Number of samples where this node was on top of the call stack. */ hitCount?: number | undefined; /** * Child node ids. */ children?: number[] | undefined; /** * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. */ deoptReason?: string | undefined; /** * An array of source position ticks. */ positionTicks?: PositionTickInfo[] | undefined; } /** * Profile. */ interface Profile { /** * The list of profile nodes. First item is the root node. */ nodes: ProfileNode[]; /** * Profiling start timestamp in microseconds. */ startTime: number; /** * Profiling end timestamp in microseconds. */ endTime: number; /** * Ids of samples top nodes. */ samples?: number[] | undefined; /** * Time intervals between adjacent samples in microseconds. Th
e first delta is relative to the profile startTime. */ timeDeltas?: number[] | undefined; } /** * Specifies a number of samples attributed to a certain source position. */ interface PositionTickInfo { /** * Source line number (1-based). */ line: number; /** * Number of samples attributed to the source line. */ ticks: number; } /** * Coverage data for a source range. */ interface CoverageRange { /** * JavaScript script source offset for the range start. */ startOffset: number; /** * JavaScript script source offset for the range end. */ endOffset: number; /** * Collected execution count of the source range. */ count: number; } /** * Coverage data for a JavaScript function. */ interface FunctionCoverage { /** * JavaScript function name. */ functionName: string; /** * Source ranges inside the function with coverage data. */ ranges: CoverageRange[]; /** * Whether coverage data for this function has block granularity. */ isBlockCoverage: boolean; } /** * Coverage data for a JavaScript script. */ interface ScriptCoverage { /** * JavaScript script id. */ scriptId: Runtime.ScriptId; /** * JavaScript script name or url. */ url: string; /** * Functions contained in the script that has coverage data. */ functions: FunctionCoverage[]; } /** * Describes a type collected during runtime. * @experimental */ interface TypeObject { /** * Name of a type collected with type profiling. */ name: string; } /** * Source offset and types for a parameter or return value. * @experimental */ interface TypeProfileEntry { /** * Source offset of the parameter or end of function for return values. */ offset: number; /** * The types for this parameter or return value. */ types: TypeObject[]; } /** * Type profile data collected during runtime for a JavaScript script. * @experimental */ interface ScriptTypeProfile { /** * JavaScript script id. */ scriptId: Runtime.ScriptId; /** * JavaScript script name or url. */ url: string; /** * Type profile entries for parameters and return values of the functions in the script. */ entries: TypeProfileEntry[]; } interface SetSamplingIntervalParameterType { /** * New sampling interval in microseconds. */ interval: number; } interface StartPreciseCoverageParameterType { /** * Collect accurate call counts beyond simple 'covered' or 'not covered'. */ callCount?: boolean | undefined; /** * Collect block-based coverage. */ detailed?: boolean | undefined; } interface StopReturnType { /** * Recorded profile. */ profile: Profile; } interface TakePreciseCoverageReturnType { /**
* Coverage data for the current isolate. */ result: ScriptCoverage[]; } interface GetBestEffortCoverageReturnType { /** * Coverage data for the current isolate. */ result: ScriptCoverage[]; } interface TakeTypeProfileReturnType { /** * Type profile for all scripts since startTypeProfile() was turned on. */ result: ScriptTypeProfile[]; } interface ConsoleProfileStartedEventDataType { id: string; /** * Location of console.profile(). */ location: Debugger.Location; /** * Profile title passed as an argument to console.profile(). */ title?: string | undefined; } interface ConsoleProfileFinishedEventDataType { id: string; /** * Location of console.profileEnd(). */ location: Debugger.Location; profile: Profile; /** * Profile title passed as an argument to console.profile(). */ title?: string | undefined; } } namespace HeapProfiler { /** * Heap snapshot object id. */ type HeapSnapshotObjectId = string; /** * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. */ interface SamplingHeapProfileNode { /** * Function location. */ callFrame: Runtime.CallFrame; /** * Allocations size in bytes for the node excluding children. */ selfSize: number; /** * Child nodes. */ children: SamplingHeapProfileNode[]; } /** * Profile. */ interface SamplingHeapProfile { head: SamplingHeapProfileNode; } interface StartTrackingHeapObjectsParameterType { trackAllocations?: boolean | undefined; } interface StopTrackingHeapObjectsParameterType { /** * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. */ reportProgress?: boolean | undefined; } interface TakeHeapSnapshotParameterType { /** * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. */ reportProgress?: boolean | undefined; } interface GetObjectByHeapObjectIdParameterType { objectId: HeapSnapshotObjectId; /** * Symbolic group name that can be used to release multiple objects. */ objectGroup?: string | undefined; } interface AddInspectedHeapObjectParameterType { /** * Heap snapshot object id to be accessible by means of $x command line API. */ heapObjectId: HeapSnapshotObjectId; } interface GetHeapObjectIdParameterType { /** * Identifier of the object to get heap object id for. */ objectId: Runtime.RemoteObjectId; } interface StartSamplingParameterType { /** * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. */ samplingInterval?: number | undefined; } interface GetObjectByHeapObjectIdReturnType { /** * Evaluation result. */ result: Runtime.RemoteObject; } interface GetHeapObjectIdReturnType { /** * Id of the heap snapshot object corresponding to the passed
remote object id. */ heapSnapshotObjectId: HeapSnapshotObjectId; } interface StopSamplingReturnType { /** * Recorded sampling heap profile. */ profile: SamplingHeapProfile; } interface GetSamplingProfileReturnType { /** * Return the sampling profile being collected. */ profile: SamplingHeapProfile; } interface AddHeapSnapshotChunkEventDataType { chunk: string; } interface ReportHeapSnapshotProgressEventDataType { done: number; total: number; finished?: boolean | undefined; } interface LastSeenObjectIdEventDataType { lastSeenObjectId: number; timestamp: number; } interface HeapStatsUpdateEventDataType { /** * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. */ statsUpdate: number[]; } } namespace NodeTracing { interface TraceConfig { /** * Controls how the trace buffer stores data. */ recordMode?: string | undefined; /** * Included category filters. */ includedCategories: string[]; } interface StartParameterType { traceConfig: TraceConfig; } interface GetCategoriesReturnType { /** * A list of supported tracing categories. */ categories: string[]; } interface DataCollectedEventDataType { value: Array<{}>; } } namespace NodeWorker { type WorkerID = string; /** * Unique identifier of attached debugging session. */ type SessionID = string; interface WorkerInfo { workerId: WorkerID; type: string; title: string; url: string; } interface SendMessageToWorkerParameterType { message: string; /** * Identifier of the session. */ sessionId: SessionID; } interface EnableParameterType { /** * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` * message to run them. */ waitForDebuggerOnStart: boolean; } interface DetachParameterType { sessionId: SessionID; } interface AttachedToWorkerEventDataType { /** * Identifier assigned to the session used to send/receive messages. */ sessionId: SessionID; workerInfo: WorkerInfo; waitingForDebugger: boolean; } interface DetachedFromWorkerEventDataType { /** * Detached session identifier. */ sessionId: SessionID; } interface ReceivedMessageFromWorkerEventDataType { /** * Identifier of a session which sends a message. */ sessionId: SessionID; message: string; } } namespace NodeRuntime { interface NotifyWhenWaitingForDisconnectParameterType { enabled: boolean; } } /** * The `inspector.Session` is used for dispatching messages to the V8 inspector * back-end and receiving message responses and notifications. */ class Session extends EventEmitter { /** * Create a new instance of the inspector.Session class. * The inspector session needs to be connected through session.connect() before the m
essages can be dispatched to the inspector backend. */ constructor(); /** * Connects a session to the inspector back-end. * @since v8.0.0 */ connect(): void; /** * Immediately close the session. All pending message callbacks will be called * with an error. `session.connect()` will need to be called to be able to send * messages again. Reconnected session will lose all inspector state, such as * enabled agents or configured breakpoints. * @since v8.0.0 */ disconnect(): void; /** * Posts a message to the inspector back-end. `callback` will be notified when * a response is received. `callback` is a function that accepts two optional * arguments: error and message-specific result. * * ```js * session.post('Runtime.evaluate', { expression: '2 + 2' }, * (error, { result }) => console.log(result)); * // Output: { type: 'number', value: 4, description: '4' } * ``` * * The latest version of the V8 inspector protocol is published on the [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). * * Node.js inspector supports all the Chrome DevTools Protocol domains declared * by V8\. Chrome DevTools Protocol domain provides an interface for interacting * with one of the runtime agents used to inspect the application state and listen * to the run-time events. * * ## Example usage * * Apart from the debugger, various V8 Profilers are available through the DevTools * protocol. * @since v8.0.0 */ post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; post(method: string, callback?: (err: Error | null, params?: {}) => void): void; /** * Returns supported domains. */ post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; /** * Evaluates expression on global object. */ post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; /** * Add handler to promise with given promise object id. */ post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; /** * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. */ post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; /** * Returns properties of a given object. Object group of the result is inherited from the target object. */ post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; /** * Releases remote object with given id. */ post(method: 'Runtime.releaseObject', params?: Runtime.Relea
seObjectParameterType, callback?: (err: Error | null) => void): void; post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; /** * Releases all remote objects that belong to a given group. */ post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; /** * Tells inspected instance to run if it was waiting for debugger to attach. */ post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; /** * Enables reporting of execution contexts creation by means of <code>executionContextCreated</code> event. When the reporting gets enabled the event will be sent immediately for each existing execution context. */ post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; /** * Disables reporting of execution contexts creation. */ post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; /** * Discards collected exceptions and console API calls. */ post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; /** * @experimental */ post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; /** * Compiles expression. */ post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; /** * Runs script with given id in a given context. */ post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; /** * Returns all let, const and class variables from global scope. */ post( method: 'Runtime.globalLexicalScopeNames', params?: Runtime.GlobalLexicalScopeNamesParameterType, callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void ): void; post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; /** * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. */ post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; /** * Disables debugger for given page. */ post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; /** * Activates / deactivates all breakpoints on the page. */ post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void;
post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; /** * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). */ post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; /** * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in <code>locations</code> property. Further matching script parsing will result in subsequent <code>breakpointResolved</code> events issued. This logical breakpoint will survive page reloads. */ post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; /** * Sets JavaScript breakpoint at a given location. */ post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; /** * Removes JavaScript breakpoint. */ post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; /** * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. */ post( method: 'Debugger.getPossibleBreakpoints', params?: Debugger.GetPossibleBreakpointsParameterType, callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void ): void; post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; /** * Continues execution until specific location is reached. */ post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; /** * @experimental */ post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; /** * Steps over the statement. */ post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; /** * Steps into the function call. */ post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; /** * Steps out of the function call. */ post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; /** * Stops on the next JavaScript statement. */ post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; /** * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into
next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. * @experimental */ post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; /** * Resumes JavaScript execution. */ post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; /** * Returns stack trace with given <code>stackTraceId</code>. * @experimental */ post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; /** * Searches for given string in script content. */ post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; /** * Edits JavaScript source live. */ post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; /** * Restarts particular call frame from the beginning. */ post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; /** * Returns source for the script with given id. */ post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; /** * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is <code>none</code>. */ post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; /** * Evaluates expression on a given call frame. */ post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; /** * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. */ post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; /** * Changes return value in top frame. Available only at return break position. * @experimental */ post(method: 'Debugger.setReturnValue', par
ams?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; /** * Enables or disables async call stacks tracking. */ post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; /** * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. * @experimental */ post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; /** * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. * @experimental */ post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; /** * Enables console domain, sends the messages collected so far to the client by means of the <code>messageAdded</code> notification. */ post(method: 'Console.enable', callback?: (err: Error | null) => void): void; /** * Disables console domain, prevents further console messages from being reported to the client. */ post(method: 'Console.disable', callback?: (err: Error | null) => void): void; /** * Does nothing. */ post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; /** * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. */ post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; /** * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. */ post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; /** * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. */ post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; /** * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started.
*/ post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; /** * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. */ post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; /** * Enable type profile. * @experimental */ post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; /** * Disable type profile. Disabling releases type profile data collected so far. * @experimental */ post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; /** * Collect type profile. * @experimental */ post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; post( method: 'HeapProfiler.getObjectByHeapObjectId', params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void ): void; post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; /** * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). */ post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; /** * Gets supported tracing categories. */
post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; /** * Start trace events collection. */ post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; /** * Stop trace events collection. Remaining collected events will be sent as a sequence of * dataCollected events followed by tracingComplete event. */ post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; /** * Sends protocol message over session with given id. */ post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; /** * Instructs the inspector to attach to running workers. Will also attach to new workers * as they start */ post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; /** * Detaches from all running workers and disables attaching to new workers as they are started. */ post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; /** * Detached from the worker with given sessionId. */ post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; /** * Enable the `NodeRuntime.waitingForDisconnect`. */ post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; // Events addListener(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. */ addListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; /** * Issued when new execution context is created. */ addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; /** * Issued when execution context is destroyed. */ addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; /** * Issued when all executionContexts were cleared in browser */ addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; /** * Issued when exception was thrown and unhandled. */ addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; /** * Issued when unhandled exception was revoked. */ addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; /** * Issued when console API was called. */ addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; /**
* Issued when object should be inspected (for example, as a result of inspect() command line API call). */ addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; /** * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. */ addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; /** * Fired when virtual machine fails to parse the script. */ addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; /** * Fired when breakpoint is resolved to an actual script and location. */ addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; /** * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. */ addListener(event: 'Debugger.paused', listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; /** * Fired when the virtual machine resumed execution. */ addListener(event: 'Debugger.resumed', listener: () => void): this; /** * Issued when new console message is added. */ addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; /** * Sent when new profile recording is started using console.profile() call. */ addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; /** * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. */ addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; /** * If heap objects tracking has been started then backend may send update for one or more fragments */ addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; /** * Contains an bucket of collected trace events. */ addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; /** * Signals that tracing is stopped and there is no trace buffers pending flush, all data were * delivered via dataCollected events. */ addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; /** * Issued when attached to a worker. */ addListener(event: 'NodeWorker.a
ttachedToWorker', listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; /** * Issued when detached from the worker. */ addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; /** * Notifies about a new protocol message received from the session * (session ID is provided in attachedToWorker notification). */ addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; /** * This event is fired instead of `Runtime.executionContextDestroyed` when * enabled. * It is fired when the Node process finished all code execution and is * waiting for all frontends to disconnect. */ addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: 'inspectorNotification', message: InspectorNotification<{}>): boolean; emit(event: 'Runtime.executionContextCreated', message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>): boolean; emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>): boolean; emit(event: 'Runtime.executionContextsCleared'): boolean; emit(event: 'Runtime.exceptionThrown', message: InspectorNotification<Runtime.ExceptionThrownEventDataType>): boolean; emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>): boolean; emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>): boolean; emit(event: 'Runtime.inspectRequested', message: InspectorNotification<Runtime.InspectRequestedEventDataType>): boolean; emit(event: 'Debugger.scriptParsed', message: InspectorNotification<Debugger.ScriptParsedEventDataType>): boolean; emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>): boolean; emit(event: 'Debugger.breakpointResolved', message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>): boolean; emit(event: 'Debugger.paused', message: InspectorNotification<Debugger.PausedEventDataType>): boolean; emit(event: 'Debugger.resumed'): boolean; emit(event: 'Console.messageAdded', message: InspectorNotification<Console.MessageAddedEventDataType>): boolean; emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>): boolean; emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>): boolean; emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>): boolean; emit(event: 'HeapProfiler.resetProfiles'): boolean; emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>): boolean; emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>): boolean; emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>): boolean; emit(event: 'NodeTracing.dataCollected', message: InspectorNotification<NodeTracing.DataCollectedEventDataType>): boolean; emit(event: 'NodeTracing.tracingComplete'): boolean; emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>): boo
lean; emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>): boolean; emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>): boolean; emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; on(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. */ on(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; /** * Issued when new execution context is created. */ on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; /** * Issued when execution context is destroyed. */ on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; /** * Issued when all executionContexts were cleared in browser */ on(event: 'Runtime.executionContextsCleared', listener: () => void): this; /** * Issued when exception was thrown and unhandled. */ on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; /** * Issued when unhandled exception was revoked. */ on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; /** * Issued when console API was called. */ on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; /** * Issued when object should be inspected (for example, as a result of inspect() command line API call). */ on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; /** * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. */ on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; /** * Fired when virtual machine fails to parse the script. */ on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; /** * Fired when breakpoint is resolved to an actual script and location. */ on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; /** * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. */ on(event: 'Debugger.paused', listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; /** * Fired when the virtual machine resumed execution. */ on(event: 'Debugger.resumed', listener: () => void): this; /** * Issued when new console message is added. */ on(event: 'Console.messageAdded', listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; /** * Sent when new profile recording is started using console.profile() call. */ on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; on(event: 'Profiler.consoleProfileFinished', listener: (message: Inspect
orNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; /** * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. */ on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; /** * If heap objects tracking has been started then backend may send update for one or more fragments */ on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; /** * Contains an bucket of collected trace events. */ on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; /** * Signals that tracing is stopped and there is no trace buffers pending flush, all data were * delivered via dataCollected events. */ on(event: 'NodeTracing.tracingComplete', listener: () => void): this; /** * Issued when attached to a worker. */ on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; /** * Issued when detached from the worker. */ on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; /** * Notifies about a new protocol message received from the session * (session ID is provided in attachedToWorker notification). */ on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; /** * This event is fired instead of `Runtime.executionContextDestroyed` when * enabled. * It is fired when the Node process finished all code execution and is * waiting for all frontends to disconnect. */ on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. */ once(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; /** * Issued when new execution context is created. */ once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; /** * Issued when execution context is destroyed. */ once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; /** * Issued when all executionContexts were cleared in browser */ once(event: 'Runtime.executionContextsCleared', listener: () => void): this; /** * Issued when exception was thrown and unhandled. */ once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) =>
void): this; /** * Issued when unhandled exception was revoked. */ once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; /** * Issued when console API was called. */ once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; /** * Issued when object should be inspected (for example, as a result of inspect() command line API call). */ once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; /** * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. */ once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; /** * Fired when virtual machine fails to parse the script. */ once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; /** * Fired when breakpoint is resolved to an actual script and location. */ once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; /** * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. */ once(event: 'Debugger.paused', listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; /** * Fired when the virtual machine resumed execution. */ once(event: 'Debugger.resumed', listener: () => void): this; /** * Issued when new console message is added. */ once(event: 'Console.messageAdded', listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; /** * Sent when new profile recording is started using console.profile() call. */ once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; /** * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. */ once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; /** * If heap objects tracking has been started then backend may send update for one or more fragments */ once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; /** * Contains an bucket of collected trace events. */ once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this;
/** * Signals that tracing is stopped and there is no trace buffers pending flush, all data were * delivered via dataCollected events. */ once(event: 'NodeTracing.tracingComplete', listener: () => void): this; /** * Issued when attached to a worker. */ once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; /** * Issued when detached from the worker. */ once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; /** * Notifies about a new protocol message received from the session * (session ID is provided in attachedToWorker notification). */ once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; /** * This event is fired instead of `Runtime.executionContextDestroyed` when * enabled. * It is fired when the Node process finished all code execution and is * waiting for all frontends to disconnect. */ once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. */ prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; /** * Issued when new execution context is created. */ prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; /** * Issued when execution context is destroyed. */ prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; /** * Issued when all executionContexts were cleared in browser */ prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; /** * Issued when exception was thrown and unhandled. */ prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; /** * Issued when unhandled exception was revoked. */ prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; /** * Issued when console API was called. */ prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; /** * Issued when object should be inspected (for example, as a result of inspect() command line API call). */ prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; /** * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. */ prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; /** * Fired when virtual machine fails to parse the script. */ prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; /** * Fired when breakpoint is resolv
ed to an actual script and location. */ prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; /** * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. */ prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; /** * Fired when the virtual machine resumed execution. */ prependListener(event: 'Debugger.resumed', listener: () => void): this; /** * Issued when new console message is added. */ prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; /** * Sent when new profile recording is started using console.profile() call. */ prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; /** * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. */ prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; /** * If heap objects tracking has been started then backend may send update for one or more fragments */ prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; /** * Contains an bucket of collected trace events. */ prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; /** * Signals that tracing is stopped and there is no trace buffers pending flush, all data were * delivered via dataCollected events. */ prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; /** * Issued when attached to a worker. */ prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; /** * Issued when detached from the worker. */ prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; /** * Notifies about a new protocol message received from the session * (session ID is provided in attachedToWorker notification). */ prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; /** * This event is fired instead of `Runtime.executionContextDestroyed` when * enabled. *
It is fired when the Node process finished all code execution and is * waiting for all frontends to disconnect. */ prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. */ prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; /** * Issued when new execution context is created. */ prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; /** * Issued when execution context is destroyed. */ prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; /** * Issued when all executionContexts were cleared in browser */ prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; /** * Issued when exception was thrown and unhandled. */ prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; /** * Issued when unhandled exception was revoked. */ prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; /** * Issued when console API was called. */ prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; /** * Issued when object should be inspected (for example, as a result of inspect() command line API call). */ prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; /** * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. */ prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; /** * Fired when virtual machine fails to parse the script. */ prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; /** * Fired when breakpoint is resolved to an actual script and location. */ prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; /** * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. */ prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; /** * Fired when the virtual machine resumed execution. */ prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; /** * Issued when new console message is added. */ prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; /** * Sent when new profile recording is started using console.profile() call. */ prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification<Prof
iler.ConsoleProfileStartedEventDataType>) => void): this; prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; /** * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. */ prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; /** * If heap objects tracking has been started then backend may send update for one or more fragments */ prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; /** * Contains an bucket of collected trace events. */ prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; /** * Signals that tracing is stopped and there is no trace buffers pending flush, all data were * delivered via dataCollected events. */ prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; /** * Issued when attached to a worker. */ prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; /** * Issued when detached from the worker. */ prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; /** * Notifies about a new protocol message received from the session * (session ID is provided in attachedToWorker notification). */ prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; /** * This event is fired instead of `Runtime.executionContextDestroyed` when * enabled. * It is fired when the Node process finished all code execution and is * waiting for all frontends to disconnect. */ prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; } /** * Activate inspector on host and port. Equivalent to`node --inspect=[[host:]port]`, but can be done programmatically after node has * started. * * If wait is `true`, will block until a client has connected to the inspect port * and flow control has been passed to the debugger client. * * See the `security warning` regarding the `host`parameter usage. * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. * @param [wait=false] Block until a client has connected. Optional. * @returns Disposable that calls `inspector.close()`. */ function open(port?: number, host?: string, wait?:
boolean): Disposable; /** * Deactivate the inspector. Blocks until there are no active connections. */ function close(): void; /** * Return the URL of the active inspector, or `undefined` if there is none. * * ```console * $ node --inspect -p 'inspector.url()' * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 * For help, see: https://nodejs.org/en/docs/inspector * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 * * $ node --inspect=localhost:3000 -p 'inspector.url()' * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a * For help, see: https://nodejs.org/en/docs/inspector * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a * * $ node -p 'inspector.url()' * undefined * ``` */ function url(): string | undefined; /** * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. * * An exception will be thrown if there is no active inspector. * @since v12.7.0 */ function waitForDebugger(): void; } /** * The inspector module provides an API for interacting with the V8 inspector. */ declare module 'node:inspector' { import inspector = require('inspector'); export = inspector; }
/** * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for * Node.js-specific performance measurements. * * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): * * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) * * [Performance Timeline](https://w3c.github.io/performance-timeline/) * * [User Timing](https://www.w3.org/TR/user-timing/) * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) * * ```js * const { PerformanceObserver, performance } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((items) => { * console.log(items.getEntries()[0].duration); * performance.clearMarks(); * }); * obs.observe({ type: 'measure' }); * performance.measure('Start to Now'); * * performance.mark('A'); * doSomeLongRunningProcess(() => { * performance.measure('A to Now', 'A'); * * performance.mark('B'); * performance.measure('A to B', 'A', 'B'); * }); * ``` * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/perf_hooks.js) */ declare module "perf_hooks" { import { AsyncResource } from "node:async_hooks"; type EntryType = "node" | "mark" | "measure" | "gc" | "function" | "http2" | "http" | "dns" | "net"; interface NodeGCPerformanceDetail { /** * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies * the type of garbage collection operation that occurred. * See perf_hooks.constants for valid values. */ readonly kind?: number | undefined; /** * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` * property contains additional information about garbage collection operation. * See perf_hooks.constants for valid values. */ readonly flags?: number | undefined; } /** * The constructor of this class is not exposed to users directly. * @since v8.5.0 */ class PerformanceEntry { protected constructor(); /** * The total number of milliseconds elapsed for this entry. This value will not * be meaningful for all Performance Entry types. * @since v8.5.0 */ readonly duration: number; /** * The name of the performance entry. * @since v8.5.0 */ readonly name: string; /** * The high resolution millisecond timestamp marking the starting time of the * Performance Entry. * @since v8.5.0 */ readonly startTime: number; /** * The type of the performance entry. It may be one of: * * * `'node'` (Node.js only) * * `'mark'` (available on the Web) * * `'measure'` (available on the Web) * * `'gc'` (Node.js only) * * `'function'` (Node.js only) * * `'http2'` (Node.js only) * * `'http'` (Node.js only) * @since v8.5.0 */ readonly entryType: EntryType; /** * Additional detail specific to the `entryType`. * @since v16.0.0 */ readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. toJSON(): any; } /** * Exposes marks created via the `Performance.mark()` method. * @since v18.2.0, v16.17.0 */ class PerformanceMark extends PerformanceEntry { readonly duration: 0; readonly entryType: "mark"; } /** * Exposes measures created via the `Performance.measure()` method. * * The constructor of this class is not exposed to users directly. * @since v18.2.0, v16.17.0 */ class PerformanceMeasure extends PerformanceEntry { readonly entryType: "measure"; } /** * _This property is an extension b
y Node.js. It is not available in Web browsers._ * * Provides timing details for Node.js itself. The constructor of this class * is not exposed to users. * @since v8.5.0 */ class PerformanceNodeTiming extends PerformanceEntry { /** * The high resolution millisecond timestamp at which the Node.js process * completed bootstrapping. If bootstrapping has not yet finished, the property * has the value of -1. * @since v8.5.0 */ readonly bootstrapComplete: number; /** * The high resolution millisecond timestamp at which the Node.js environment was * initialized. * @since v8.5.0 */ readonly environment: number; /** * The high resolution millisecond timestamp of the amount of time the event loop * has been idle within the event loop's event provider (e.g. `epoll_wait`). This * does not take CPU usage into consideration. If the event loop has not yet * started (e.g., in the first tick of the main script), the property has the * value of 0. * @since v14.10.0, v12.19.0 */ readonly idleTime: number; /** * The high resolution millisecond timestamp at which the Node.js event loop * exited. If the event loop has not yet exited, the property has the value of -1\. * It can only have a value of not -1 in a handler of the `'exit'` event. * @since v8.5.0 */ readonly loopExit: number; /** * The high resolution millisecond timestamp at which the Node.js event loop * started. If the event loop has not yet started (e.g., in the first tick of the * main script), the property has the value of -1. * @since v8.5.0 */ readonly loopStart: number; /** * The high resolution millisecond timestamp at which the V8 platform was * initialized. * @since v8.5.0 */ readonly v8Start: number; } interface EventLoopUtilization { idle: number; active: number; utilization: number; } /** * @param util1 The result of a previous call to eventLoopUtilization() * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 */ type EventLoopUtilityFunction = ( util1?: EventLoopUtilization, util2?: EventLoopUtilization, ) => EventLoopUtilization; interface MarkOptions { /** * Additional optional detail to include with the mark. */ detail?: unknown | undefined; /** * An optional timestamp to be used as the mark time. * @default `performance.now()`. */ startTime?: number | undefined; } interface MeasureOptions { /** * Additional optional detail to include with the mark. */ detail?: unknown | undefined; /** * Duration between start and end times. */ duration?: number | undefined; /** * Timestamp to be used as the end time, or a string identifying a previously recorded mark. */ end?: number | string | undefined; /** * Timestamp to be used as the start time, or a string identifying a previously recorded mark. */ start?: number | string | undefined; } interface TimerifyOptions { /** * A histogram object created using * `perf_hooks.createHistogram()` that will record runtime durations in * nanoseconds. */ histogram?: RecordableHistogram | undefined; } interface Performance { /** * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. * If name is provided, removes only the named mark. * @param name */ clearMarks(name?: stri
ng): void; /** * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. * If name is provided, removes only the named measure. * @param name * @since v16.7.0 */ clearMeasures(name?: string): void; /** * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. * If you are only interested in performance entries of certain types or that have certain names, see * `performance.getEntriesByType()` and `performance.getEntriesByName()`. * @since v16.7.0 */ getEntries(): PerformanceEntry[]; /** * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. * @param name * @param type * @since v16.7.0 */ getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; /** * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` * whose `performanceEntry.entryType` is equal to `type`. * @param type * @since v16.7.0 */ getEntriesByType(type: EntryType): PerformanceEntry[]; /** * Creates a new PerformanceMark entry in the Performance Timeline. * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', * and whose performanceEntry.duration is always 0. * Performance marks are used to mark specific significant moments in the Performance Timeline. * @param name * @return The PerformanceMark entry that was created */ mark(name?: string, options?: MarkOptions): PerformanceMark; /** * Creates a new PerformanceMeasure entry in the Performance Timeline. * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. * * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, * then startMark is set to timeOrigin by default. * * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. * @param name * @param startMark * @param endMark * @return The PerformanceMeasure entry that was created */ measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; measure(name: string, options: MeasureOptions): PerformanceMeasure; /** * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. */ readonly nodeTiming: PerformanceNodeTiming; /** * @return the current high resolution millisecond timestamp */ now(): number; /** * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. */ readonly timeOrigin: number; /** * Wraps a function within a new function that measures the running time of the wrapped function. * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be
accessed. * @param fn */ timerify<T extends (...params: any[]) => any>(fn: T, options?: TimerifyOptions): T; /** * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). * No other CPU idle time is taken into consideration. */ eventLoopUtilization: EventLoopUtilityFunction; } interface PerformanceObserverEntryList { /** * Returns a list of `PerformanceEntry` objects in chronological order * with respect to `performanceEntry.startTime`. * * ```js * const { * performance, * PerformanceObserver, * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntries()); * * * [ * * PerformanceEntry { * * name: 'test', * * entryType: 'mark', * * startTime: 81.465639, * * duration: 0, * * detail: null * * }, * * PerformanceEntry { * * name: 'meow', * * entryType: 'mark', * * startTime: 81.860064, * * duration: 0, * * detail: null * * } * * ] * * performance.clearMarks(); * performance.clearMeasures(); * observer.disconnect(); * }); * obs.observe({ type: 'mark' }); * * performance.mark('test'); * performance.mark('meow'); * ``` * @since v8.5.0 */ getEntries(): PerformanceEntry[]; /** * Returns a list of `PerformanceEntry` objects in chronological order * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. * * ```js * const { * performance, * PerformanceObserver, * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntriesByName('meow')); * * * [ * * PerformanceEntry { * * name: 'meow', * * entryType: 'mark', * * startTime: 98.545991, * * duration: 0, * * detail: null * * } * * ] * * console.log(perfObserverList.getEntriesByName('nope')); // [] * * console.log(perfObserverList.getEntriesByName('test', 'mark')); * * * [ * * PerformanceEntry { * * name: 'test', * * entryType: 'mark', * * startTime: 63.518931, * * duration: 0, * * detail: null * * } * * ] * * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] * * performance.clearMarks(); * performance.clearMeasures(); * observer.disconnect(); * }); * obs.observe({ entryTypes: ['mark', 'measure'] }); * * performance.mark('test'); * performance.mark('meow'); * ``` * @since v8.5.0 */ getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; /** * Returns a list of `PerformanceEntry` objects in chronological order * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. * * ``
`js * const { * performance, * PerformanceObserver, * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((perfObserverList, observer) => { * console.log(perfObserverList.getEntriesByType('mark')); * * * [ * * PerformanceEntry { * * name: 'test', * * entryType: 'mark', * * startTime: 55.897834, * * duration: 0, * * detail: null * * }, * * PerformanceEntry { * * name: 'meow', * * entryType: 'mark', * * startTime: 56.350146, * * duration: 0, * * detail: null * * } * * ] * * performance.clearMarks(); * performance.clearMeasures(); * observer.disconnect(); * }); * obs.observe({ type: 'mark' }); * * performance.mark('test'); * performance.mark('meow'); * ``` * @since v8.5.0 */ getEntriesByType(type: EntryType): PerformanceEntry[]; } type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; /** * @since v8.5.0 */ class PerformanceObserver extends AsyncResource { constructor(callback: PerformanceObserverCallback); /** * Disconnects the `PerformanceObserver` instance from all notifications. * @since v8.5.0 */ disconnect(): void; /** * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`: * * ```js * const { * performance, * PerformanceObserver, * } = require('node:perf_hooks'); * * const obs = new PerformanceObserver((list, observer) => { * // Called once asynchronously. `list` contains three items. * }); * obs.observe({ type: 'mark' }); * * for (let n = 0; n < 3; n++) * performance.mark(`test${n}`); * ``` * @since v8.5.0 */ observe( options: | { entryTypes: readonly EntryType[]; buffered?: boolean | undefined; } | { type: EntryType; buffered?: boolean | undefined; }, ): void; } namespace constants { const NODE_PERFORMANCE_GC_MAJOR: number; const NODE_PERFORMANCE_GC_MINOR: number; const NODE_PERFORMANCE_GC_INCREMENTAL: number; const NODE_PERFORMANCE_GC_WEAKCB: number; const NODE_PERFORMANCE_GC_FLAGS_NO: number; const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; } const performance: Performance; interface EventLoopMonitorOptions { /** * The sampling rate in milliseconds. * Must be greater than zero. * @default 10 */ resolution?: number | undefined; } interface Histogram { /** * Returns a `Map` object detailing the accumulated percentile distribution. * @since v11.10.0 */ readonly percentiles: Map<number, number>; /** * The number of times the event loop delay exceeded the maximum 1 hour event * loop delay threshold. * @since v11.10.0 */ readonly exce
eds: number; /** * The minimum recorded event loop delay. * @since v11.10.0 */ readonly min: number; /** * The maximum recorded event loop delay. * @since v11.10.0 */ readonly max: number; /** * The mean of the recorded event loop delays. * @since v11.10.0 */ readonly mean: number; /** * The standard deviation of the recorded event loop delays. * @since v11.10.0 */ readonly stddev: number; /** * Resets the collected histogram data. * @since v11.10.0 */ reset(): void; /** * Returns the value at the given percentile. * @since v11.10.0 * @param percentile A percentile value in the range (0, 100]. */ percentile(percentile: number): number; } interface IntervalHistogram extends Histogram { /** * Enables the update interval timer. Returns `true` if the timer was * started, `false` if it was already started. * @since v11.10.0 */ enable(): boolean; /** * Disables the update interval timer. Returns `true` if the timer was * stopped, `false` if it was already stopped. * @since v11.10.0 */ disable(): boolean; } interface RecordableHistogram extends Histogram { /** * @since v15.9.0, v14.18.0 * @param val The amount to record in the histogram. */ record(val: number | bigint): void; /** * Calculates the amount of time (in nanoseconds) that has passed since the * previous call to `recordDelta()` and records that amount in the histogram. * * ## Examples * @since v15.9.0, v14.18.0 */ recordDelta(): void; /** * Adds the values from `other` to this histogram. * @since v17.4.0, v16.14.0 */ add(other: RecordableHistogram): void; } /** * _This property is an extension by Node.js. It is not available in Web browsers._ * * Creates an `IntervalHistogram` object that samples and reports the event loop * delay over time. The delays will be reported in nanoseconds. * * Using a timer to detect approximate event loop delay works because the * execution of timers is tied specifically to the lifecycle of the libuv * event loop. That is, a delay in the loop will cause a delay in the execution * of the timer, and those delays are specifically what this API is intended to * detect. * * ```js * const { monitorEventLoopDelay } = require('node:perf_hooks'); * const h = monitorEventLoopDelay({ resolution: 20 }); * h.enable(); * // Do something. * h.disable(); * console.log(h.min); * console.log(h.max); * console.log(h.mean); * console.log(h.stddev); * console.log(h.percentiles); * console.log(h.percentile(50)); * console.log(h.percentile(99)); * ``` * @since v11.10.0 */ function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; interface CreateHistogramOptions { /** * The minimum recordable value. Must be an integer value greater than 0. * @default 1 */ min?: number | bigint | undefined; /** * The maximum recordable value. Must be an integer value greater than min. * @default Number.MAX_SAFE_INTEGER */ max?: number | bigint | undefined; /** * The number of accuracy digits. Must be a number between 1 and 5. * @default 3 */ figures?: number | undefined; } /** * Returns a `RecordableHistogram`. * @since v15.9.0, v14.18.0 */ function createHistogram(options?: CreateHistogramOptions): RecordableHistogram;
import { performance as _performance } from "perf_hooks"; global { /** * `performance` is a global reference for `require('perf_hooks').performance` * https://nodejs.org/api/globals.html#performance * @since v16.0.0 */ var performance: typeof globalThis extends { onmessage: any; performance: infer T; } ? T : typeof _performance; } } declare module "node:perf_hooks" { export * from "perf_hooks"; }
/** * The `node:url` module provides utilities for URL resolution and parsing. It can * be accessed using: * * ```js * import url from 'node:url'; * ``` * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/url.js) */ declare module "url" { import { Blob as NodeBlob } from "node:buffer"; import { ClientRequestArgs } from "node:http"; import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; // Input to `url.format` interface UrlObject { auth?: string | null | undefined; hash?: string | null | undefined; host?: string | null | undefined; hostname?: string | null | undefined; href?: string | null | undefined; pathname?: string | null | undefined; protocol?: string | null | undefined; search?: string | null | undefined; slashes?: boolean | null | undefined; port?: string | number | null | undefined; query?: string | null | ParsedUrlQueryInput | undefined; } // Output of `url.parse` interface Url { auth: string | null; hash: string | null; host: string | null; hostname: string | null; href: string; path: string | null; pathname: string | null; protocol: string | null; search: string | null; slashes: boolean | null; port: string | null; query: string | null | ParsedUrlQuery; } interface UrlWithParsedQuery extends Url { query: ParsedUrlQuery; } interface UrlWithStringQuery extends Url { query: string | null; } /** * The `url.parse()` method takes a URL string, parses it, and returns a URL * object. * * A `TypeError` is thrown if `urlString` is not a string. * * A `URIError` is thrown if the `auth` property is present but cannot be decoded. * * `url.parse()` uses a lenient, non-standard algorithm for parsing URL * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. * @since v0.1.25 * @deprecated Use the WHATWG URL API instead. * @param urlString The URL string to parse. * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property * on the returned URL object will be an unparsed, undecoded string. * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. */ function parse(urlString: string): UrlWithStringQuery; function parse( urlString: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean, ): UrlWithStringQuery; function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; /** * The `url.format()` method returns a formatted URL string derived from`urlObject`. * * ```js * const url = require('node:url'); * url.format({ * protocol: 'https', * hostname: 'example.com', * pathname: '/some/path', * query: { * page: 1, * format: 'json', * }, * }); * * // => 'https://example.com/some/path?page=1&#x26;format=json' * ``` * * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. * * The formatting process operates as follows: * * * A n
ew empty string `result` is created. * * If `urlObject.protocol` is a string, it is appended as-is to `result`. * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII * colon (`:`) character, the literal string `:` will be appended to `result`. * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: * * `urlObject.slashes` property is true; * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string * and appended to `result`followed by the literal string `@`. * * If the `urlObject.host` property is `undefined` then: * * If the `urlObject.hostname` is a string, it is appended to `result`. * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, * an `Error` is thrown. * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: * * The literal string `:` is appended to `result`, and * * The value of `urlObject.port` is coerced to a string and appended to`result`. * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. * * If the `urlObject.pathname` property is a string that is not an empty string: * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash * (`/`), then the literal string `'/'` is appended to `result`. * * The value of `urlObject.pathname` is appended to `result`. * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the * `querystring` module's `stringify()`method passing the value of `urlObject.query`. * * Otherwise, if `urlObject.search` is a string: * * If the value of `urlObject.search`_does not start_ with the ASCII question * mark (`?`) character, the literal string `?` is appended to `result`. * * The value of `urlObject.search` is appended to `result`. * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. * * If the `urlObject.hash` property is a string: * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) * character, the literal string `#` is appended to `result`. * * The value of `urlObject.hash` is appended to `result`. * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a * string, an `Error` is thrown. * * `result` is returned. * @since v0.1.25 * @legacy Use the WHATWG URL API instead. * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. */ function format(urlObject: URL, options?: URLFormatOptions): string; /** * The `url.format()` method returns a formatted URL string derived from`urlObject`. * * ```js * const url = require('url'); * url.format({ * protocol: 'https', * hostname: 'example.com', * pathname: '/some/path', * query: { * page: 1, * format: 'json' * } * }); * * // => 'https://example.com/some/path?page=1&#x26;format=json' * ``` * * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. * * The
formatting process operates as follows: * * * A new empty string `result` is created. * * If `urlObject.protocol` is a string, it is appended as-is to `result`. * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII * colon (`:`) character, the literal string `:` will be appended to `result`. * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: * * `urlObject.slashes` property is true; * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string * and appended to `result`followed by the literal string `@`. * * If the `urlObject.host` property is `undefined` then: * * If the `urlObject.hostname` is a string, it is appended to `result`. * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, * an `Error` is thrown. * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: * * The literal string `:` is appended to `result`, and * * The value of `urlObject.port` is coerced to a string and appended to`result`. * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. * * If the `urlObject.pathname` property is a string that is not an empty string: * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash * (`/`), then the literal string `'/'` is appended to `result`. * * The value of `urlObject.pathname` is appended to `result`. * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the * `querystring` module's `stringify()`method passing the value of `urlObject.query`. * * Otherwise, if `urlObject.search` is a string: * * If the value of `urlObject.search`_does not start_ with the ASCII question * mark (`?`) character, the literal string `?` is appended to `result`. * * The value of `urlObject.search` is appended to `result`. * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. * * If the `urlObject.hash` property is a string: * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) * character, the literal string `#` is appended to `result`. * * The value of `urlObject.hash` is appended to `result`. * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a * string, an `Error` is thrown. * * `result` is returned. * @since v0.1.25 * @legacy Use the WHATWG URL API instead. * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. */ function format(urlObject: UrlObject | string): string; /** * The `url.resolve()` method resolves a target URL relative to a base URL in a * manner similar to that of a web browser resolving an anchor tag. * * ```js * const url = require('node:url'); * url.resolve('/one/two/three', 'four'); // '/one/two/four' * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' * ``` * * To achieve the same resu
lt using the WHATWG URL API: * * ```js * function resolve(from, to) { * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); * if (resolvedUrl.protocol === 'resolve:') { * // `from` is a relative URL. * const { pathname, search, hash } = resolvedUrl; * return pathname + search + hash; * } * return resolvedUrl.toString(); * } * * resolve('/one/two/three', 'four'); // '/one/two/four' * resolve('http://example.com/', '/one'); // 'http://example.com/one' * resolve('http://example.com/one', '/two'); // 'http://example.com/two' * ``` * @since v0.1.25 * @legacy Use the WHATWG URL API instead. * @param from The base URL to use if `to` is a relative URL. * @param to The target URL to resolve. */ function resolve(from: string, to: string): string; /** * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an * invalid domain, the empty string is returned. * * It performs the inverse operation to {@link domainToUnicode}. * * ```js * import url from 'node:url'; * * console.log(url.domainToASCII('español.com')); * // Prints xn--espaol-zwa.com * console.log(url.domainToASCII('中文.com')); * // Prints xn--fiq228c.com * console.log(url.domainToASCII('xn--iñvalid.com')); * // Prints an empty string * ``` * @since v7.4.0, v6.13.0 */ function domainToASCII(domain: string): string; /** * Returns the Unicode serialization of the `domain`. If `domain` is an invalid * domain, the empty string is returned. * * It performs the inverse operation to {@link domainToASCII}. * * ```js * import url from 'node:url'; * * console.log(url.domainToUnicode('xn--espaol-zwa.com')); * // Prints español.com * console.log(url.domainToUnicode('xn--fiq228c.com')); * // Prints 中文.com * console.log(url.domainToUnicode('xn--iñvalid.com')); * // Prints an empty string * ``` * @since v7.4.0, v6.13.0 */ function domainToUnicode(domain: string): string; /** * This function ensures the correct decodings of percent-encoded characters as * well as ensuring a cross-platform valid absolute path string. * * ```js * import { fileURLToPath } from 'node:url'; * * const __filename = fileURLToPath(import.meta.url); * * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) * * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) * * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) * * new URL('file:///hello world').pathname; // Incorrect: /hello%20world * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) * ``` * @since v10.12.0 * @param url The file URL string or URL object to convert to a path. * @return The fully-resolved platform-specific Node.js file path. */ function fileURLToPath(url: string | URL): string; /** * This function ensures that `path` is resolved absolutely, and that the URL * control characters are correctly encoded when converting into a File URL. * * ```js * import { pathToFileURL } from 'node:url'; * * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) * * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c * pathToFileURL('/some/path%.c'); // Correct: f
ile:///some/path%25.c (POSIX) * ``` * @since v10.12.0 * @param path The path to convert to a File URL. * @return The file URL object. */ function pathToFileURL(path: string): URL; /** * This utility function converts a URL object into an ordinary options object as * expected by the `http.request()` and `https.request()` APIs. * * ```js * import { urlToHttpOptions } from 'node:url'; * const myURL = new URL('https://a:b@測試?abc#foo'); * * console.log(urlToHttpOptions(myURL)); * /* * { * protocol: 'https:', * hostname: 'xn--g6w251d', * hash: '#foo', * search: '?abc', * pathname: '/', * path: '/?abc', * href: 'https://a:b@xn--g6w251d/?abc#foo', * auth: 'a:b' * } * * ``` * @since v15.7.0, v14.18.0 * @param url The `WHATWG URL` object to convert to an options object. * @return Options object */ function urlToHttpOptions(url: URL): ClientRequestArgs; interface URLFormatOptions { auth?: boolean | undefined; fragment?: boolean | undefined; search?: boolean | undefined; unicode?: boolean | undefined; } /** * Browser-compatible `URL` class, implemented by following the WHATWG URL * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. * The `URL` class is also available on the global object. * * In accordance with browser conventions, all properties of `URL` objects * are implemented as getters and setters on the class prototype, rather than as * data properties on the object itself. Thus, unlike `legacy urlObject` s, * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still * return `true`. * @since v7.0.0, v6.13.0 */ class URL { /** * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. * * ```js * const { * Blob, * resolveObjectURL, * } = require('node:buffer'); * * const blob = new Blob(['hello']); * const id = URL.createObjectURL(blob); * * // later... * * const otherBlob = resolveObjectURL(id); * console.log(otherBlob.size); * ``` * * The data stored by the registered `Blob` will be retained in memory until`URL.revokeObjectURL()` is called to remove it. * * `Blob` objects are registered within the current thread. If using Worker * Threads, `Blob` objects registered within one Worker will not be available * to other workers or the main thread. * @since v16.7.0 * @experimental */ static createObjectURL(blob: NodeBlob): string; /** * Removes the stored `Blob` identified by the given ID. Attempting to revoke a * ID that isn't registered will silently fail. * @since v16.7.0 * @experimental * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. */ static revokeObjectURL(objectUrl: string): void; /** * Checks if an `input` relative to the `base` can be parsed to a `URL`. * * ```js * const isValid = URL.canParse('/foo', 'https://example.org/'); // true * * const isNotValid = URL.canParse('/foo'); // false * ``` * @since v19.9.0 * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is * `converted to a string` first. * @param base The base UR
L to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. */ static canParse(input: string, base?: string): boolean; constructor(input: string, base?: string | URL); /** * Gets and sets the fragment portion of the URL. * * ```js * const myURL = new URL('https://example.org/foo#bar'); * console.log(myURL.hash); * // Prints #bar * * myURL.hash = 'baz'; * console.log(myURL.href); * // Prints https://example.org/foo#baz * ``` * * Invalid URL characters included in the value assigned to the `hash` property * are `percent-encoded`. The selection of which characters to * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. */ hash: string; /** * Gets and sets the host portion of the URL. * * ```js * const myURL = new URL('https://example.org:81/foo'); * console.log(myURL.host); * // Prints example.org:81 * * myURL.host = 'example.com:82'; * console.log(myURL.href); * // Prints https://example.com:82/foo * ``` * * Invalid host values assigned to the `host` property are ignored. */ host: string; /** * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the * port. * * ```js * const myURL = new URL('https://example.org:81/foo'); * console.log(myURL.hostname); * // Prints example.org * * // Setting the hostname does not change the port * myURL.hostname = 'example.com'; * console.log(myURL.href); * // Prints https://example.com:81/foo * * // Use myURL.host to change the hostname and port * myURL.host = 'example.org:82'; * console.log(myURL.href); * // Prints https://example.org:82/foo * ``` * * Invalid host name values assigned to the `hostname` property are ignored. */ hostname: string; /** * Gets and sets the serialized URL. * * ```js * const myURL = new URL('https://example.org/foo'); * console.log(myURL.href); * // Prints https://example.org/foo * * myURL.href = 'https://example.com/bar'; * console.log(myURL.href); * // Prints https://example.com/bar * ``` * * Getting the value of the `href` property is equivalent to calling {@link toString}. * * Setting the value of this property to a new value is equivalent to creating a * new `URL` object using `new URL(value)`. Each of the `URL`object's properties will be modified. * * If the value assigned to the `href` property is not a valid URL, a `TypeError`will be thrown. */ href: string; /** * Gets the read-only serialization of the URL's origin. * * ```js * const myURL = new URL('https://example.org/foo/bar?baz'); * console.log(myURL.origin); * // Prints https://example.org * ``` * * ```js * const idnURL = new URL('https://測試'); * console.log(idnURL.origin); * // Prints https://xn--g6w251d * * console.log(idnURL.hostname); * // Prints xn--g6w251d * ``` */ readonly origin: string; /** * Gets and sets the password portion of the URL. * * ```js * const myURL = new URL('https://abc:xyz@example.com'); * console.log(myURL.password); * // Prints xyz *
* myURL.password = '123'; * console.log(myURL.href); * // Prints https://abc:123@example.com/ * ``` * * Invalid URL characters included in the value assigned to the `password` property * are `percent-encoded`. The selection of which characters to * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. */ password: string; /** * Gets and sets the path portion of the URL. * * ```js * const myURL = new URL('https://example.org/abc/xyz?123'); * console.log(myURL.pathname); * // Prints /abc/xyz * * myURL.pathname = '/abcdef'; * console.log(myURL.href); * // Prints https://example.org/abcdef?123 * ``` * * Invalid URL characters included in the value assigned to the `pathname`property are `percent-encoded`. The selection of which characters * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. */ pathname: string; /** * Gets and sets the port portion of the URL. * * The port value may be a number or a string containing a number in the range`0` to `65535` (inclusive). Setting the value to the default port of the`URL` objects given `protocol` will * result in the `port` value becoming * the empty string (`''`). * * The port value can be an empty string in which case the port depends on * the protocol/scheme: * * <omitted> * * Upon assigning a value to the port, the value will first be converted to a * string using `.toString()`. * * If that string is invalid but it begins with a number, the leading number is * assigned to `port`. * If the number lies outside the range denoted above, it is ignored. * * ```js * const myURL = new URL('https://example.org:8888'); * console.log(myURL.port); * // Prints 8888 * * // Default ports are automatically transformed to the empty string * // (HTTPS protocol's default port is 443) * myURL.port = '443'; * console.log(myURL.port); * // Prints the empty string * console.log(myURL.href); * // Prints https://example.org/ * * myURL.port = 1234; * console.log(myURL.port); * // Prints 1234 * console.log(myURL.href); * // Prints https://example.org:1234/ * * // Completely invalid port strings are ignored * myURL.port = 'abcd'; * console.log(myURL.port); * // Prints 1234 * * // Leading numbers are treated as a port number * myURL.port = '5678abcd'; * console.log(myURL.port); * // Prints 5678 * * // Non-integers are truncated * myURL.port = 1234.5678; * console.log(myURL.port); * // Prints 1234 * * // Out-of-range numbers which are not represented in scientific notation * // will be ignored. * myURL.port = 1e10; // 10000000000, will be range-checked as described below * console.log(myURL.port); * // Prints 1234 * ``` * * Numbers which contain a decimal point, * such as floating-point numbers or numbers in scientific notation, * are not an exception to this rule. * Leading numbers up to the decimal point will be set as the URL's port, * assuming they are valid: * * ```js * myURL.port = 4.567e21; * console.log(myURL.port); * // Prints 4 (because it is the leading number in the string '4.567e21') * ``` */ port: string; /** *
Gets and sets the protocol portion of the URL. * * ```js * const myURL = new URL('https://example.org'); * console.log(myURL.protocol); * // Prints https: * * myURL.protocol = 'ftp'; * console.log(myURL.href); * // Prints ftp://example.org/ * ``` * * Invalid URL protocol values assigned to the `protocol` property are ignored. */ protocol: string; /** * Gets and sets the serialized query portion of the URL. * * ```js * const myURL = new URL('https://example.org/abc?123'); * console.log(myURL.search); * // Prints ?123 * * myURL.search = 'abc=xyz'; * console.log(myURL.href); * // Prints https://example.org/abc?abc=xyz * ``` * * Any invalid URL characters appearing in the value assigned the `search`property will be `percent-encoded`. The selection of which * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. */ search: string; /** * Gets the `URLSearchParams` object representing the query parameters of the * URL. This property is read-only but the `URLSearchParams` object it provides * can be used to mutate the URL instance; to replace the entirety of query * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. * * Use care when using `.searchParams` to modify the `URL` because, * per the WHATWG specification, the `URLSearchParams` object uses * different rules to determine which characters to percent-encode. For * instance, the `URL` object will not percent encode the ASCII tilde (`~`) * character, while `URLSearchParams` will always encode it: * * ```js * const myURL = new URL('https://example.org/abc?foo=~bar'); * * console.log(myURL.search); // prints ?foo=~bar * * // Modify the URL via searchParams... * myURL.searchParams.sort(); * * console.log(myURL.search); // prints ?foo=%7Ebar * ``` */ readonly searchParams: URLSearchParams; /** * Gets and sets the username portion of the URL. * * ```js * const myURL = new URL('https://abc:xyz@example.com'); * console.log(myURL.username); * // Prints abc * * myURL.username = '123'; * console.log(myURL.href); * // Prints https://123:xyz@example.com/ * ``` * * Any invalid URL characters appearing in the value assigned the `username`property will be `percent-encoded`. The selection of which * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. */ username: string; /** * The `toString()` method on the `URL` object returns the serialized URL. The * value returned is equivalent to that of {@link href} and {@link toJSON}. */ toString(): string; /** * The `toJSON()` method on the `URL` object returns the serialized URL. The * value returned is equivalent to that of {@link href} and {@link toString}. * * This method is automatically called when an `URL` object is serialized * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). * * ```js * const myURLs = [ * new URL('https://www.example.com'), * new URL('https://test.example.org'), * ]; * console.log(JSON.stringify(myURLs)); * // Prints ["https://www.example.com/","https://test.example.org/"]
* ``` */ toJSON(): string; } /** * The `URLSearchParams` API provides read and write access to the query of a`URL`. The `URLSearchParams` class can also be used standalone with one of the * four following constructors. * The `URLSearchParams` class is also available on the global object. * * The WHATWG `URLSearchParams` interface and the `querystring` module have * similar purpose, but the purpose of the `querystring` module is more * general, as it allows the customization of delimiter characters (`&#x26;` and `=`). * On the other hand, this API is designed purely for URL query strings. * * ```js * const myURL = new URL('https://example.org/?abc=123'); * console.log(myURL.searchParams.get('abc')); * // Prints 123 * * myURL.searchParams.append('abc', 'xyz'); * console.log(myURL.href); * // Prints https://example.org/?abc=123&#x26;abc=xyz * * myURL.searchParams.delete('abc'); * myURL.searchParams.set('a', 'b'); * console.log(myURL.href); * // Prints https://example.org/?a=b * * const newSearchParams = new URLSearchParams(myURL.searchParams); * // The above is equivalent to * // const newSearchParams = new URLSearchParams(myURL.search); * * newSearchParams.append('a', 'c'); * console.log(myURL.href); * // Prints https://example.org/?a=b * console.log(newSearchParams.toString()); * // Prints a=b&#x26;a=c * * // newSearchParams.toString() is implicitly called * myURL.search = newSearchParams; * console.log(myURL.href); * // Prints https://example.org/?a=b&#x26;a=c * newSearchParams.delete('a'); * console.log(myURL.href); * // Prints https://example.org/?a=b&#x26;a=c * ``` * @since v7.5.0, v6.13.0 */ class URLSearchParams implements Iterable<[string, string]> { constructor( init?: | URLSearchParams | string | Record<string, string | readonly string[]> | Iterable<[string, string]> | ReadonlyArray<[string, string]>, ); /** * Append a new name-value pair to the query string. */ append(name: string, value: string): void; /** * If `value` is provided, removes all name-value pairs * where name is `name` and value is `value`.. * * If `value` is not provided, removes all name-value pairs whose name is `name`. */ delete(name: string, value?: string): void; /** * Returns an ES6 `Iterator` over each of the name-value pairs in the query. * Each item of the iterator is a JavaScript `Array`. The first item of the `Array`is the `name`, the second item of the `Array` is the `value`. * * Alias for `urlSearchParams[@@iterator]()`. */ entries(): IterableIterator<[string, string]>; /** * Iterates over each name-value pair in the query and invokes the given function. * * ```js * const myURL = new URL('https://example.org/?a=b&#x26;c=d'); * myURL.searchParams.forEach((value, name, searchParams) => { * console.log(name, value, myURL.searchParams === searchParams); * }); * // Prints: * // a b true * // c d true * ``` * @param fn Invoked for each name-value pair in the query * @param thisArg To be used as `this` value for when `fn` is called */ forEach<TThis = this>( callback: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, thisArg?: TThis, ): void; /** * Returns the value of the first name-value pair whose name is `name`. If there * are no such pairs, `null` is returned. * @return or `null` if there is no nam
e-value pair with the given `name`. */ get(name: string): string | null; /** * Returns the values of all name-value pairs whose name is `name`. If there are * no such pairs, an empty array is returned. */ getAll(name: string): string[]; /** * Checks if the `URLSearchParams` object contains key-value pair(s) based on`name` and an optional `value` argument. * * If `value` is provided, returns `true` when name-value pair with * same `name` and `value` exists. * * If `value` is not provided, returns `true` if there is at least one name-value * pair whose name is `name`. */ has(name: string, value?: string): boolean; /** * Returns an ES6 `Iterator` over the names of each name-value pair. * * ```js * const params = new URLSearchParams('foo=bar&#x26;foo=baz'); * for (const name of params.keys()) { * console.log(name); * } * // Prints: * // foo * // foo * ``` */ keys(): IterableIterator<string>; /** * Sets the value in the `URLSearchParams` object associated with `name` to`value`. If there are any pre-existing name-value pairs whose names are `name`, * set the first such pair's value to `value` and remove all others. If not, * append the name-value pair to the query string. * * ```js * const params = new URLSearchParams(); * params.append('foo', 'bar'); * params.append('foo', 'baz'); * params.append('abc', 'def'); * console.log(params.toString()); * // Prints foo=bar&#x26;foo=baz&#x26;abc=def * * params.set('foo', 'def'); * params.set('xyz', 'opq'); * console.log(params.toString()); * // Prints foo=def&#x26;abc=def&#x26;xyz=opq * ``` */ set(name: string, value: string): void; /** * The total number of parameter entries. * @since v19.8.0 */ readonly size: number; /** * Sort all existing name-value pairs in-place by their names. Sorting is done * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs * with the same name is preserved. * * This method can be used, in particular, to increase cache hits. * * ```js * const params = new URLSearchParams('query[]=abc&#x26;type=search&#x26;query[]=123'); * params.sort(); * console.log(params.toString()); * // Prints query%5B%5D=abc&#x26;query%5B%5D=123&#x26;type=search * ``` * @since v7.7.0, v6.13.0 */ sort(): void; /** * Returns the search parameters serialized as a string, with characters * percent-encoded where necessary. */ toString(): string; /** * Returns an ES6 `Iterator` over the values of each name-value pair. */ values(): IterableIterator<string>; [Symbol.iterator](): IterableIterator<[string, string]>; } import { URL as _URL, URLSearchParams as _URLSearchParams } from "url"; global { interface URLSearchParams extends _URLSearchParams {} interface URL extends _URL {} interface Global { URL: typeof _URL; URLSearchParams: typeof _URLSearchParams; } /** * `URL` class is a global reference for `require('url').URL` * https://nodejs.org/api/url.html#the-whatwg-url-api * @since v10.0.0 */ var URL: typeof globalThis extends { onmessage: any; URL: infer T; } ? T : typeof _URL; /** * `URLSearchParams` class is a global refer
ence for `require('url').URLSearchParams` * https://nodejs.org/api/url.html#class-urlsearchparams * @since v10.0.0 */ var URLSearchParams: typeof globalThis extends { onmessage: any; URLSearchParams: infer T; } ? T : typeof _URLSearchParams; } } declare module "node:url" { export * from "url"; }
/** * Clusters of Node.js processes can be used to run multiple instances of Node.js * that can distribute workloads among their application threads. When process * isolation is not needed, use the `worker_threads` module instead, which * allows running multiple application threads within a single Node.js instance. * * The cluster module allows easy creation of child processes that all share * server ports. * * ```js * import cluster from 'node:cluster'; * import http from 'node:http'; * import { availableParallelism } from 'node:os'; * import process from 'node:process'; * * const numCPUs = availableParallelism(); * * if (cluster.isPrimary) { * console.log(`Primary ${process.pid} is running`); * * // Fork workers. * for (let i = 0; i < numCPUs; i++) { * cluster.fork(); * } * * cluster.on('exit', (worker, code, signal) => { * console.log(`worker ${worker.process.pid} died`); * }); * } else { * // Workers can share any TCP connection * // In this case it is an HTTP server * http.createServer((req, res) => { * res.writeHead(200); * res.end('hello world\n'); * }).listen(8000); * * console.log(`Worker ${process.pid} started`); * } * ``` * * Running Node.js will now share port 8000 between the workers: * * ```console * $ node server.js * Primary 3596 is running * Worker 4324 started * Worker 4520 started * Worker 6056 started * Worker 5644 started * ``` * * On Windows, it is not yet possible to set up a named pipe server in a worker. * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/cluster.js) */ declare module "cluster" { import * as child from "node:child_process"; import EventEmitter = require("node:events"); import * as net from "node:net"; type SerializationType = "json" | "advanced"; export interface ClusterSettings { execArgv?: string[] | undefined; // default: process.execArgv exec?: string | undefined; args?: string[] | undefined; silent?: boolean | undefined; stdio?: any[] | undefined; uid?: number | undefined; gid?: number | undefined; inspectPort?: number | (() => number) | undefined; serialization?: SerializationType | undefined; cwd?: string | undefined; windowsHide?: boolean | undefined; } export interface Address { address: string; port: number; addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" } /** * A `Worker` object contains all public information and method about a worker. * In the primary it can be obtained using `cluster.workers`. In a worker * it can be obtained using `cluster.worker`. * @since v0.7.0 */ export class Worker extends EventEmitter { /** * Each new worker is given its own unique id, this id is stored in the`id`. * * While a worker is alive, this is the key that indexes it in`cluster.workers`. * @since v0.8.0 */ id: number; /** * All workers are created using `child_process.fork()`, the returned object * from this function is stored as `.process`. In a worker, the global `process`is stored. * * See: `Child Process module`. * * Workers will call `process.exit(0)` if the `'disconnect'` event occurs * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against * accidental disconnection. * @since v0.7.0 */ process: child.ChildProcess; /** * Send a message to a worker or primary, optionally with a handle. * * In the primary, this sends a message to a specific worker. It is identical to `ChildProcess.send()`. * * In a worker, this sends a message to the primary. It is identical to`process.send()`. * * This example will echo back all messages from the prim
ary: * * ```js * if (cluster.isPrimary) { * const worker = cluster.fork(); * worker.send('hi there'); * * } else if (cluster.isWorker) { * process.on('message', (msg) => { * process.send(msg); * }); * } * ``` * @since v0.7.0 * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: */ send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; send( message: child.Serializable, sendHandle: child.SendHandle, callback?: (error: Error | null) => void, ): boolean; send( message: child.Serializable, sendHandle: child.SendHandle, options?: child.MessageOptions, callback?: (error: Error | null) => void, ): boolean; /** * This function will kill the worker. In the primary worker, it does this by * disconnecting the `worker.process`, and once disconnected, killing with`signal`. In the worker, it does it by killing the process with `signal`. * * The `kill()` function kills the worker process without waiting for a graceful * disconnect, it has the same behavior as `worker.process.kill()`. * * This method is aliased as `worker.destroy()` for backwards compatibility. * * In a worker, `process.kill()` exists, but it is not this function; * it is `kill()`. * @since v0.9.12 * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. */ kill(signal?: string): void; destroy(signal?: string): void; /** * In a worker, this function will close all servers, wait for the `'close'` event * on those servers, and then disconnect the IPC channel. * * In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself. * * Causes `.exitedAfterDisconnect` to be set. * * After a server is closed, it will no longer accept new connections, * but connections may be accepted by any other listening worker. Existing * connections will be allowed to close as usual. When no more connections exist, * see `server.close()`, the IPC channel to the worker will close allowing it * to die gracefully. * * The above applies _only_ to server connections, client connections are not * automatically closed by workers, and disconnect does not wait for them to close * before exiting. * * In a worker, `process.disconnect` exists, but it is not this function; * it is `disconnect()`. * * Because long living server connections may block workers from disconnecting, it * may be useful to send a message, so application specific actions may be taken to * close them. It also may be useful to implement a timeout, killing a worker if * the `'disconnect'` event has not been emitted after some time. * * ```js * if (cluster.isPrimary) { * const worker = cluster.fork(); * let timeout; * * worker.on('listening', (address) => { * worker.send('shutdown'); * worker.disconnect(); * timeout = setTimeout(() => { * worker.kill(); * }, 2000); * }); * * worker.on('disconnect', () => { * clearTimeout(timeout); * }); * * } else if (cluster.isWorker) { * const net = require('node:net'); * const server = net.createServer((socket) => { * // Connection
s never end * }); * * server.listen(8000); * * process.on('message', (msg) => { * if (msg === 'shutdown') { * // Initiate graceful close of any connections to server * } * }); * } * ``` * @since v0.7.7 * @return A reference to `worker`. */ disconnect(): void; /** * This function returns `true` if the worker is connected to its primary via its * IPC channel, `false` otherwise. A worker is connected to its primary after it * has been created. It is disconnected after the `'disconnect'` event is emitted. * @since v0.11.14 */ isConnected(): boolean; /** * This function returns `true` if the worker's process has terminated (either * because of exiting or being signaled). Otherwise, it returns `false`. * * ```js * import cluster from 'node:cluster'; * import http from 'node:http'; * import { availableParallelism } from 'node:os'; * import process from 'node:process'; * * const numCPUs = availableParallelism(); * * if (cluster.isPrimary) { * console.log(`Primary ${process.pid} is running`); * * // Fork workers. * for (let i = 0; i < numCPUs; i++) { * cluster.fork(); * } * * cluster.on('fork', (worker) => { * console.log('worker is dead:', worker.isDead()); * }); * * cluster.on('exit', (worker, code, signal) => { * console.log('worker is dead:', worker.isDead()); * }); * } else { * // Workers can share any TCP connection. In this case, it is an HTTP server. * http.createServer((req, res) => { * res.writeHead(200); * res.end(`Current process\n ${process.pid}`); * process.kill(process.pid); * }).listen(8000); * } * ``` * @since v0.11.14 */ isDead(): boolean; /** * This property is `true` if the worker exited due to `.disconnect()`. * If the worker exited any other way, it is `false`. If the * worker has not exited, it is `undefined`. * * The boolean `worker.exitedAfterDisconnect` allows distinguishing between * voluntary and accidental exit, the primary may choose not to respawn a worker * based on this value. * * ```js * cluster.on('exit', (worker, code, signal) => { * if (worker.exitedAfterDisconnect === true) { * console.log('Oh, it was just voluntary – no need to worry'); * } * }); * * // kill worker * worker.kill(); * ``` * @since v6.0.0 */ exitedAfterDisconnect: boolean; /** * events.EventEmitter * 1. disconnect * 2. error * 3. exit * 4. listening * 5. message * 6. online */ addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "disconnect", listener: () => void): this; addListener(event: "error", listener: (error: Error) => void): this; addListener(event: "exit", listener: (code: number, signal: string) => void): this; addListener(event: "listening", listener: (address: Address) => void): this; addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. addListener(event: "online", listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "disconnect"): boolean; emit(event: "error"
, error: Error): boolean; emit(event: "exit", code: number, signal: string): boolean; emit(event: "listening", address: Address): boolean; emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; emit(event: "online"): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "disconnect", listener: () => void): this; on(event: "error", listener: (error: Error) => void): this; on(event: "exit", listener: (code: number, signal: string) => void): this; on(event: "listening", listener: (address: Address) => void): this; on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. on(event: "online", listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "disconnect", listener: () => void): this; once(event: "error", listener: (error: Error) => void): this; once(event: "exit", listener: (code: number, signal: string) => void): this; once(event: "listening", listener: (address: Address) => void): this; once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. once(event: "online", listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "disconnect", listener: () => void): this; prependListener(event: "error", listener: (error: Error) => void): this; prependListener(event: "exit", listener: (code: number, signal: string) => void): this; prependListener(event: "listening", listener: (address: Address) => void): this; prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. prependListener(event: "online", listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "disconnect", listener: () => void): this; prependOnceListener(event: "error", listener: (error: Error) => void): this; prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; prependOnceListener(event: "listening", listener: (address: Address) => void): this; prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. prependOnceListener(event: "online", listener: () => void): this; } export interface Cluster extends EventEmitter { disconnect(callback?: () => void): void; fork(env?: any): Worker; /** @deprecated since v16.0.0 - use isPrimary. */ readonly isMaster: boolean; readonly isPrimary: boolean; readonly isWorker: boolean; schedulingPolicy: number; readonly settings: ClusterSettings; /** @deprecated since v16.0.0 - use setupPrimary. */ setupMaster(settings?: ClusterSettings): void; /** * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. */ setupPrimary(settings?: ClusterSettings): void; readonly worker?: Worker | undefined; readonly workers?: NodeJS.Dict<Worker> | undefined; readonly SCHED_NONE: number; readonly SCHED_RR: number; /** * events.EventEmitter * 1. disconnect * 2. exit * 3. fork * 4. listening * 5. message * 6. online * 7. setup */ addListener(event: string, listener: (.
..args: any[]) => void): this; addListener(event: "disconnect", listener: (worker: Worker) => void): this; addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; addListener(event: "fork", listener: (worker: Worker) => void): this; addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; addListener( event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, ): this; // the handle is a net.Socket or net.Server object, or undefined. addListener(event: "online", listener: (worker: Worker) => void): this; addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "disconnect", worker: Worker): boolean; emit(event: "exit", worker: Worker, code: number, signal: string): boolean; emit(event: "fork", worker: Worker): boolean; emit(event: "listening", worker: Worker, address: Address): boolean; emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; emit(event: "online", worker: Worker): boolean; emit(event: "setup", settings: ClusterSettings): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "disconnect", listener: (worker: Worker) => void): this; on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; on(event: "fork", listener: (worker: Worker) => void): this; on(event: "listening", listener: (worker: Worker, address: Address) => void): this; on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. on(event: "online", listener: (worker: Worker) => void): this; on(event: "setup", listener: (settings: ClusterSettings) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "disconnect", listener: (worker: Worker) => void): this; once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; once(event: "fork", listener: (worker: Worker) => void): this; once(event: "listening", listener: (worker: Worker, address: Address) => void): this; once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. once(event: "online", listener: (worker: Worker) => void): this; once(event: "setup", listener: (settings: ClusterSettings) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "disconnect", listener: (worker: Worker) => void): this; prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; prependListener(event: "fork", listener: (worker: Worker) => void): this; prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; // the handle is a net.Socket or net.Server object, or undefined. prependListener( event: "message", listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void, ): this; prependListener(event: "online", listener: (worker: Worker) => void): this; prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; prependOnceListener(event: "exit", listener: (worker: Worker,
code: number, signal: string) => void): this; prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; // the handle is a net.Socket or net.Server object, or undefined. prependOnceListener( event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, ): this; prependOnceListener(event: "online", listener: (worker: Worker) => void): this; prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; } const cluster: Cluster; export default cluster; } declare module "node:cluster" { export * from "cluster"; export { default as default } from "cluster"; }
/** * The `node:assert` module provides a set of assertion functions for verifying * invariants. * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/assert.js) */ declare module "assert" { /** * An alias of {@link ok}. * @since v0.5.9 * @param value The input that is checked for being truthy. */ function assert(value: unknown, message?: string | Error): asserts value; namespace assert { /** * Indicates the failure of an assertion. All errors thrown by the `node:assert`module will be instances of the `AssertionError` class. */ class AssertionError extends Error { /** * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. */ actual: unknown; /** * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. */ expected: unknown; /** * Set to the passed in operator value. */ operator: string; /** * Indicates if the message was auto-generated (`true`) or not. */ generatedMessage: boolean; /** * Value is always `ERR_ASSERTION` to show that the error is an assertion error. */ code: "ERR_ASSERTION"; constructor(options?: { /** If provided, the error message is set to this value. */ message?: string | undefined; /** The `actual` property on the error instance. */ actual?: unknown | undefined; /** The `expected` property on the error instance. */ expected?: unknown | undefined; /** The `operator` property on the error instance. */ operator?: string | undefined; /** If provided, the generated stack trace omits frames before this function. */ // eslint-disable-next-line @typescript-eslint/ban-types stackStartFn?: Function | undefined; }); } /** * This feature is deprecated and will be removed in a future version. * Please consider using alternatives such as the `mock` helper function. * @since v14.2.0, v12.19.0 * @deprecated Deprecated */ class CallTracker { /** * The wrapper function is expected to be called exactly `exact` times. If the * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an * error. * * ```js * import assert from 'node:assert'; * * // Creates call tracker. * const tracker = new assert.CallTracker(); * * function func() {} * * // Returns a function that wraps func() that must be called exact times * // before tracker.verify(). * const callsfunc = tracker.calls(func); * ``` * @since v14.2.0, v12.19.0 * @param [fn='A no-op function'] * @param [exact=1] * @return that wraps `fn`. */ calls(exact?: number): () => void; calls<Func extends (...args: any[]) => any>(fn?: Func, exact?: number): Func; /** * Example: * * ```js * import assert from 'node:assert'; * * const tracker = new assert.CallTracker(); * * function func() {} * const callsfunc = tracker.calls(func); * callsfunc(1, 2, 3); * * assert.deepStrictEqual(tracker.getCalls(callsfunc), * [{ thisArg: undefined, arguments: [1, 2, 3] }]); * ```
* @since v18.8.0, v16.18.0 * @param fn * @return An Array with all the calls to a tracked function. */ getCalls(fn: Function): CallTrackerCall[]; /** * The arrays contains information about the expected and actual number of calls of * the functions that have not been called the expected number of times. * * ```js * import assert from 'node:assert'; * * // Creates call tracker. * const tracker = new assert.CallTracker(); * * function func() {} * * // Returns a function that wraps func() that must be called exact times * // before tracker.verify(). * const callsfunc = tracker.calls(func, 2); * * // Returns an array containing information on callsfunc() * console.log(tracker.report()); * // [ * // { * // message: 'Expected the func function to be executed 2 time(s) but was * // executed 0 time(s).', * // actual: 0, * // expected: 2, * // operator: 'func', * // stack: stack trace * // } * // ] * ``` * @since v14.2.0, v12.19.0 * @return An Array of objects containing information about the wrapper functions returned by `calls`. */ report(): CallTrackerReportInformation[]; /** * Reset calls of the call tracker. * If a tracked function is passed as an argument, the calls will be reset for it. * If no arguments are passed, all tracked functions will be reset. * * ```js * import assert from 'node:assert'; * * const tracker = new assert.CallTracker(); * * function func() {} * const callsfunc = tracker.calls(func); * * callsfunc(); * // Tracker was called once * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); * * tracker.reset(callsfunc); * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); * ``` * @since v18.8.0, v16.18.0 * @param fn a tracked function to reset. */ reset(fn?: Function): void; /** * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that * have not been called the expected number of times. * * ```js * import assert from 'node:assert'; * * // Creates call tracker. * const tracker = new assert.CallTracker(); * * function func() {} * * // Returns a function that wraps func() that must be called exact times * // before tracker.verify(). * const callsfunc = tracker.calls(func, 2); * * callsfunc(); * * // Will throw an error since callsfunc() was only called once. * tracker.verify(); * ``` * @since v14.2.0, v12.19.0 */ verify(): void; } interface CallTrackerCall { thisArg: object; arguments: unknown[]; } interface CallTrackerReportInformation { message: string; /** The actual number of times the function was called. */ actual: number; /** The number of times the function was expected to be called. */ expected: number; /** The name of the function that is wrapped. */ operator: string; /** A stack trace of th
e function. */ stack: object; } type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; /** * Throws an `AssertionError` with the provided error message or a default * error message. If the `message` parameter is an instance of an `Error` then * it will be thrown instead of the `AssertionError`. * * ```js * import assert from 'node:assert/strict'; * * assert.fail(); * // AssertionError [ERR_ASSERTION]: Failed * * assert.fail('boom'); * // AssertionError [ERR_ASSERTION]: boom * * assert.fail(new TypeError('need array')); * // TypeError: need array * ``` * * Using `assert.fail()` with more than two arguments is possible but deprecated. * See below for further details. * @since v0.1.21 * @param [message='Failed'] */ function fail(message?: string | Error): never; /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ function fail( actual: unknown, expected: unknown, message?: string | Error, operator?: string, // eslint-disable-next-line @typescript-eslint/ban-types stackStartFn?: Function, ): never; /** * Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. * * If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. * * Be aware that in the `repl` the error message will be different to the one * thrown in a file! See below for further details. * * ```js * import assert from 'node:assert/strict'; * * assert.ok(true); * // OK * assert.ok(1); * // OK * * assert.ok(); * // AssertionError: No value argument passed to `assert.ok()` * * assert.ok(false, 'it\'s false'); * // AssertionError: it's false * * // In the repl: * assert.ok(typeof 123 === 'string'); * // AssertionError: false == true * * // In a file (e.g. test.js): * assert.ok(typeof 123 === 'string'); * // AssertionError: The expression evaluated to a falsy value: * // * // assert.ok(typeof 123 === 'string') * * assert.ok(false); * // AssertionError: The expression evaluated to a falsy value: * // * // assert.ok(false) * * assert.ok(0); * // AssertionError: The expression evaluated to a falsy value: * // * // assert.ok(0) * ``` * * ```js * import assert from 'node:assert/strict'; * * // Using `assert()` works the same: * assert(0); * // AssertionError: The expression evaluated to a falsy value: * // * // assert(0) * ``` * @since v0.1.21 */ function ok(value: unknown, message?: string | Error): asserts value; /** * **Strict assertion mode** * * An alias of {@link strictEqual}. * * **Legacy assertion mode** * * > Stability: 3 - Legacy: Use {@link strictEqual} instead. * * Tests shallow, coercive equality between the `actual` and `expected` parameters
* using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled * and treated as being identical if both sides are `NaN`. * * ```js * import assert from 'node:assert'; * * assert.equal(1, 1); * // OK, 1 == 1 * assert.equal(1, '1'); * // OK, 1 == '1' * assert.equal(NaN, NaN); * // OK * * assert.equal(1, 2); * // AssertionError: 1 == 2 * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } * ``` * * If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. * @since v0.1.21 */ function equal(actual: unknown, expected: unknown, message?: string | Error): void; /** * **Strict assertion mode** * * An alias of {@link notStrictEqual}. * * **Legacy assertion mode** * * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. * * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is * specially handled and treated as being identical if both sides are `NaN`. * * ```js * import assert from 'node:assert'; * * assert.notEqual(1, 2); * // OK * * assert.notEqual(1, 1); * // AssertionError: 1 != 1 * * assert.notEqual(1, '1'); * // AssertionError: 1 != '1' * ``` * * If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error * message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. * @since v0.1.21 */ function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; /** * **Strict assertion mode** * * An alias of {@link deepStrictEqual}. * * **Legacy assertion mode** * * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. * * Tests for deep equality between the `actual` and `expected` parameters. Consider * using {@link deepStrictEqual} instead. {@link deepEqual} can have * surprising results. * * _Deep equality_ means that the enumerable "own" properties of child objects * are also recursively evaluated by the following rules. * @since v0.1.21 */ function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; /** * **Strict assertion mode** * * An alias of {@link notDeepStrictEqual}. * * **Legacy assertion mode** * * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. * * Tests for any deep inequality. Opposite of {@link deepEqual}. * * ```js * import assert from 'node:assert'; * * const obj1 = { * a: { * b: 1, * }, * }; * const obj2 = { * a: { * b: 2, * }, * }; * const obj3 = { * a: { * b: 1, * }, * }; * const obj4 = { __proto__: obj1 }; * * assert.n
otDeepEqual(obj1, obj1); * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } * * assert.notDeepEqual(obj1, obj2); * // OK * * assert.notDeepEqual(obj1, obj3); * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } * * assert.notDeepEqual(obj1, obj4); * // OK * ``` * * If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default * error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown * instead of the `AssertionError`. * @since v0.1.21 */ function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; /** * Tests strict equality between the `actual` and `expected` parameters as * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * ```js * import assert from 'node:assert/strict'; * * assert.strictEqual(1, 2); * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: * // * // 1 !== 2 * * assert.strictEqual(1, 1); * // OK * * assert.strictEqual('Hello foobar', 'Hello World!'); * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: * // + actual - expected * // * // + 'Hello foobar' * // - 'Hello World!' * // ^ * * const apples = 1; * const oranges = 2; * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 * * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); * // TypeError: Inputs are not identical * ``` * * If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown * instead of the `AssertionError`. * @since v0.1.21 */ function strictEqual<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T; /** * Tests strict inequality between the `actual` and `expected` parameters as * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * ```js * import assert from 'node:assert/strict'; * * assert.notStrictEqual(1, 2); * // OK * * assert.notStrictEqual(1, 1); * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: * // * // 1 * * assert.notStrictEqual(1, '1'); * // OK * ``` * * If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown * instead of the `AssertionError`. * @since v0.1.21 */ function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; /** * Tests for deep equality between the `actual` and `expected` parameters. * "Deep" equality means that the enumerable "own" properties of child objects * are recursively e
valuated also by the following rules. * @since v1.2.0 */ function deepStrictEqual<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T; /** * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. * * ```js * import assert from 'node:assert/strict'; * * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); * // OK * ``` * * If the values are deeply and strictly equal, an `AssertionError` is thrown * with a `message` property set equal to the value of the `message` parameter. If * the `message` parameter is undefined, a default error message is assigned. If * the `message` parameter is an instance of an `Error` then it will be thrown * instead of the `AssertionError`. * @since v1.2.0 */ function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; /** * Expects the function `fn` to throw an error. * * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, * a validation object where each property will be tested for strict deep equality, * or an instance of error where each property will be tested for strict deep * equality including the non-enumerable `message` and `name` properties. When * using an object, it is also possible to use a regular expression, when * validating against a string property. See below for examples. * * If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation * fails. * * Custom validation object/error instance: * * ```js * import assert from 'node:assert/strict'; * * const err = new TypeError('Wrong value'); * err.code = 404; * err.foo = 'bar'; * err.info = { * nested: true, * baz: 'text', * }; * err.reg = /abc/i; * * assert.throws( * () => { * throw err; * }, * { * name: 'TypeError', * message: 'Wrong value', * info: { * nested: true, * baz: 'text', * }, * // Only properties on the validation object will be tested for. * // Using nested objects requires all properties to be present. Otherwise * // the validation is going to fail. * }, * ); * * // Using regular expressions to validate error properties: * assert.throws( * () => { * throw err; * }, * { * // The `name` and `message` properties are strings and using regular * // expressions on those will match against the string. If they fail, an * // error is thrown. * name: /^TypeError$/, * message: /Wrong/, * foo: 'bar', * info: { * nested: true, * // It is not possible to use regular expressions for nested properties! * baz: 'text', * }, * // The `reg` property contains a regular expression and only if the * // validation object contains an identical regular expression, it is going * // to pass. * reg: /abc/i, * }, * ); * * // Fails due to the different `message` and `name` properties: * assert.throws( * () => { * const otherErr = new Error('Not f
ound'); * // Copy all enumerable properties from `err` to `otherErr`. * for (const [key, value] of Object.entries(err)) { * otherErr[key] = value; * } * throw otherErr; * }, * // The error's `message` and `name` properties will also be checked when using * // an error as validation object. * err, * ); * ``` * * Validate instanceof using constructor: * * ```js * import assert from 'node:assert/strict'; * * assert.throws( * () => { * throw new Error('Wrong value'); * }, * Error, * ); * ``` * * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): * * Using a regular expression runs `.toString` on the error object, and will * therefore also include the error name. * * ```js * import assert from 'node:assert/strict'; * * assert.throws( * () => { * throw new Error('Wrong value'); * }, * /^Error: Wrong value$/, * ); * ``` * * Custom error validation: * * The function must return `true` to indicate all internal validations passed. * It will otherwise fail with an `AssertionError`. * * ```js * import assert from 'node:assert/strict'; * * assert.throws( * () => { * throw new Error('Wrong value'); * }, * (err) => { * assert(err instanceof Error); * assert(/value/.test(err)); * // Avoid returning anything from validation functions besides `true`. * // Otherwise, it's not clear what part of the validation failed. Instead, * // throw an error about the specific validation that failed (as done in this * // example) and add as much helpful debugging information to that error as * // possible. * return true; * }, * 'unexpected error', * ); * ``` * * `error` cannot be a string. If a string is provided as the second * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same * message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using * a string as the second argument gets considered: * * ```js * import assert from 'node:assert/strict'; * * function throwingFirst() { * throw new Error('First'); * } * * function throwingSecond() { * throw new Error('Second'); * } * * function notThrowing() {} * * // The second argument is a string and the input function threw an Error. * // The first case will not throw as it does not match for the error message * // thrown by the input function! * assert.throws(throwingFirst, 'Second'); * // In the next example the message has no benefit over the message from the * // error and since it is not clear if the user intended to actually match * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. * assert.throws(throwingSecond, 'Second'); * // TypeError [ERR_AMBIGUOUS_ARGUMENT] * * // The string is only used (as message) in case the function does not throw: * assert.throws(notThrowing, 'Second'); * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second *
* // If it was intended to match for the error message do this instead: * // It does not throw because the error messages match. * assert.throws(throwingSecond, /Second$/); * * // If the error message does not match, an AssertionError is thrown. * assert.throws(throwingFirst, /Second$/); * // AssertionError [ERR_ASSERTION] * ``` * * Due to the confusing error-prone notation, avoid a string as the second * argument. * @since v0.1.21 */ function throws(block: () => unknown, message?: string | Error): void; function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; /** * Asserts that the function `fn` does not throw an error. * * Using `assert.doesNotThrow()` is actually not useful because there * is no benefit in catching an error and then rethrowing it. Instead, consider * adding a comment next to the specific code path that should not throw and keep * error messages as expressive as possible. * * When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. * * If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a * different type, or if the `error` parameter is undefined, the error is * propagated back to the caller. * * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation * function. See {@link throws} for more details. * * The following, for instance, will throw the `TypeError` because there is no * matching error type in the assertion: * * ```js * import assert from 'node:assert/strict'; * * assert.doesNotThrow( * () => { * throw new TypeError('Wrong value'); * }, * SyntaxError, * ); * ``` * * However, the following will result in an `AssertionError` with the message * 'Got unwanted exception...': * * ```js * import assert from 'node:assert/strict'; * * assert.doesNotThrow( * () => { * throw new TypeError('Wrong value'); * }, * TypeError, * ); * ``` * * If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: * * ```js * import assert from 'node:assert/strict'; * * assert.doesNotThrow( * () => { * throw new TypeError('Wrong value'); * }, * /Wrong value/, * 'Whoops', * ); * // Throws: AssertionError: Got unwanted exception: Whoops * ``` * @since v0.1.21 */ function doesNotThrow(block: () => unknown, message?: string | Error): void; function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; /** * Throws `value` if `value` is not `undefined` or `null`. This is useful when * testing the `error` argument in callbacks. The stack trace contains all frames * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. * * ```js * import assert from 'node:assert/strict'; * * assert.ifError(null); * // OK * assert.ifError(0); * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 * assert.ifE
rror('error'); * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' * assert.ifError(new Error()); * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error * * // Create some random error frames. * let err; * (function errorFrame() { * err = new Error('test error'); * })(); * * (function ifErrorFrame() { * assert.ifError(err); * })(); * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error * // at ifErrorFrame * // at errorFrame * ``` * @since v0.1.97 */ function ifError(value: unknown): asserts value is null | undefined; /** * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately * calls the function and awaits the returned promise to complete. It will then * check that the promise is rejected. * * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error * handler is skipped. * * Besides the async nature to await the completion behaves identically to {@link throws}. * * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, * an object where each property will be tested for, or an instance of error where * each property will be tested for including the non-enumerable `message` and`name` properties. * * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. * * ```js * import assert from 'node:assert/strict'; * * await assert.rejects( * async () => { * throw new TypeError('Wrong value'); * }, * { * name: 'TypeError', * message: 'Wrong value', * }, * ); * ``` * * ```js * import assert from 'node:assert/strict'; * * await assert.rejects( * async () => { * throw new TypeError('Wrong value'); * }, * (err) => { * assert.strictEqual(err.name, 'TypeError'); * assert.strictEqual(err.message, 'Wrong value'); * return true; * }, * ); * ``` * * ```js * import assert from 'node:assert/strict'; * * assert.rejects( * Promise.reject(new Error('Wrong value')), * Error, * ).then(() => { * // ... * }); * ``` * * `error` cannot be a string. If a string is provided as the second * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the * example in {@link throws} carefully if using a string as the second * argument gets considered. * @since v10.0.0 */ function rejects(block: (() => Promise<unknown>) | Promise<unknown>, message?: string | Error): Promise<void>; function rejects( block: (() => Promise<unknown>) | Promise<unknown>, error: AssertPredicate, message?: string | Error, ): Promise<void>; /** * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately * calls the function and awaits the returne
d promise to complete. It will then * check that the promise is not rejected. * * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If * the function does not return a promise, `assert.doesNotReject()` will return a * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases * the error handler is skipped. * * Using `assert.doesNotReject()` is actually not useful because there is little * benefit in catching a rejection and then rejecting it again. Instead, consider * adding a comment next to the specific code path that should not reject and keep * error messages as expressive as possible. * * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation * function. See {@link throws} for more details. * * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. * * ```js * import assert from 'node:assert/strict'; * * await assert.doesNotReject( * async () => { * throw new TypeError('Wrong value'); * }, * SyntaxError, * ); * ``` * * ```js * import assert from 'node:assert/strict'; * * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) * .then(() => { * // ... * }); * ``` * @since v10.0.0 */ function doesNotReject( block: (() => Promise<unknown>) | Promise<unknown>, message?: string | Error, ): Promise<void>; function doesNotReject( block: (() => Promise<unknown>) | Promise<unknown>, error: AssertPredicate, message?: string | Error, ): Promise<void>; /** * Expects the `string` input to match the regular expression. * * ```js * import assert from 'node:assert/strict'; * * assert.match('I will fail', /pass/); * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... * * assert.match(123, /pass/); * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. * * assert.match('I will pass', /pass/); * // OK * ``` * * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal * to the value of the `message` parameter. If the `message` parameter is * undefined, a default error message is assigned. If the `message` parameter is an * instance of an `Error` then it will be thrown instead of the `AssertionError`. * @since v13.6.0, v12.16.0 */ function match(value: string, regExp: RegExp, message?: string | Error): void; /** * Expects the `string` input not to match the regular expression. * * ```js * import assert from 'node:assert/strict'; * * assert.doesNotMatch('I will fail', /fail/); * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... * * assert.doesNotMatch(123, /pass/); * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. * * assert.doesNotMatch('I will pass', /different/); * // OK * ``` * * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `messa
ge` property set equal * to the value of the `message` parameter. If the `message` parameter is * undefined, a default error message is assigned. If the `message` parameter is an * instance of an `Error` then it will be thrown instead of the `AssertionError`. * @since v13.6.0, v12.16.0 */ function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; const strict: & Omit< typeof assert, | "equal" | "notEqual" | "deepEqual" | "notDeepEqual" | "ok" | "strictEqual" | "deepStrictEqual" | "ifError" | "strict" > & { (value: unknown, message?: string | Error): asserts value; equal: typeof strictEqual; notEqual: typeof notStrictEqual; deepEqual: typeof deepStrictEqual; notDeepEqual: typeof notDeepStrictEqual; // Mapped types and assertion functions are incompatible? // TS2775: Assertions require every name in the call target // to be declared with an explicit type annotation. ok: typeof ok; strictEqual: typeof strictEqual; deepStrictEqual: typeof deepStrictEqual; ifError: typeof ifError; strict: typeof strict; }; } export = assert; } declare module "node:assert" { import assert = require("assert"); export = assert; }
/** * The `node:fs` module enables interacting with the file system in a * way modeled on standard POSIX functions. * * To use the promise-based APIs: * * ```js * import * as fs from 'node:fs/promises'; * ``` * * To use the callback and sync APIs: * * ```js * import * as fs from 'node:fs'; * ``` * * All file system operations have synchronous, callback, and promise-based * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/fs.js) */ declare module "fs" { import * as stream from "node:stream"; import { Abortable, EventEmitter } from "node:events"; import { URL } from "node:url"; import * as promises from "node:fs/promises"; export { promises }; /** * Valid types for path values in "fs". */ export type PathLike = string | Buffer | URL; export type PathOrFileDescriptor = PathLike | number; export type TimeLike = string | number | Date; export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; export type BufferEncodingOption = | "buffer" | { encoding: "buffer"; }; export interface ObjectEncodingOptions { encoding?: BufferEncoding | null | undefined; } export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; export type OpenMode = number | string; export type Mode = number | string; export interface StatsBase<T> { 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<number> {} /** * A `fs.Stats` object provides information about a file. * * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and * their synchronous counterparts are of this type. * If `bigint` in the `options` passed to those methods is true, the numeric values * will be `bigint` instead of `number`, and the object will contain additional * nanosecond-precision properties suffixed with `Ns`. * * ```console * Stats { * dev: 2114, * ino: 48064969, * mode: 33188, * nlink: 1, * uid: 85, * gid: 100, * rdev: 0, * size: 527, * blksize: 4096, * blocks: 8, * atimeMs: 1318289051000.1, * mtimeMs: 1318289051000.1, * ctimeMs: 1318289051000.1, * birthtimeMs: 1318289051000.1, * atime: Mon, 10 Oct 2011 23:24:11 GMT, * mtime: Mon, 10 Oct 2011 23:24:11 GMT, * ctime: Mon, 10 Oct 2011 23:24:11 GMT, * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } * ``` * * `bigint` version: * * ```console * BigIntStats { * dev: 2114n, * ino: 48064969n, * mode: 33188n, * nlink: 1n, * uid: 85n, * gid: 100n, * rdev: 0n, * size: 527n, * blksize: 4096n, * blocks: 8n, * atimeMs: 1318289051000n, * mtimeMs: 1318289051000n, * ctimeMs: 1318289051000n, * birthtimeMs: 1318289051000n, * atimeNs: 1318289051000000000n, * mtimeNs: 1318289051000000000n, * ctimeNs: 1318289051000000000n, * birthtimeNs: 1318289051000000000n, * atime: Mon, 10 Oct 2011 23:24:11 GMT, * mtime: Mon, 10 Oct 2011 23:24:11 GMT, * ctime: Mon, 10 Oct 2011 23:24:11 GMT, * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } * ``` * @since v0.1.21 */
export class Stats {} export interface StatsFsBase<T> { /** Type of file system. */ type: T; /** Optimal transfer block size. */ bsize: T; /** Total data blocks in file system. */ blocks: T; /** Free blocks in file system. */ bfree: T; /** Available blocks for unprivileged users */ bavail: T; /** Total file nodes in file system. */ files: T; /** Free file nodes in file system. */ ffree: T; } export interface StatsFs extends StatsFsBase<number> {} /** * Provides information about a mounted file system. * * Objects returned from {@link statfs} and its synchronous counterpart are of * this type. If `bigint` in the `options` passed to those methods is `true`, the * numeric values will be `bigint` instead of `number`. * * ```console * StatFs { * type: 1397114950, * bsize: 4096, * blocks: 121938943, * bfree: 61058895, * bavail: 61058895, * files: 999, * ffree: 1000000 * } * ``` * * `bigint` version: * * ```console * StatFs { * type: 1397114950n, * bsize: 4096n, * blocks: 121938943n, * bfree: 61058895n, * bavail: 61058895n, * files: 999n, * ffree: 1000000n * } * ``` * @since v19.6.0, v18.15.0 */ export class StatsFs {} export interface BigIntStatsFs extends StatsFsBase<bigint> {} export interface StatFsOptions { bigint?: boolean | undefined; } /** * A representation of a directory entry, which can be a file or a subdirectory * within the directory, as returned by reading from an `fs.Dir`. The * directory entry is a combination of the file name and file type pairs. * * Additionally, when {@link readdir} or {@link readdirSync} is called with * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. * @since v10.10.0 */ export class Dirent { /** * Returns `true` if the `fs.Dirent` object describes a regular file. * @since v10.10.0 */ isFile(): boolean; /** * Returns `true` if the `fs.Dirent` object describes a file system * directory. * @since v10.10.0 */ isDirectory(): boolean; /** * Returns `true` if the `fs.Dirent` object describes a block device. * @since v10.10.0 */ isBlockDevice(): boolean; /** * Returns `true` if the `fs.Dirent` object describes a character device. * @since v10.10.0 */ isCharacterDevice(): boolean; /** * Returns `true` if the `fs.Dirent` object describes a symbolic link. * @since v10.10.0 */ isSymbolicLink(): boolean; /** * Returns `true` if the `fs.Dirent` object describes a first-in-first-out * (FIFO) pipe. * @since v10.10.0 */ isFIFO(): boolean; /** * Returns `true` if the `fs.Dirent` object describes a socket. * @since v10.10.0 */ isSocket(): boolean; /** * The file name that this `fs.Dirent` object refers to. The type of this * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. * @since v10.10.0 */ name: string; /** * The base path that this `fs.Dirent` object refers to. * @since v20.1.0 */ path: string; } /** * A class representing a directory stream. * * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. * * ```js * import { opendir } from 'node:fs/promises'; * * try { * const dir = await opendir('./'); *