Upload via GUI (7543 Dateien)
This commit is contained in:
+2340
File diff suppressed because it is too large
Load Diff
+285
@@ -0,0 +1,285 @@
|
||||
/**
|
||||
* The `timer` module exposes a global API for scheduling functions to
|
||||
* be called at some future period of time. Because the timer functions are
|
||||
* globals, there is no need to import `node:timers` to use the API.
|
||||
*
|
||||
* The timer functions within Node.js implement a similar API as the timers API
|
||||
* provided by Web Browsers but use a different internal implementation that is
|
||||
* built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout).
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/timers.js)
|
||||
*/
|
||||
declare module "timers" {
|
||||
import { Abortable } from "node:events";
|
||||
import * as promises from "node:timers/promises";
|
||||
export interface TimerOptions extends Abortable {
|
||||
/**
|
||||
* Set to `false` to indicate that the scheduled `Timeout`
|
||||
* should not require the Node.js event loop to remain active.
|
||||
* @default true
|
||||
*/
|
||||
ref?: boolean | undefined;
|
||||
}
|
||||
global {
|
||||
namespace NodeJS {
|
||||
/**
|
||||
* This object is created internally and is returned from `setImmediate()`. It
|
||||
* can be passed to `clearImmediate()` in order to cancel the scheduled
|
||||
* actions.
|
||||
*
|
||||
* By default, when an immediate is scheduled, the Node.js event loop will continue
|
||||
* running as long as the immediate is active. The `Immediate` object returned by
|
||||
* `setImmediate()` exports both `immediate.ref()` and `immediate.unref()`
|
||||
* functions that can be used to control this default behavior.
|
||||
*/
|
||||
interface Immediate extends RefCounted, Disposable {
|
||||
/**
|
||||
* If true, the `Immediate` object will keep the Node.js event loop active.
|
||||
* @since v11.0.0
|
||||
*/
|
||||
hasRef(): boolean;
|
||||
/**
|
||||
* When called, requests that the Node.js event loop _not_ exit so long as the
|
||||
* `Immediate` is active. Calling `immediate.ref()` multiple times will have no
|
||||
* effect.
|
||||
*
|
||||
* By default, all `Immediate` objects are "ref'ed", making it normally unnecessary
|
||||
* to call `immediate.ref()` unless `immediate.unref()` had been called previously.
|
||||
* @since v9.7.0
|
||||
* @returns a reference to `immediate`
|
||||
*/
|
||||
ref(): this;
|
||||
/**
|
||||
* When called, the active `Immediate` object will not require the Node.js event
|
||||
* loop to remain active. If there is no other activity keeping the event loop
|
||||
* running, the process may exit before the `Immediate` object's callback is
|
||||
* invoked. Calling `immediate.unref()` multiple times will have no effect.
|
||||
* @since v9.7.0
|
||||
* @returns a reference to `immediate`
|
||||
*/
|
||||
unref(): this;
|
||||
/**
|
||||
* Cancels the immediate. This is similar to calling `clearImmediate()`.
|
||||
* @since v20.5.0, v18.18.0
|
||||
*/
|
||||
[Symbol.dispose](): void;
|
||||
_onImmediate(...args: any[]): void;
|
||||
}
|
||||
// Legacy interface used in Node.js v9 and prior
|
||||
// TODO: remove in a future major version bump
|
||||
/** @deprecated Use `NodeJS.Timeout` instead. */
|
||||
interface Timer extends RefCounted {
|
||||
hasRef(): boolean;
|
||||
refresh(): this;
|
||||
[Symbol.toPrimitive](): number;
|
||||
}
|
||||
/**
|
||||
* This object is created internally and is returned from `setTimeout()` and
|
||||
* `setInterval()`. It can be passed to either `clearTimeout()` or
|
||||
* `clearInterval()` in order to cancel the scheduled actions.
|
||||
*
|
||||
* By default, when a timer is scheduled using either `setTimeout()` or
|
||||
* `setInterval()`, the Node.js event loop will continue running as long as the
|
||||
* timer is active. Each of the `Timeout` objects returned by these functions
|
||||
* export both `timeout.ref()` and `timeout.unref()` functions that can be used to
|
||||
* control this default behavior.
|
||||
*/
|
||||
interface Timeout extends RefCounted, Disposable, Timer {
|
||||
/**
|
||||
* Cancels the timeout.
|
||||
* @since v0.9.1
|
||||
* @legacy Use `clearTimeout()` instead.
|
||||
* @returns a reference to `timeout`
|
||||
*/
|
||||
close(): this;
|
||||
/**
|
||||
* If true, the `Timeout` object will keep the Node.js event loop active.
|
||||
* @since v11.0.0
|
||||
*/
|
||||
hasRef(): boolean;
|
||||
/**
|
||||
* When called, requests that the Node.js event loop _not_ exit so long as the
|
||||
* `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect.
|
||||
*
|
||||
* By default, all `Timeout` objects are "ref'ed", making it normally unnecessary
|
||||
* to call `timeout.ref()` unless `timeout.unref()` had been called previously.
|
||||
* @since v0.9.1
|
||||
* @returns a reference to `timeout`
|
||||
*/
|
||||
ref(): this;
|
||||
/**
|
||||
* Sets the timer's start time to the current time, and reschedules the timer to
|
||||
* call its callback at the previously specified duration adjusted to the current
|
||||
* time. This is useful for refreshing a timer without allocating a new
|
||||
* JavaScript object.
|
||||
*
|
||||
* Using this on a timer that has already called its callback will reactivate the
|
||||
* timer.
|
||||
* @since v10.2.0
|
||||
* @returns a reference to `timeout`
|
||||
*/
|
||||
refresh(): this;
|
||||
/**
|
||||
* When called, the active `Timeout` object will not require the Node.js event loop
|
||||
* to remain active. If there is no other activity keeping the event loop running,
|
||||
* the process may exit before the `Timeout` object's callback is invoked. Calling
|
||||
* `timeout.unref()` multiple times will have no effect.
|
||||
* @since v0.9.1
|
||||
* @returns a reference to `timeout`
|
||||
*/
|
||||
unref(): this;
|
||||
/**
|
||||
* Coerce a `Timeout` to a primitive. The primitive can be used to
|
||||
* clear the `Timeout`. The primitive can only be used in the
|
||||
* same thread where the timeout was created. Therefore, to use it
|
||||
* across `worker_threads` it must first be passed to the correct
|
||||
* thread. This allows enhanced compatibility with browser
|
||||
* `setTimeout()` and `setInterval()` implementations.
|
||||
* @since v14.9.0, v12.19.0
|
||||
*/
|
||||
[Symbol.toPrimitive](): number;
|
||||
/**
|
||||
* Cancels the timeout.
|
||||
* @since v20.5.0, v18.18.0
|
||||
*/
|
||||
[Symbol.dispose](): void;
|
||||
_onTimeout(...args: any[]): void;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Schedules the "immediate" execution of the `callback` after I/O events'
|
||||
* callbacks.
|
||||
*
|
||||
* When multiple calls to `setImmediate()` are made, the `callback` functions are
|
||||
* queued for execution in the order in which they are created. The entire callback
|
||||
* queue is processed every event loop iteration. If an immediate timer is queued
|
||||
* from inside an executing callback, that timer will not be triggered until the
|
||||
* next event loop iteration.
|
||||
*
|
||||
* If `callback` is not a function, a `TypeError` will be thrown.
|
||||
*
|
||||
* This method has a custom variant for promises that is available using
|
||||
* `timersPromises.setImmediate()`.
|
||||
* @since v0.9.1
|
||||
* @param callback The function to call at the end of this turn of
|
||||
* the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout)
|
||||
* @param args Optional arguments to pass when the `callback` is called.
|
||||
* @returns for use with `clearImmediate()`
|
||||
*/
|
||||
function setImmediate<TArgs extends any[]>(
|
||||
callback: (...args: TArgs) => void,
|
||||
...args: TArgs
|
||||
): NodeJS.Immediate;
|
||||
// Allow a single void-accepting argument to be optional in arguments lists.
|
||||
// Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258)
|
||||
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
|
||||
function setImmediate(callback: (_: void) => void): NodeJS.Immediate;
|
||||
namespace setImmediate {
|
||||
import __promisify__ = promises.setImmediate;
|
||||
export { __promisify__ };
|
||||
}
|
||||
/**
|
||||
* Schedules repeated execution of `callback` every `delay` milliseconds.
|
||||
*
|
||||
* When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay`
|
||||
* will be set to `1`. Non-integer delays are truncated to an integer.
|
||||
*
|
||||
* If `callback` is not a function, a `TypeError` will be thrown.
|
||||
*
|
||||
* This method has a custom variant for promises that is available using
|
||||
* `timersPromises.setInterval()`.
|
||||
* @since v0.0.1
|
||||
* @param callback The function to call when the timer elapses.
|
||||
* @param delay The number of milliseconds to wait before calling the
|
||||
* `callback`. **Default:** `1`.
|
||||
* @param args Optional arguments to pass when the `callback` is called.
|
||||
* @returns for use with `clearInterval()`
|
||||
*/
|
||||
function setInterval<TArgs extends any[]>(
|
||||
callback: (...args: TArgs) => void,
|
||||
delay?: number,
|
||||
...args: TArgs
|
||||
): NodeJS.Timeout;
|
||||
// Allow a single void-accepting argument to be optional in arguments lists.
|
||||
// Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258)
|
||||
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
|
||||
function setInterval(callback: (_: void) => void, delay?: number): NodeJS.Timeout;
|
||||
/**
|
||||
* Schedules execution of a one-time `callback` after `delay` milliseconds.
|
||||
*
|
||||
* The `callback` will likely not be invoked in precisely `delay` milliseconds.
|
||||
* Node.js makes no guarantees about the exact timing of when callbacks will fire,
|
||||
* nor of their ordering. The callback will be called as close as possible to the
|
||||
* time specified.
|
||||
*
|
||||
* When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay`
|
||||
* will be set to `1`. Non-integer delays are truncated to an integer.
|
||||
*
|
||||
* If `callback` is not a function, a `TypeError` will be thrown.
|
||||
*
|
||||
* This method has a custom variant for promises that is available using
|
||||
* `timersPromises.setTimeout()`.
|
||||
* @since v0.0.1
|
||||
* @param callback The function to call when the timer elapses.
|
||||
* @param delay The number of milliseconds to wait before calling the
|
||||
* `callback`. **Default:** `1`.
|
||||
* @param args Optional arguments to pass when the `callback` is called.
|
||||
* @returns for use with `clearTimeout()`
|
||||
*/
|
||||
function setTimeout<TArgs extends any[]>(
|
||||
callback: (...args: TArgs) => void,
|
||||
delay?: number,
|
||||
...args: TArgs
|
||||
): NodeJS.Timeout;
|
||||
// Allow a single void-accepting argument to be optional in arguments lists.
|
||||
// Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258)
|
||||
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
|
||||
function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout;
|
||||
namespace setTimeout {
|
||||
import __promisify__ = promises.setTimeout;
|
||||
export { __promisify__ };
|
||||
}
|
||||
/**
|
||||
* Cancels an `Immediate` object created by `setImmediate()`.
|
||||
* @since v0.9.1
|
||||
* @param immediate An `Immediate` object as returned by `setImmediate()`.
|
||||
*/
|
||||
function clearImmediate(immediate: NodeJS.Immediate | undefined): void;
|
||||
/**
|
||||
* Cancels a `Timeout` object created by `setInterval()`.
|
||||
* @since v0.0.1
|
||||
* @param timeout A `Timeout` object as returned by `setInterval()`
|
||||
* or the primitive of the `Timeout` object as a string or a number.
|
||||
*/
|
||||
function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void;
|
||||
/**
|
||||
* Cancels a `Timeout` object created by `setTimeout()`.
|
||||
* @since v0.0.1
|
||||
* @param timeout A `Timeout` object as returned by `setTimeout()`
|
||||
* or the primitive of the `Timeout` object as a string or a number.
|
||||
*/
|
||||
function clearTimeout(timeout: NodeJS.Timeout | string | number | undefined): void;
|
||||
/**
|
||||
* The `queueMicrotask()` method queues a microtask to invoke `callback`. If
|
||||
* `callback` throws an exception, the `process` object `'uncaughtException'`
|
||||
* event will be emitted.
|
||||
*
|
||||
* The microtask queue is managed by V8 and may be used in a similar manner to
|
||||
* the `process.nextTick()` queue, which is managed by Node.js. The
|
||||
* `process.nextTick()` queue is always processed before the microtask queue
|
||||
* within each turn of the Node.js event loop.
|
||||
* @since v11.0.0
|
||||
* @param callback Function to be queued.
|
||||
*/
|
||||
function queueMicrotask(callback: () => void): void;
|
||||
}
|
||||
import clearImmediate = globalThis.clearImmediate;
|
||||
import clearInterval = globalThis.clearInterval;
|
||||
import clearTimeout = globalThis.clearTimeout;
|
||||
import setImmediate = globalThis.setImmediate;
|
||||
import setInterval = globalThis.setInterval;
|
||||
import setTimeout = globalThis.setTimeout;
|
||||
export { clearImmediate, clearInterval, clearTimeout, promises, setImmediate, setInterval, setTimeout };
|
||||
}
|
||||
declare module "node:timers" {
|
||||
export * from "timers";
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* The `timers/promises` API provides an alternative set of timer functions
|
||||
* that return `Promise` objects. The API is accessible via
|
||||
* `require('node:timers/promises')`.
|
||||
*
|
||||
* ```js
|
||||
* import {
|
||||
* setTimeout,
|
||||
* setImmediate,
|
||||
* setInterval,
|
||||
* } from 'node:timers/promises';
|
||||
* ```
|
||||
* @since v15.0.0
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/timers/promises.js)
|
||||
*/
|
||||
declare module "timers/promises" {
|
||||
import { TimerOptions } from "node:timers";
|
||||
/**
|
||||
* ```js
|
||||
* import {
|
||||
* setTimeout,
|
||||
* } from 'node:timers/promises';
|
||||
*
|
||||
* const res = await setTimeout(100, 'result');
|
||||
*
|
||||
* console.log(res); // Prints 'result'
|
||||
* ```
|
||||
* @since v15.0.0
|
||||
* @param delay The number of milliseconds to wait before fulfilling the
|
||||
* promise. **Default:** `1`.
|
||||
* @param value A value with which the promise is fulfilled.
|
||||
*/
|
||||
function setTimeout<T = void>(delay?: number, value?: T, options?: TimerOptions): Promise<T>;
|
||||
/**
|
||||
* ```js
|
||||
* import {
|
||||
* setImmediate,
|
||||
* } from 'node:timers/promises';
|
||||
*
|
||||
* const res = await setImmediate('result');
|
||||
*
|
||||
* console.log(res); // Prints 'result'
|
||||
* ```
|
||||
* @since v15.0.0
|
||||
* @param value A value with which the promise is fulfilled.
|
||||
*/
|
||||
function setImmediate<T = void>(value?: T, options?: TimerOptions): Promise<T>;
|
||||
/**
|
||||
* Returns an async iterator that generates values in an interval of `delay` ms.
|
||||
* If `ref` is `true`, you need to call `next()` of async iterator explicitly
|
||||
* or implicitly to keep the event loop alive.
|
||||
*
|
||||
* ```js
|
||||
* import {
|
||||
* setInterval,
|
||||
* } from 'node:timers/promises';
|
||||
*
|
||||
* const interval = 100;
|
||||
* for await (const startTime of setInterval(interval, Date.now())) {
|
||||
* const now = Date.now();
|
||||
* console.log(now);
|
||||
* if ((now - startTime) > 1000)
|
||||
* break;
|
||||
* }
|
||||
* console.log(Date.now());
|
||||
* ```
|
||||
* @since v15.9.0
|
||||
* @param delay The number of milliseconds to wait between iterations.
|
||||
* **Default:** `1`.
|
||||
* @param value A value with which the iterator returns.
|
||||
*/
|
||||
function setInterval<T = void>(delay?: number, value?: T, options?: TimerOptions): NodeJS.AsyncIterator<T>;
|
||||
interface Scheduler {
|
||||
/**
|
||||
* An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification
|
||||
* being developed as a standard Web Platform API.
|
||||
*
|
||||
* Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent
|
||||
* to calling `timersPromises.setTimeout(delay, undefined, options)` except that
|
||||
* the `ref` option is not supported.
|
||||
*
|
||||
* ```js
|
||||
* import { scheduler } from 'node:timers/promises';
|
||||
*
|
||||
* await scheduler.wait(1000); // Wait one second before continuing
|
||||
* ```
|
||||
* @since v17.3.0, v16.14.0
|
||||
* @experimental
|
||||
* @param delay The number of milliseconds to wait before resolving the
|
||||
* promise.
|
||||
*/
|
||||
wait(delay: number, options?: { signal?: AbortSignal }): Promise<void>;
|
||||
/**
|
||||
* An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification
|
||||
* being developed as a standard Web Platform API.
|
||||
*
|
||||
* Calling `timersPromises.scheduler.yield()` is equivalent to calling
|
||||
* `timersPromises.setImmediate()` with no arguments.
|
||||
* @since v17.3.0, v16.14.0
|
||||
* @experimental
|
||||
*/
|
||||
yield(): Promise<void>;
|
||||
}
|
||||
const scheduler: Scheduler;
|
||||
}
|
||||
declare module "node:timers/promises" {
|
||||
export * from "timers/promises";
|
||||
}
|
||||
+1273
File diff suppressed because it is too large
Load Diff
+197
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* The `node:trace_events` module provides a mechanism to centralize tracing information
|
||||
* generated by V8, Node.js core, and userspace code.
|
||||
*
|
||||
* Tracing can be enabled with the `--trace-event-categories` command-line flag
|
||||
* or by using the `trace_events` module. The `--trace-event-categories` flag
|
||||
* accepts a list of comma-separated category names.
|
||||
*
|
||||
* The available categories are:
|
||||
*
|
||||
* * `node`: An empty placeholder.
|
||||
* * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html) trace data.
|
||||
* The [`async_hooks`](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property.
|
||||
* * `node.bootstrap`: Enables capture of Node.js bootstrap milestones.
|
||||
* * `node.console`: Enables capture of `console.time()` and `console.count()` output.
|
||||
* * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`.
|
||||
* * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`.
|
||||
* * `node.dns.native`: Enables capture of trace data for DNS queries.
|
||||
* * `node.net.native`: Enables capture of trace data for network.
|
||||
* * `node.environment`: Enables capture of Node.js Environment milestones.
|
||||
* * `node.fs.sync`: Enables capture of trace data for file system sync methods.
|
||||
* * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods.
|
||||
* * `node.fs.async`: Enables capture of trace data for file system async methods.
|
||||
* * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods.
|
||||
* * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v24.x/api/perf_hooks.html) measurements.
|
||||
* * `node.perf.usertiming`: Enables capture of only Performance API User Timing
|
||||
* measures and marks.
|
||||
* * `node.perf.timerify`: Enables capture of only Performance API timerify
|
||||
* measurements.
|
||||
* * `node.promises.rejections`: Enables capture of trace data tracking the number
|
||||
* of unhandled Promise rejections and handled-after-rejections.
|
||||
* * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods.
|
||||
* * `v8`: The [V8](https://nodejs.org/docs/latest-v24.x/api/v8.html) events are GC, compiling, and execution related.
|
||||
* * `node.http`: Enables capture of trace data for http request / response.
|
||||
*
|
||||
* By default the `node`, `node.async_hooks`, and `v8` categories are enabled.
|
||||
*
|
||||
* ```bash
|
||||
* node --trace-event-categories v8,node,node.async_hooks server.js
|
||||
* ```
|
||||
*
|
||||
* Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the `--trace-events-enabled` flag _may_ still be
|
||||
* used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default.
|
||||
*
|
||||
* ```bash
|
||||
* node --trace-events-enabled
|
||||
*
|
||||
* # is equivalent to
|
||||
*
|
||||
* node --trace-event-categories v8,node,node.async_hooks
|
||||
* ```
|
||||
*
|
||||
* Alternatively, trace events may be enabled using the `node:trace_events` module:
|
||||
*
|
||||
* ```js
|
||||
* import trace_events from 'node:trace_events';
|
||||
* const tracing = trace_events.createTracing({ categories: ['node.perf'] });
|
||||
* tracing.enable(); // Enable trace event capture for the 'node.perf' category
|
||||
*
|
||||
* // do work
|
||||
*
|
||||
* tracing.disable(); // Disable trace event capture for the 'node.perf' category
|
||||
* ```
|
||||
*
|
||||
* Running Node.js with tracing enabled will produce log files that can be opened
|
||||
* in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome.
|
||||
*
|
||||
* The logging file is by default called `node_trace.${rotation}.log`, where `${rotation}` is an incrementing log-rotation id. The filepath pattern can
|
||||
* be specified with `--trace-event-file-pattern` that accepts a template
|
||||
* string that supports `${rotation}` and `${pid}`:
|
||||
*
|
||||
* ```bash
|
||||
* node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js
|
||||
* ```
|
||||
*
|
||||
* To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers
|
||||
* in your code, such as:
|
||||
*
|
||||
* ```js
|
||||
* process.on('SIGINT', function onSigint() {
|
||||
* console.info('Received SIGINT.');
|
||||
* process.exit(130); // Or applicable exit code depending on OS and signal
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* The tracing system uses the same time source
|
||||
* as the one used by `process.hrtime()`.
|
||||
* However the trace-event timestamps are expressed in microseconds,
|
||||
* unlike `process.hrtime()` which returns nanoseconds.
|
||||
*
|
||||
* The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html#class-worker) threads.
|
||||
* @experimental
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/trace_events.js)
|
||||
*/
|
||||
declare module "trace_events" {
|
||||
/**
|
||||
* The `Tracing` object is used to enable or disable tracing for sets of
|
||||
* categories. Instances are created using the
|
||||
* `trace_events.createTracing()` method.
|
||||
*
|
||||
* When created, the `Tracing` object is disabled. Calling the
|
||||
* `tracing.enable()` method adds the categories to the set of enabled trace
|
||||
* event categories. Calling `tracing.disable()` will remove the categories
|
||||
* from the set of enabled trace event categories.
|
||||
*/
|
||||
interface Tracing {
|
||||
/**
|
||||
* A comma-separated list of the trace event categories covered by this
|
||||
* `Tracing` object.
|
||||
* @since v10.0.0
|
||||
*/
|
||||
readonly categories: string;
|
||||
/**
|
||||
* Disables this `Tracing` object.
|
||||
*
|
||||
* Only trace event categories _not_ covered by other enabled `Tracing`
|
||||
* objects and _not_ specified by the `--trace-event-categories` flag
|
||||
* will be disabled.
|
||||
*
|
||||
* ```js
|
||||
* import trace_events from 'node:trace_events';
|
||||
* const t1 = trace_events.createTracing({ categories: ['node', 'v8'] });
|
||||
* const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] });
|
||||
* t1.enable();
|
||||
* t2.enable();
|
||||
*
|
||||
* // Prints 'node,node.perf,v8'
|
||||
* console.log(trace_events.getEnabledCategories());
|
||||
*
|
||||
* t2.disable(); // Will only disable emission of the 'node.perf' category
|
||||
*
|
||||
* // Prints 'node,v8'
|
||||
* console.log(trace_events.getEnabledCategories());
|
||||
* ```
|
||||
* @since v10.0.0
|
||||
*/
|
||||
disable(): void;
|
||||
/**
|
||||
* Enables this `Tracing` object for the set of categories covered by
|
||||
* the `Tracing` object.
|
||||
* @since v10.0.0
|
||||
*/
|
||||
enable(): void;
|
||||
/**
|
||||
* `true` only if the `Tracing` object has been enabled.
|
||||
* @since v10.0.0
|
||||
*/
|
||||
readonly enabled: boolean;
|
||||
}
|
||||
interface CreateTracingOptions {
|
||||
/**
|
||||
* An array of trace category names. Values included in the array are
|
||||
* coerced to a string when possible. An error will be thrown if the
|
||||
* value cannot be coerced.
|
||||
*/
|
||||
categories: string[];
|
||||
}
|
||||
/**
|
||||
* Creates and returns a `Tracing` object for the given set of `categories`.
|
||||
*
|
||||
* ```js
|
||||
* import trace_events from 'node:trace_events';
|
||||
* const categories = ['node.perf', 'node.async_hooks'];
|
||||
* const tracing = trace_events.createTracing({ categories });
|
||||
* tracing.enable();
|
||||
* // do stuff
|
||||
* tracing.disable();
|
||||
* ```
|
||||
* @since v10.0.0
|
||||
*/
|
||||
function createTracing(options: CreateTracingOptions): Tracing;
|
||||
/**
|
||||
* Returns a comma-separated list of all currently-enabled trace event
|
||||
* categories. The current set of enabled trace event categories is determined
|
||||
* by the _union_ of all currently-enabled `Tracing` objects and any categories
|
||||
* enabled using the `--trace-event-categories` flag.
|
||||
*
|
||||
* Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console.
|
||||
*
|
||||
* ```js
|
||||
* import trace_events from 'node:trace_events';
|
||||
* const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });
|
||||
* const t2 = trace_events.createTracing({ categories: ['node.perf'] });
|
||||
* const t3 = trace_events.createTracing({ categories: ['v8'] });
|
||||
*
|
||||
* t1.enable();
|
||||
* t2.enable();
|
||||
*
|
||||
* console.log(trace_events.getEnabledCategories());
|
||||
* ```
|
||||
* @since v10.0.0
|
||||
*/
|
||||
function getEnabledCategories(): string | undefined;
|
||||
}
|
||||
declare module "node:trace_events" {
|
||||
export * from "trace_events";
|
||||
}
|
||||
+468
@@ -0,0 +1,468 @@
|
||||
declare module "buffer" {
|
||||
global {
|
||||
interface BufferConstructor {
|
||||
// see ../buffer.d.ts for implementation shared with all TypeScript versions
|
||||
|
||||
/**
|
||||
* Allocates a new buffer containing the given {str}.
|
||||
*
|
||||
* @param str String to store in buffer.
|
||||
* @param encoding encoding to use, optional. Default is 'utf8'
|
||||
* @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead.
|
||||
*/
|
||||
new(str: string, encoding?: BufferEncoding): Buffer;
|
||||
/**
|
||||
* Allocates a new buffer of {size} octets.
|
||||
*
|
||||
* @param size count of octets to allocate.
|
||||
* @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`).
|
||||
*/
|
||||
new(size: number): Buffer;
|
||||
/**
|
||||
* Allocates a new buffer containing the given {array} of octets.
|
||||
*
|
||||
* @param array The octets to store.
|
||||
* @deprecated since v10.0.0 - Use `Buffer.from(array)` instead.
|
||||
*/
|
||||
new(array: ArrayLike<number>): Buffer;
|
||||
/**
|
||||
* Produces a Buffer backed by the same allocated memory as
|
||||
* the given {ArrayBuffer}/{SharedArrayBuffer}.
|
||||
*
|
||||
* @param arrayBuffer The ArrayBuffer with which to share memory.
|
||||
* @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead.
|
||||
*/
|
||||
new(arrayBuffer: ArrayBufferLike): Buffer;
|
||||
/**
|
||||
* Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`.
|
||||
* Array entries outside that range will be truncated to fit into it.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
|
||||
* const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
|
||||
* ```
|
||||
*
|
||||
* If `array` is an `Array`-like object (that is, one with a `length` property of
|
||||
* type `number`), it is treated as if it is an array, unless it is a `Buffer` or
|
||||
* a `Uint8Array`. This means all other `TypedArray` variants get treated as an
|
||||
* `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use
|
||||
* `Buffer.copyBytesFrom()`.
|
||||
*
|
||||
* A `TypeError` will be thrown if `array` is not an `Array` or another type
|
||||
* appropriate for `Buffer.from()` variants.
|
||||
*
|
||||
* `Buffer.from(array)` and `Buffer.from(string)` may also use the internal
|
||||
* `Buffer` pool like `Buffer.allocUnsafe()` does.
|
||||
* @since v5.10.0
|
||||
*/
|
||||
from(array: WithImplicitCoercion<ArrayLike<number>>): Buffer;
|
||||
/**
|
||||
* This creates a view of the `ArrayBuffer` without copying the underlying
|
||||
* memory. For example, when passed a reference to the `.buffer` property of a
|
||||
* `TypedArray` instance, the newly created `Buffer` will share the same
|
||||
* allocated memory as the `TypedArray`'s underlying `ArrayBuffer`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const arr = new Uint16Array(2);
|
||||
*
|
||||
* arr[0] = 5000;
|
||||
* arr[1] = 4000;
|
||||
*
|
||||
* // Shares memory with `arr`.
|
||||
* const buf = Buffer.from(arr.buffer);
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 88 13 a0 0f>
|
||||
*
|
||||
* // Changing the original Uint16Array changes the Buffer also.
|
||||
* arr[1] = 6000;
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 88 13 70 17>
|
||||
* ```
|
||||
*
|
||||
* The optional `byteOffset` and `length` arguments specify a memory range within
|
||||
* the `arrayBuffer` that will be shared by the `Buffer`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const ab = new ArrayBuffer(10);
|
||||
* const buf = Buffer.from(ab, 0, 2);
|
||||
*
|
||||
* console.log(buf.length);
|
||||
* // Prints: 2
|
||||
* ```
|
||||
*
|
||||
* A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a
|
||||
* `SharedArrayBuffer` or another type appropriate for `Buffer.from()`
|
||||
* variants.
|
||||
*
|
||||
* It is important to remember that a backing `ArrayBuffer` can cover a range
|
||||
* of memory that extends beyond the bounds of a `TypedArray` view. A new
|
||||
* `Buffer` created using the `buffer` property of a `TypedArray` may extend
|
||||
* beyond the range of the `TypedArray`:
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
|
||||
* const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
|
||||
* console.log(arrA.buffer === arrB.buffer); // true
|
||||
*
|
||||
* const buf = Buffer.from(arrB.buffer);
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 63 64 65 66>
|
||||
* ```
|
||||
* @since v5.10.0
|
||||
* @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the
|
||||
* `.buffer` property of a `TypedArray`.
|
||||
* @param byteOffset Index of first byte to expose. **Default:** `0`.
|
||||
* @param length Number of bytes to expose. **Default:**
|
||||
* `arrayBuffer.byteLength - byteOffset`.
|
||||
*/
|
||||
from(
|
||||
arrayBuffer: WithImplicitCoercion<ArrayBufferLike>,
|
||||
byteOffset?: number,
|
||||
length?: number,
|
||||
): Buffer;
|
||||
/**
|
||||
* Creates a new `Buffer` containing `string`. The `encoding` parameter identifies
|
||||
* the character encoding to be used when converting `string` into bytes.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf1 = Buffer.from('this is a tést');
|
||||
* const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
|
||||
*
|
||||
* console.log(buf1.toString());
|
||||
* // Prints: this is a tést
|
||||
* console.log(buf2.toString());
|
||||
* // Prints: this is a tést
|
||||
* console.log(buf1.toString('latin1'));
|
||||
* // Prints: this is a tést
|
||||
* ```
|
||||
*
|
||||
* A `TypeError` will be thrown if `string` is not a string or another type
|
||||
* appropriate for `Buffer.from()` variants.
|
||||
*
|
||||
* `Buffer.from(string)` may also use the internal `Buffer` pool like
|
||||
* `Buffer.allocUnsafe()` does.
|
||||
* @since v5.10.0
|
||||
* @param string A string to encode.
|
||||
* @param encoding The encoding of `string`. **Default:** `'utf8'`.
|
||||
*/
|
||||
from(string: WithImplicitCoercion<string>, encoding?: BufferEncoding): Buffer;
|
||||
from(arrayOrString: WithImplicitCoercion<ArrayLike<number> | string>): Buffer;
|
||||
/**
|
||||
* Creates a new Buffer using the passed {data}
|
||||
* @param values to create a new Buffer
|
||||
*/
|
||||
of(...items: number[]): Buffer;
|
||||
/**
|
||||
* Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together.
|
||||
*
|
||||
* If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned.
|
||||
*
|
||||
* If `totalLength` is not provided, it is calculated from the `Buffer` instances
|
||||
* in `list` by adding their lengths.
|
||||
*
|
||||
* If `totalLength` is provided, it is coerced to an unsigned integer. If the
|
||||
* combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is
|
||||
* truncated to `totalLength`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* // Create a single `Buffer` from a list of three `Buffer` instances.
|
||||
*
|
||||
* const buf1 = Buffer.alloc(10);
|
||||
* const buf2 = Buffer.alloc(14);
|
||||
* const buf3 = Buffer.alloc(18);
|
||||
* const totalLength = buf1.length + buf2.length + buf3.length;
|
||||
*
|
||||
* console.log(totalLength);
|
||||
* // Prints: 42
|
||||
*
|
||||
* const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
|
||||
*
|
||||
* console.log(bufA);
|
||||
* // Prints: <Buffer 00 00 00 00 ...>
|
||||
* console.log(bufA.length);
|
||||
* // Prints: 42
|
||||
* ```
|
||||
*
|
||||
* `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does.
|
||||
* @since v0.7.11
|
||||
* @param list List of `Buffer` or {@link Uint8Array} instances to concatenate.
|
||||
* @param totalLength Total length of the `Buffer` instances in `list` when concatenated.
|
||||
*/
|
||||
concat(list: readonly Uint8Array[], totalLength?: number): Buffer;
|
||||
/**
|
||||
* Copies the underlying memory of `view` into a new `Buffer`.
|
||||
*
|
||||
* ```js
|
||||
* const u16 = new Uint16Array([0, 0xffff]);
|
||||
* const buf = Buffer.copyBytesFrom(u16, 1, 1);
|
||||
* u16[1] = 0;
|
||||
* console.log(buf.length); // 2
|
||||
* console.log(buf[0]); // 255
|
||||
* console.log(buf[1]); // 255
|
||||
* ```
|
||||
* @since v19.8.0
|
||||
* @param view The {TypedArray} to copy.
|
||||
* @param [offset=0] The starting offset within `view`.
|
||||
* @param [length=view.length - offset] The number of elements from `view` to copy.
|
||||
*/
|
||||
copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer;
|
||||
/**
|
||||
* Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.alloc(5);
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 00 00 00 00 00>
|
||||
* ```
|
||||
*
|
||||
* If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown.
|
||||
*
|
||||
* If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.alloc(5, 'a');
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 61 61 61 61 61>
|
||||
* ```
|
||||
*
|
||||
* If both `fill` and `encoding` are specified, the allocated `Buffer` will be
|
||||
* initialized by calling `buf.fill(fill, encoding)`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
|
||||
* ```
|
||||
*
|
||||
* Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance
|
||||
* contents will never contain sensitive data from previous allocations, including
|
||||
* data that might not have been allocated for `Buffer`s.
|
||||
*
|
||||
* A `TypeError` will be thrown if `size` is not a number.
|
||||
* @since v5.10.0
|
||||
* @param size The desired length of the new `Buffer`.
|
||||
* @param [fill=0] A value to pre-fill the new `Buffer` with.
|
||||
* @param [encoding='utf8'] If `fill` is a string, this is its encoding.
|
||||
*/
|
||||
alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer;
|
||||
/**
|
||||
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown.
|
||||
*
|
||||
* The underlying memory for `Buffer` instances created in this way is _not_
|
||||
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.allocUnsafe(10);
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
|
||||
*
|
||||
* buf.fill(0);
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
|
||||
* ```
|
||||
*
|
||||
* A `TypeError` will be thrown if `size` is not a number.
|
||||
*
|
||||
* The `Buffer` module pre-allocates an internal `Buffer` instance of
|
||||
* size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`,
|
||||
* and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two).
|
||||
*
|
||||
* Use of this pre-allocated internal memory pool is a key difference between
|
||||
* calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
|
||||
* Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less
|
||||
* than or equal to half `Buffer.poolSize`. The
|
||||
* difference is subtle but can be important when an application requires the
|
||||
* additional performance that `Buffer.allocUnsafe()` provides.
|
||||
* @since v5.10.0
|
||||
* @param size The desired length of the new `Buffer`.
|
||||
*/
|
||||
allocUnsafe(size: number): Buffer;
|
||||
/**
|
||||
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if
|
||||
* `size` is 0.
|
||||
*
|
||||
* The underlying memory for `Buffer` instances created in this way is _not_
|
||||
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize
|
||||
* such `Buffer` instances with zeroes.
|
||||
*
|
||||
* When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
|
||||
* allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This
|
||||
* allows applications to avoid the garbage collection overhead of creating many
|
||||
* individually allocated `Buffer` instances. This approach improves both
|
||||
* performance and memory usage by eliminating the need to track and clean up as
|
||||
* many individual `ArrayBuffer` objects.
|
||||
*
|
||||
* However, in the case where a developer may need to retain a small chunk of
|
||||
* memory from a pool for an indeterminate amount of time, it may be appropriate
|
||||
* to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and
|
||||
* then copying out the relevant bits.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* // Need to keep around a few small chunks of memory.
|
||||
* const store = [];
|
||||
*
|
||||
* socket.on('readable', () => {
|
||||
* let data;
|
||||
* while (null !== (data = readable.read())) {
|
||||
* // Allocate for retained data.
|
||||
* const sb = Buffer.allocUnsafeSlow(10);
|
||||
*
|
||||
* // Copy the data into the new allocation.
|
||||
* data.copy(sb, 0, 0, 10);
|
||||
*
|
||||
* store.push(sb);
|
||||
* }
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* A `TypeError` will be thrown if `size` is not a number.
|
||||
* @since v5.12.0
|
||||
* @param size The desired length of the new `Buffer`.
|
||||
*/
|
||||
allocUnsafeSlow(size: number): Buffer;
|
||||
}
|
||||
interface Buffer extends Uint8Array {
|
||||
// see ../buffer.d.ts for implementation shared with all TypeScript versions
|
||||
|
||||
/**
|
||||
* Returns a new `Buffer` that references the same memory as the original, but
|
||||
* offset and cropped by the `start` and `end` indices.
|
||||
*
|
||||
* This method is not compatible with the `Uint8Array.prototype.slice()`,
|
||||
* which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.from('buffer');
|
||||
*
|
||||
* const copiedBuf = Uint8Array.prototype.slice.call(buf);
|
||||
* copiedBuf[0]++;
|
||||
* console.log(copiedBuf.toString());
|
||||
* // Prints: cuffer
|
||||
*
|
||||
* console.log(buf.toString());
|
||||
* // Prints: buffer
|
||||
*
|
||||
* // With buf.slice(), the original buffer is modified.
|
||||
* const notReallyCopiedBuf = buf.slice();
|
||||
* notReallyCopiedBuf[0]++;
|
||||
* console.log(notReallyCopiedBuf.toString());
|
||||
* // Prints: cuffer
|
||||
* console.log(buf.toString());
|
||||
* // Also prints: cuffer (!)
|
||||
* ```
|
||||
* @since v0.3.0
|
||||
* @deprecated Use `subarray` instead.
|
||||
* @param [start=0] Where the new `Buffer` will start.
|
||||
* @param [end=buf.length] Where the new `Buffer` will end (not inclusive).
|
||||
*/
|
||||
slice(start?: number, end?: number): Buffer;
|
||||
/**
|
||||
* Returns a new `Buffer` that references the same memory as the original, but
|
||||
* offset and cropped by the `start` and `end` indices.
|
||||
*
|
||||
* Specifying `end` greater than `buf.length` will return the same result as
|
||||
* that of `end` equal to `buf.length`.
|
||||
*
|
||||
* This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray).
|
||||
*
|
||||
* Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
|
||||
* // from the original `Buffer`.
|
||||
*
|
||||
* const buf1 = Buffer.allocUnsafe(26);
|
||||
*
|
||||
* for (let i = 0; i < 26; i++) {
|
||||
* // 97 is the decimal ASCII value for 'a'.
|
||||
* buf1[i] = i + 97;
|
||||
* }
|
||||
*
|
||||
* const buf2 = buf1.subarray(0, 3);
|
||||
*
|
||||
* console.log(buf2.toString('ascii', 0, buf2.length));
|
||||
* // Prints: abc
|
||||
*
|
||||
* buf1[0] = 33;
|
||||
*
|
||||
* console.log(buf2.toString('ascii', 0, buf2.length));
|
||||
* // Prints: !bc
|
||||
* ```
|
||||
*
|
||||
* Specifying negative indexes causes the slice to be generated relative to the
|
||||
* end of `buf` rather than the beginning.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.from('buffer');
|
||||
*
|
||||
* console.log(buf.subarray(-6, -1).toString());
|
||||
* // Prints: buffe
|
||||
* // (Equivalent to buf.subarray(0, 5).)
|
||||
*
|
||||
* console.log(buf.subarray(-6, -2).toString());
|
||||
* // Prints: buff
|
||||
* // (Equivalent to buf.subarray(0, 4).)
|
||||
*
|
||||
* console.log(buf.subarray(-5, -2).toString());
|
||||
* // Prints: uff
|
||||
* // (Equivalent to buf.subarray(1, 4).)
|
||||
* ```
|
||||
* @since v3.0.0
|
||||
* @param [start=0] Where the new `Buffer` will start.
|
||||
* @param [end=buf.length] Where the new `Buffer` will end (not inclusive).
|
||||
*/
|
||||
subarray(start?: number, end?: number): Buffer;
|
||||
}
|
||||
/**
|
||||
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
|
||||
* TypeScript versions earlier than 5.7.
|
||||
*/
|
||||
type NonSharedBuffer = Buffer;
|
||||
/**
|
||||
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
|
||||
* TypeScript versions earlier than 5.7.
|
||||
*/
|
||||
type AllowSharedBuffer = Buffer;
|
||||
}
|
||||
/** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */
|
||||
var SlowBuffer: {
|
||||
/** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */
|
||||
new(size: number): Buffer;
|
||||
prototype: Buffer;
|
||||
};
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
// Interface declaration for Float16Array, required in @types/node v24+.
|
||||
// These definitions are specific to TS <=5.6.
|
||||
|
||||
// This needs all of the "common" properties/methods of the TypedArrays,
|
||||
// otherwise the type unions `TypedArray` and `ArrayBufferView` will be
|
||||
// empty objects.
|
||||
interface Float16Array extends Pick<Float32Array, typeof Symbol.iterator | "entries" | "keys" | "values"> {
|
||||
readonly BYTES_PER_ELEMENT: number;
|
||||
readonly buffer: ArrayBufferLike;
|
||||
readonly byteLength: number;
|
||||
readonly byteOffset: number;
|
||||
readonly length: number;
|
||||
readonly [Symbol.toStringTag]: "Float16Array";
|
||||
at(index: number): number | undefined;
|
||||
copyWithin(target: number, start: number, end?: number): this;
|
||||
every(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): boolean;
|
||||
fill(value: number, start?: number, end?: number): this;
|
||||
filter(predicate: (value: number, index: number, array: Float16Array) => any, thisArg?: any): Float16Array;
|
||||
find(predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any): number | undefined;
|
||||
findIndex(predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any): number;
|
||||
findLast<S extends number>(
|
||||
predicate: (value: number, index: number, array: Float16Array) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (value: number, index: number, array: Float16Array) => unknown,
|
||||
thisArg?: any,
|
||||
): number | undefined;
|
||||
findLastIndex(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): number;
|
||||
forEach(callbackfn: (value: number, index: number, array: Float16Array) => void, thisArg?: any): void;
|
||||
includes(searchElement: number, fromIndex?: number): boolean;
|
||||
indexOf(searchElement: number, fromIndex?: number): number;
|
||||
join(separator?: string): string;
|
||||
lastIndexOf(searchElement: number, fromIndex?: number): number;
|
||||
map(callbackfn: (value: number, index: number, array: Float16Array) => number, thisArg?: any): Float16Array;
|
||||
reduce(
|
||||
callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number,
|
||||
): number;
|
||||
reduce(
|
||||
callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number,
|
||||
initialValue: number,
|
||||
): number;
|
||||
reduce<U>(
|
||||
callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float16Array) => U,
|
||||
initialValue: U,
|
||||
): U;
|
||||
reduceRight(
|
||||
callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number,
|
||||
): number;
|
||||
reduceRight(
|
||||
callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number,
|
||||
initialValue: number,
|
||||
): number;
|
||||
reduceRight<U>(
|
||||
callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float16Array) => U,
|
||||
initialValue: U,
|
||||
): U;
|
||||
reverse(): Float16Array;
|
||||
set(array: ArrayLike<number>, offset?: number): void;
|
||||
slice(start?: number, end?: number): Float16Array;
|
||||
some(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): boolean;
|
||||
sort(compareFn?: (a: number, b: number) => number): this;
|
||||
subarray(begin?: number, end?: number): Float16Array;
|
||||
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
|
||||
toReversed(): Float16Array;
|
||||
toSorted(compareFn?: (a: number, b: number) => number): Float16Array;
|
||||
toString(): string;
|
||||
valueOf(): Float16Array;
|
||||
with(index: number, value: number): Float16Array;
|
||||
[index: number]: number;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
export {}; // Make this a module
|
||||
|
||||
declare global {
|
||||
namespace NodeJS {
|
||||
type TypedArray =
|
||||
| Uint8Array
|
||||
| Uint8ClampedArray
|
||||
| Uint16Array
|
||||
| Uint32Array
|
||||
| Int8Array
|
||||
| Int16Array
|
||||
| Int32Array
|
||||
| BigUint64Array
|
||||
| BigInt64Array
|
||||
| Float16Array
|
||||
| Float32Array
|
||||
| Float64Array;
|
||||
type ArrayBufferView = TypedArray | DataView;
|
||||
|
||||
type NonSharedUint8Array = Uint8Array;
|
||||
type NonSharedUint8ClampedArray = Uint8ClampedArray;
|
||||
type NonSharedUint16Array = Uint16Array;
|
||||
type NonSharedUint32Array = Uint32Array;
|
||||
type NonSharedInt8Array = Int8Array;
|
||||
type NonSharedInt16Array = Int16Array;
|
||||
type NonSharedInt32Array = Int32Array;
|
||||
type NonSharedBigUint64Array = BigUint64Array;
|
||||
type NonSharedBigInt64Array = BigInt64Array;
|
||||
type NonSharedFloat16Array = Float16Array;
|
||||
type NonSharedFloat32Array = Float32Array;
|
||||
type NonSharedFloat64Array = Float64Array;
|
||||
type NonSharedDataView = DataView;
|
||||
type NonSharedTypedArray = TypedArray;
|
||||
type NonSharedArrayBufferView = ArrayBufferView;
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* License for programmatically and manually incorporated
|
||||
* documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc
|
||||
*
|
||||
* Copyright Node.js contributors. All rights reserved.
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to
|
||||
* deal in the Software without restriction, including without limitation the
|
||||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
* sell copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
// NOTE: These definitions support Node.js and TypeScript 5.2 through 5.6.
|
||||
|
||||
// Reference required TypeScript libraries:
|
||||
/// <reference lib="es2020" />
|
||||
/// <reference lib="esnext.disposable" />
|
||||
|
||||
// TypeScript library polyfills required for TypeScript <=5.6:
|
||||
/// <reference path="./compatibility/float16array.d.ts" />
|
||||
|
||||
// Iterator definitions required for compatibility with TypeScript <5.6:
|
||||
/// <reference path="../compatibility/iterators.d.ts" />
|
||||
|
||||
// Definitions for Node.js modules specific to TypeScript <=5.6:
|
||||
/// <reference path="./globals.typedarray.d.ts" />
|
||||
/// <reference path="./buffer.buffer.d.ts" />
|
||||
|
||||
// Definitions for Node.js modules that are not specific to any version of TypeScript:
|
||||
/// <reference path="../globals.d.ts" />
|
||||
/// <reference path="../web-globals/abortcontroller.d.ts" />
|
||||
/// <reference path="../web-globals/crypto.d.ts" />
|
||||
/// <reference path="../web-globals/domexception.d.ts" />
|
||||
/// <reference path="../web-globals/events.d.ts" />
|
||||
/// <reference path="../web-globals/fetch.d.ts" />
|
||||
/// <reference path="../web-globals/navigator.d.ts" />
|
||||
/// <reference path="../web-globals/storage.d.ts" />
|
||||
/// <reference path="../web-globals/streams.d.ts" />
|
||||
/// <reference path="../assert.d.ts" />
|
||||
/// <reference path="../assert/strict.d.ts" />
|
||||
/// <reference path="../async_hooks.d.ts" />
|
||||
/// <reference path="../buffer.d.ts" />
|
||||
/// <reference path="../child_process.d.ts" />
|
||||
/// <reference path="../cluster.d.ts" />
|
||||
/// <reference path="../console.d.ts" />
|
||||
/// <reference path="../constants.d.ts" />
|
||||
/// <reference path="../crypto.d.ts" />
|
||||
/// <reference path="../dgram.d.ts" />
|
||||
/// <reference path="../diagnostics_channel.d.ts" />
|
||||
/// <reference path="../dns.d.ts" />
|
||||
/// <reference path="../dns/promises.d.ts" />
|
||||
/// <reference path="../domain.d.ts" />
|
||||
/// <reference path="../events.d.ts" />
|
||||
/// <reference path="../fs.d.ts" />
|
||||
/// <reference path="../fs/promises.d.ts" />
|
||||
/// <reference path="../http.d.ts" />
|
||||
/// <reference path="../http2.d.ts" />
|
||||
/// <reference path="../https.d.ts" />
|
||||
/// <reference path="../inspector.d.ts" />
|
||||
/// <reference path="../inspector.generated.d.ts" />
|
||||
/// <reference path="../module.d.ts" />
|
||||
/// <reference path="../net.d.ts" />
|
||||
/// <reference path="../os.d.ts" />
|
||||
/// <reference path="../path.d.ts" />
|
||||
/// <reference path="../perf_hooks.d.ts" />
|
||||
/// <reference path="../process.d.ts" />
|
||||
/// <reference path="../punycode.d.ts" />
|
||||
/// <reference path="../querystring.d.ts" />
|
||||
/// <reference path="../readline.d.ts" />
|
||||
/// <reference path="../readline/promises.d.ts" />
|
||||
/// <reference path="../repl.d.ts" />
|
||||
/// <reference path="../sea.d.ts" />
|
||||
/// <reference path="../sqlite.d.ts" />
|
||||
/// <reference path="../stream.d.ts" />
|
||||
/// <reference path="../stream/promises.d.ts" />
|
||||
/// <reference path="../stream/consumers.d.ts" />
|
||||
/// <reference path="../stream/web.d.ts" />
|
||||
/// <reference path="../string_decoder.d.ts" />
|
||||
/// <reference path="../test.d.ts" />
|
||||
/// <reference path="../timers.d.ts" />
|
||||
/// <reference path="../timers/promises.d.ts" />
|
||||
/// <reference path="../tls.d.ts" />
|
||||
/// <reference path="../trace_events.d.ts" />
|
||||
/// <reference path="../tty.d.ts" />
|
||||
/// <reference path="../url.d.ts" />
|
||||
/// <reference path="../util.d.ts" />
|
||||
/// <reference path="../v8.d.ts" />
|
||||
/// <reference path="../vm.d.ts" />
|
||||
/// <reference path="../wasi.d.ts" />
|
||||
/// <reference path="../worker_threads.d.ts" />
|
||||
/// <reference path="../zlib.d.ts" />
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
// Interface declaration for Float16Array, required in @types/node v24+.
|
||||
// These definitions are specific to TS 5.7.
|
||||
|
||||
// This needs all of the "common" properties/methods of the TypedArrays,
|
||||
// otherwise the type unions `TypedArray` and `ArrayBufferView` will be
|
||||
// empty objects.
|
||||
interface Float16Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> {
|
||||
readonly BYTES_PER_ELEMENT: number;
|
||||
readonly buffer: TArrayBuffer;
|
||||
readonly byteLength: number;
|
||||
readonly byteOffset: number;
|
||||
readonly length: number;
|
||||
readonly [Symbol.toStringTag]: "Float16Array";
|
||||
at(index: number): number | undefined;
|
||||
copyWithin(target: number, start: number, end?: number): this;
|
||||
entries(): ArrayIterator<[number, number]>;
|
||||
every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean;
|
||||
fill(value: number, start?: number, end?: number): this;
|
||||
filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Float16Array<ArrayBuffer>;
|
||||
find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined;
|
||||
findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number;
|
||||
findLast<S extends number>(
|
||||
predicate: (value: number, index: number, array: this) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined;
|
||||
findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number;
|
||||
forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void;
|
||||
includes(searchElement: number, fromIndex?: number): boolean;
|
||||
indexOf(searchElement: number, fromIndex?: number): number;
|
||||
join(separator?: string): string;
|
||||
keys(): ArrayIterator<number>;
|
||||
lastIndexOf(searchElement: number, fromIndex?: number): number;
|
||||
map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Float16Array<ArrayBuffer>;
|
||||
reduce(
|
||||
callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number,
|
||||
): number;
|
||||
reduce(
|
||||
callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number,
|
||||
initialValue: number,
|
||||
): number;
|
||||
reduce<U>(
|
||||
callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U,
|
||||
initialValue: U,
|
||||
): U;
|
||||
reduceRight(
|
||||
callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number,
|
||||
): number;
|
||||
reduceRight(
|
||||
callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number,
|
||||
initialValue: number,
|
||||
): number;
|
||||
reduceRight<U>(
|
||||
callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U,
|
||||
initialValue: U,
|
||||
): U;
|
||||
reverse(): this;
|
||||
set(array: ArrayLike<number>, offset?: number): void;
|
||||
slice(start?: number, end?: number): Float16Array<ArrayBuffer>;
|
||||
some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean;
|
||||
sort(compareFn?: (a: number, b: number) => number): this;
|
||||
subarray(begin?: number, end?: number): Float16Array<TArrayBuffer>;
|
||||
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
|
||||
toReversed(): Float16Array<ArrayBuffer>;
|
||||
toSorted(compareFn?: (a: number, b: number) => number): Float16Array<ArrayBuffer>;
|
||||
toString(): string;
|
||||
valueOf(): this;
|
||||
values(): ArrayIterator<number>;
|
||||
with(index: number, value: number): Float16Array<ArrayBuffer>;
|
||||
[Symbol.iterator](): ArrayIterator<number>;
|
||||
[index: number]: number;
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* License for programmatically and manually incorporated
|
||||
* documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc
|
||||
*
|
||||
* Copyright Node.js contributors. All rights reserved.
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to
|
||||
* deal in the Software without restriction, including without limitation the
|
||||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
* sell copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
// NOTE: These definitions support Node.js and TypeScript 5.7.
|
||||
|
||||
// Reference required TypeScript libraries:
|
||||
/// <reference lib="es2020" />
|
||||
/// <reference lib="esnext.disposable" />
|
||||
|
||||
// TypeScript library polyfills required for TypeScript 5.7:
|
||||
/// <reference path="./compatibility/float16array.d.ts" />
|
||||
|
||||
// Iterator definitions required for compatibility with TypeScript <5.6:
|
||||
/// <reference path="../compatibility/iterators.d.ts" />
|
||||
|
||||
// Definitions for Node.js modules specific to TypeScript 5.7+:
|
||||
/// <reference path="../globals.typedarray.d.ts" />
|
||||
/// <reference path="../buffer.buffer.d.ts" />
|
||||
|
||||
// Definitions for Node.js modules that are not specific to any version of TypeScript:
|
||||
/// <reference path="../globals.d.ts" />
|
||||
/// <reference path="../web-globals/abortcontroller.d.ts" />
|
||||
/// <reference path="../web-globals/crypto.d.ts" />
|
||||
/// <reference path="../web-globals/domexception.d.ts" />
|
||||
/// <reference path="../web-globals/events.d.ts" />
|
||||
/// <reference path="../web-globals/fetch.d.ts" />
|
||||
/// <reference path="../web-globals/navigator.d.ts" />
|
||||
/// <reference path="../web-globals/storage.d.ts" />
|
||||
/// <reference path="../web-globals/streams.d.ts" />
|
||||
/// <reference path="../assert.d.ts" />
|
||||
/// <reference path="../assert/strict.d.ts" />
|
||||
/// <reference path="../async_hooks.d.ts" />
|
||||
/// <reference path="../buffer.d.ts" />
|
||||
/// <reference path="../child_process.d.ts" />
|
||||
/// <reference path="../cluster.d.ts" />
|
||||
/// <reference path="../console.d.ts" />
|
||||
/// <reference path="../constants.d.ts" />
|
||||
/// <reference path="../crypto.d.ts" />
|
||||
/// <reference path="../dgram.d.ts" />
|
||||
/// <reference path="../diagnostics_channel.d.ts" />
|
||||
/// <reference path="../dns.d.ts" />
|
||||
/// <reference path="../dns/promises.d.ts" />
|
||||
/// <reference path="../domain.d.ts" />
|
||||
/// <reference path="../events.d.ts" />
|
||||
/// <reference path="../fs.d.ts" />
|
||||
/// <reference path="../fs/promises.d.ts" />
|
||||
/// <reference path="../http.d.ts" />
|
||||
/// <reference path="../http2.d.ts" />
|
||||
/// <reference path="../https.d.ts" />
|
||||
/// <reference path="../inspector.d.ts" />
|
||||
/// <reference path="../inspector.generated.d.ts" />
|
||||
/// <reference path="../module.d.ts" />
|
||||
/// <reference path="../net.d.ts" />
|
||||
/// <reference path="../os.d.ts" />
|
||||
/// <reference path="../path.d.ts" />
|
||||
/// <reference path="../perf_hooks.d.ts" />
|
||||
/// <reference path="../process.d.ts" />
|
||||
/// <reference path="../punycode.d.ts" />
|
||||
/// <reference path="../querystring.d.ts" />
|
||||
/// <reference path="../readline.d.ts" />
|
||||
/// <reference path="../readline/promises.d.ts" />
|
||||
/// <reference path="../repl.d.ts" />
|
||||
/// <reference path="../sea.d.ts" />
|
||||
/// <reference path="../sqlite.d.ts" />
|
||||
/// <reference path="../stream.d.ts" />
|
||||
/// <reference path="../stream/promises.d.ts" />
|
||||
/// <reference path="../stream/consumers.d.ts" />
|
||||
/// <reference path="../stream/web.d.ts" />
|
||||
/// <reference path="../string_decoder.d.ts" />
|
||||
/// <reference path="../test.d.ts" />
|
||||
/// <reference path="../timers.d.ts" />
|
||||
/// <reference path="../timers/promises.d.ts" />
|
||||
/// <reference path="../tls.d.ts" />
|
||||
/// <reference path="../trace_events.d.ts" />
|
||||
/// <reference path="../tty.d.ts" />
|
||||
/// <reference path="../url.d.ts" />
|
||||
/// <reference path="../util.d.ts" />
|
||||
/// <reference path="../v8.d.ts" />
|
||||
/// <reference path="../vm.d.ts" />
|
||||
/// <reference path="../wasi.d.ts" />
|
||||
/// <reference path="../worker_threads.d.ts" />
|
||||
/// <reference path="../zlib.d.ts" />
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, it will not be necessary or possible to use this module
|
||||
* directly. However, it can be accessed using:
|
||||
*
|
||||
* ```js
|
||||
* import tty from 'node:tty';
|
||||
* ```
|
||||
*
|
||||
* When Node.js detects that it is being run with a text terminal ("TTY")
|
||||
* attached, `process.stdin` will, by default, be initialized as an instance of `tty.ReadStream` and both `process.stdout` and `process.stderr` will, by
|
||||
* default, be instances of `tty.WriteStream`. The preferred method of determining
|
||||
* whether Node.js is being run within a TTY context is to check that the value of
|
||||
* the `process.stdout.isTTY` property is `true`:
|
||||
*
|
||||
* ```console
|
||||
* $ node -p -e "Boolean(process.stdout.isTTY)"
|
||||
* true
|
||||
* $ node -p -e "Boolean(process.stdout.isTTY)" | cat
|
||||
* false
|
||||
* ```
|
||||
*
|
||||
* In most cases, there should be little to no reason for an application to
|
||||
* manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes.
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tty.js)
|
||||
*/
|
||||
declare module "tty" {
|
||||
import * as net from "node:net";
|
||||
/**
|
||||
* The `tty.isatty()` method returns `true` if the given `fd` is associated with
|
||||
* a TTY and `false` if it is not, including whenever `fd` is not a non-negative
|
||||
* integer.
|
||||
* @since v0.5.8
|
||||
* @param fd A numeric file descriptor
|
||||
*/
|
||||
function isatty(fd: number): boolean;
|
||||
/**
|
||||
* Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js
|
||||
* process and there should be no reason to create additional instances.
|
||||
* @since v0.5.8
|
||||
*/
|
||||
class ReadStream extends net.Socket {
|
||||
constructor(fd: number, options?: net.SocketConstructorOpts);
|
||||
/**
|
||||
* A `boolean` that is `true` if the TTY is currently configured to operate as a
|
||||
* raw device.
|
||||
*
|
||||
* This flag is always `false` when a process starts, even if the terminal is
|
||||
* operating in raw mode. Its value will change with subsequent calls to `setRawMode`.
|
||||
* @since v0.7.7
|
||||
*/
|
||||
isRaw: boolean;
|
||||
/**
|
||||
* Allows configuration of `tty.ReadStream` so that it operates as a raw device.
|
||||
*
|
||||
* When in raw mode, input is always available character-by-character, not
|
||||
* including modifiers. Additionally, all special processing of characters by the
|
||||
* terminal is disabled, including echoing input
|
||||
* characters. Ctrl+C will no longer cause a `SIGINT` when
|
||||
* in this mode.
|
||||
* @since v0.7.7
|
||||
* @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw`
|
||||
* property will be set to the resulting mode.
|
||||
* @return The read stream instance.
|
||||
*/
|
||||
setRawMode(mode: boolean): this;
|
||||
/**
|
||||
* A `boolean` that is always `true` for `tty.ReadStream` instances.
|
||||
* @since v0.5.8
|
||||
*/
|
||||
isTTY: boolean;
|
||||
}
|
||||
/**
|
||||
* -1 - to the left from cursor
|
||||
* 0 - the entire line
|
||||
* 1 - to the right from cursor
|
||||
*/
|
||||
type Direction = -1 | 0 | 1;
|
||||
/**
|
||||
* Represents the writable side of a TTY. In normal circumstances, `process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there
|
||||
* should be no reason to create additional instances.
|
||||
* @since v0.5.8
|
||||
*/
|
||||
class WriteStream extends net.Socket {
|
||||
constructor(fd: number);
|
||||
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||
addListener(event: "resize", listener: () => void): this;
|
||||
emit(event: string | symbol, ...args: any[]): boolean;
|
||||
emit(event: "resize"): boolean;
|
||||
on(event: string, listener: (...args: any[]) => void): this;
|
||||
on(event: "resize", listener: () => void): this;
|
||||
once(event: string, listener: (...args: any[]) => void): this;
|
||||
once(event: "resize", listener: () => void): this;
|
||||
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependListener(event: "resize", listener: () => void): this;
|
||||
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependOnceListener(event: "resize", listener: () => void): this;
|
||||
/**
|
||||
* `writeStream.clearLine()` clears the current line of this `WriteStream` in a
|
||||
* direction identified by `dir`.
|
||||
* @since v0.7.7
|
||||
* @param callback Invoked once the operation completes.
|
||||
* @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`.
|
||||
*/
|
||||
clearLine(dir: Direction, callback?: () => void): boolean;
|
||||
/**
|
||||
* `writeStream.clearScreenDown()` clears this `WriteStream` from the current
|
||||
* cursor down.
|
||||
* @since v0.7.7
|
||||
* @param callback Invoked once the operation completes.
|
||||
* @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`.
|
||||
*/
|
||||
clearScreenDown(callback?: () => void): boolean;
|
||||
/**
|
||||
* `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified
|
||||
* position.
|
||||
* @since v0.7.7
|
||||
* @param callback Invoked once the operation completes.
|
||||
* @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`.
|
||||
*/
|
||||
cursorTo(x: number, y?: number, callback?: () => void): boolean;
|
||||
cursorTo(x: number, callback: () => void): boolean;
|
||||
/**
|
||||
* `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its
|
||||
* current position.
|
||||
* @since v0.7.7
|
||||
* @param callback Invoked once the operation completes.
|
||||
* @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`.
|
||||
*/
|
||||
moveCursor(dx: number, dy: number, callback?: () => void): boolean;
|
||||
/**
|
||||
* Returns:
|
||||
*
|
||||
* * `1` for 2,
|
||||
* * `4` for 16,
|
||||
* * `8` for 256,
|
||||
* * `24` for 16,777,216 colors supported.
|
||||
*
|
||||
* Use this to determine what colors the terminal supports. Due to the nature of
|
||||
* colors in terminals it is possible to either have false positives or false
|
||||
* negatives. It depends on process information and the environment variables that
|
||||
* may lie about what terminal is used.
|
||||
* It is possible to pass in an `env` object to simulate the usage of a specific
|
||||
* terminal. This can be useful to check how specific environment settings behave.
|
||||
*
|
||||
* To enforce a specific color support, use one of the below environment settings.
|
||||
*
|
||||
* * 2 colors: `FORCE_COLOR = 0` (Disables colors)
|
||||
* * 16 colors: `FORCE_COLOR = 1`
|
||||
* * 256 colors: `FORCE_COLOR = 2`
|
||||
* * 16,777,216 colors: `FORCE_COLOR = 3`
|
||||
*
|
||||
* Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables.
|
||||
* @since v9.9.0
|
||||
* @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal.
|
||||
*/
|
||||
getColorDepth(env?: object): number;
|
||||
/**
|
||||
* Returns `true` if the `writeStream` supports at least as many colors as provided
|
||||
* in `count`. Minimum support is 2 (black and white).
|
||||
*
|
||||
* This has the same false positives and negatives as described in `writeStream.getColorDepth()`.
|
||||
*
|
||||
* ```js
|
||||
* process.stdout.hasColors();
|
||||
* // Returns true or false depending on if `stdout` supports at least 16 colors.
|
||||
* process.stdout.hasColors(256);
|
||||
* // Returns true or false depending on if `stdout` supports at least 256 colors.
|
||||
* process.stdout.hasColors({ TMUX: '1' });
|
||||
* // Returns true.
|
||||
* process.stdout.hasColors(2 ** 24, { TMUX: '1' });
|
||||
* // Returns false (the environment setting pretends to support 2 ** 8 colors).
|
||||
* ```
|
||||
* @since v11.13.0, v10.16.0
|
||||
* @param [count=16] The number of colors that are requested (minimum 2).
|
||||
* @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal.
|
||||
*/
|
||||
hasColors(count?: number): boolean;
|
||||
hasColors(env?: object): boolean;
|
||||
hasColors(count: number, env?: object): boolean;
|
||||
/**
|
||||
* `writeStream.getWindowSize()` returns the size of the TTY
|
||||
* corresponding to this `WriteStream`. The array is of the type `[numColumns, numRows]` where `numColumns` and `numRows` represent the number
|
||||
* of columns and rows in the corresponding TTY.
|
||||
* @since v0.7.7
|
||||
*/
|
||||
getWindowSize(): [number, number];
|
||||
/**
|
||||
* A `number` specifying the number of columns the TTY currently has. This property
|
||||
* is updated whenever the `'resize'` event is emitted.
|
||||
* @since v0.7.7
|
||||
*/
|
||||
columns: number;
|
||||
/**
|
||||
* A `number` specifying the number of rows the TTY currently has. This property
|
||||
* is updated whenever the `'resize'` event is emitted.
|
||||
* @since v0.7.7
|
||||
*/
|
||||
rows: number;
|
||||
/**
|
||||
* A `boolean` that is always `true`.
|
||||
* @since v0.5.8
|
||||
*/
|
||||
isTTY: boolean;
|
||||
}
|
||||
}
|
||||
declare module "node:tty" {
|
||||
export * from "tty";
|
||||
}
|
||||
+1057
File diff suppressed because it is too large
Load Diff
+2333
File diff suppressed because it is too large
Load Diff
+978
@@ -0,0 +1,978 @@
|
||||
/**
|
||||
* The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using:
|
||||
*
|
||||
* ```js
|
||||
* import v8 from 'node:v8';
|
||||
* ```
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/v8.js)
|
||||
*/
|
||||
declare module "v8" {
|
||||
import { NonSharedBuffer } from "node:buffer";
|
||||
import { Readable } from "node:stream";
|
||||
interface HeapSpaceInfo {
|
||||
space_name: string;
|
||||
space_size: number;
|
||||
space_used_size: number;
|
||||
space_available_size: number;
|
||||
physical_space_size: number;
|
||||
}
|
||||
// ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */
|
||||
type DoesZapCodeSpaceFlag = 0 | 1;
|
||||
interface HeapInfo {
|
||||
total_heap_size: number;
|
||||
total_heap_size_executable: number;
|
||||
total_physical_size: number;
|
||||
total_available_size: number;
|
||||
used_heap_size: number;
|
||||
heap_size_limit: number;
|
||||
malloced_memory: number;
|
||||
peak_malloced_memory: number;
|
||||
does_zap_garbage: DoesZapCodeSpaceFlag;
|
||||
number_of_native_contexts: number;
|
||||
number_of_detached_contexts: number;
|
||||
total_global_handles_size: number;
|
||||
used_global_handles_size: number;
|
||||
external_memory: number;
|
||||
}
|
||||
interface HeapCodeStatistics {
|
||||
code_and_metadata_size: number;
|
||||
bytecode_and_metadata_size: number;
|
||||
external_script_source_size: number;
|
||||
}
|
||||
interface HeapSnapshotOptions {
|
||||
/**
|
||||
* If true, expose internals in the heap snapshot.
|
||||
* @default false
|
||||
*/
|
||||
exposeInternals?: boolean | undefined;
|
||||
/**
|
||||
* If true, expose numeric values in artificial fields.
|
||||
* @default false
|
||||
*/
|
||||
exposeNumericValues?: boolean | undefined;
|
||||
}
|
||||
/**
|
||||
* Returns an integer representing a version tag derived from the V8 version,
|
||||
* command-line flags, and detected CPU features. This is useful for determining
|
||||
* whether a `vm.Script` `cachedData` buffer is compatible with this instance
|
||||
* of V8.
|
||||
*
|
||||
* ```js
|
||||
* console.log(v8.cachedDataVersionTag()); // 3947234607
|
||||
* // The value returned by v8.cachedDataVersionTag() is derived from the V8
|
||||
* // version, command-line flags, and detected CPU features. Test that the value
|
||||
* // does indeed update when flags are toggled.
|
||||
* v8.setFlagsFromString('--allow_natives_syntax');
|
||||
* console.log(v8.cachedDataVersionTag()); // 183726201
|
||||
* ```
|
||||
* @since v8.0.0
|
||||
*/
|
||||
function cachedDataVersionTag(): number;
|
||||
/**
|
||||
* Returns an object with the following properties:
|
||||
*
|
||||
* `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap
|
||||
* garbage with a bit pattern. The RSS footprint (resident set size) gets bigger
|
||||
* because it continuously touches all heap pages and that makes them less likely
|
||||
* to get swapped out by the operating system.
|
||||
*
|
||||
* `number_of_native_contexts` The value of native\_context is the number of the
|
||||
* top-level contexts currently active. Increase of this number over time indicates
|
||||
* a memory leak.
|
||||
*
|
||||
* `number_of_detached_contexts` The value of detached\_context is the number
|
||||
* of contexts that were detached and not yet garbage collected. This number
|
||||
* being non-zero indicates a potential memory leak.
|
||||
*
|
||||
* `total_global_handles_size` The value of total\_global\_handles\_size is the
|
||||
* total memory size of V8 global handles.
|
||||
*
|
||||
* `used_global_handles_size` The value of used\_global\_handles\_size is the
|
||||
* used memory size of V8 global handles.
|
||||
*
|
||||
* `external_memory` The value of external\_memory is the memory size of array
|
||||
* buffers and external strings.
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* total_heap_size: 7326976,
|
||||
* total_heap_size_executable: 4194304,
|
||||
* total_physical_size: 7326976,
|
||||
* total_available_size: 1152656,
|
||||
* used_heap_size: 3476208,
|
||||
* heap_size_limit: 1535115264,
|
||||
* malloced_memory: 16384,
|
||||
* peak_malloced_memory: 1127496,
|
||||
* does_zap_garbage: 0,
|
||||
* number_of_native_contexts: 1,
|
||||
* number_of_detached_contexts: 0,
|
||||
* total_global_handles_size: 8192,
|
||||
* used_global_handles_size: 3296,
|
||||
* external_memory: 318824
|
||||
* }
|
||||
* ```
|
||||
* @since v1.0.0
|
||||
*/
|
||||
function getHeapStatistics(): HeapInfo;
|
||||
/**
|
||||
* It returns an object with a structure similar to the
|
||||
* [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html)
|
||||
* object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html)
|
||||
* for more information about the properties of the object.
|
||||
*
|
||||
* ```js
|
||||
* // Detailed
|
||||
* ({
|
||||
* committed_size_bytes: 131072,
|
||||
* resident_size_bytes: 131072,
|
||||
* used_size_bytes: 152,
|
||||
* space_statistics: [
|
||||
* {
|
||||
* name: 'NormalPageSpace0',
|
||||
* committed_size_bytes: 0,
|
||||
* resident_size_bytes: 0,
|
||||
* used_size_bytes: 0,
|
||||
* page_stats: [{}],
|
||||
* free_list_stats: {},
|
||||
* },
|
||||
* {
|
||||
* name: 'NormalPageSpace1',
|
||||
* committed_size_bytes: 131072,
|
||||
* resident_size_bytes: 131072,
|
||||
* used_size_bytes: 152,
|
||||
* page_stats: [{}],
|
||||
* free_list_stats: {},
|
||||
* },
|
||||
* {
|
||||
* name: 'NormalPageSpace2',
|
||||
* committed_size_bytes: 0,
|
||||
* resident_size_bytes: 0,
|
||||
* used_size_bytes: 0,
|
||||
* page_stats: [{}],
|
||||
* free_list_stats: {},
|
||||
* },
|
||||
* {
|
||||
* name: 'NormalPageSpace3',
|
||||
* committed_size_bytes: 0,
|
||||
* resident_size_bytes: 0,
|
||||
* used_size_bytes: 0,
|
||||
* page_stats: [{}],
|
||||
* free_list_stats: {},
|
||||
* },
|
||||
* {
|
||||
* name: 'LargePageSpace',
|
||||
* committed_size_bytes: 0,
|
||||
* resident_size_bytes: 0,
|
||||
* used_size_bytes: 0,
|
||||
* page_stats: [{}],
|
||||
* free_list_stats: {},
|
||||
* },
|
||||
* ],
|
||||
* type_names: [],
|
||||
* detail_level: 'detailed',
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* ```js
|
||||
* // Brief
|
||||
* ({
|
||||
* committed_size_bytes: 131072,
|
||||
* resident_size_bytes: 131072,
|
||||
* used_size_bytes: 128864,
|
||||
* space_statistics: [],
|
||||
* type_names: [],
|
||||
* detail_level: 'brief',
|
||||
* });
|
||||
* ```
|
||||
* @since v22.15.0
|
||||
* @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics.
|
||||
* Accepted values are:
|
||||
* * `'brief'`: Brief statistics contain only the top-level
|
||||
* allocated and used
|
||||
* memory statistics for the entire heap.
|
||||
* * `'detailed'`: Detailed statistics also contain a break
|
||||
* down per space and page, as well as freelist statistics
|
||||
* and object type histograms.
|
||||
*/
|
||||
function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object;
|
||||
/**
|
||||
* Returns statistics about the V8 heap spaces, i.e. the segments which make up
|
||||
* the V8 heap. Neither the ordering of heap spaces, nor the availability of a
|
||||
* heap space can be guaranteed as the statistics are provided via the
|
||||
* V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the
|
||||
* next.
|
||||
*
|
||||
* The value returned is an array of objects containing the following properties:
|
||||
*
|
||||
* ```json
|
||||
* [
|
||||
* {
|
||||
* "space_name": "new_space",
|
||||
* "space_size": 2063872,
|
||||
* "space_used_size": 951112,
|
||||
* "space_available_size": 80824,
|
||||
* "physical_space_size": 2063872
|
||||
* },
|
||||
* {
|
||||
* "space_name": "old_space",
|
||||
* "space_size": 3090560,
|
||||
* "space_used_size": 2493792,
|
||||
* "space_available_size": 0,
|
||||
* "physical_space_size": 3090560
|
||||
* },
|
||||
* {
|
||||
* "space_name": "code_space",
|
||||
* "space_size": 1260160,
|
||||
* "space_used_size": 644256,
|
||||
* "space_available_size": 960,
|
||||
* "physical_space_size": 1260160
|
||||
* },
|
||||
* {
|
||||
* "space_name": "map_space",
|
||||
* "space_size": 1094160,
|
||||
* "space_used_size": 201608,
|
||||
* "space_available_size": 0,
|
||||
* "physical_space_size": 1094160
|
||||
* },
|
||||
* {
|
||||
* "space_name": "large_object_space",
|
||||
* "space_size": 0,
|
||||
* "space_used_size": 0,
|
||||
* "space_available_size": 1490980608,
|
||||
* "physical_space_size": 0
|
||||
* }
|
||||
* ]
|
||||
* ```
|
||||
* @since v6.0.0
|
||||
*/
|
||||
function getHeapSpaceStatistics(): HeapSpaceInfo[];
|
||||
/**
|
||||
* The `v8.setFlagsFromString()` method can be used to programmatically set
|
||||
* V8 command-line flags. This method should be used with care. Changing settings
|
||||
* after the VM has started may result in unpredictable behavior, including
|
||||
* crashes and data loss; or it may simply do nothing.
|
||||
*
|
||||
* The V8 options available for a version of Node.js may be determined by running `node --v8-options`.
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* ```js
|
||||
* // Print GC events to stdout for one minute.
|
||||
* import v8 from 'node:v8';
|
||||
* v8.setFlagsFromString('--trace_gc');
|
||||
* setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
|
||||
* ```
|
||||
* @since v1.0.0
|
||||
*/
|
||||
function setFlagsFromString(flags: string): void;
|
||||
/**
|
||||
* This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function)
|
||||
* provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain
|
||||
* in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should
|
||||
* avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the
|
||||
* application.
|
||||
*
|
||||
* To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects
|
||||
* found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided
|
||||
* in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the
|
||||
* target objects during the search.
|
||||
*
|
||||
* Only objects created in the current execution context are included in the results.
|
||||
*
|
||||
* ```js
|
||||
* import { queryObjects } from 'node:v8';
|
||||
* class A { foo = 'bar'; }
|
||||
* console.log(queryObjects(A)); // 0
|
||||
* const a = new A();
|
||||
* console.log(queryObjects(A)); // 1
|
||||
* // [ "A { foo: 'bar' }" ]
|
||||
* console.log(queryObjects(A, { format: 'summary' }));
|
||||
*
|
||||
* class B extends A { bar = 'qux'; }
|
||||
* const b = new B();
|
||||
* console.log(queryObjects(B)); // 1
|
||||
* // [ "B { foo: 'bar', bar: 'qux' }" ]
|
||||
* console.log(queryObjects(B, { format: 'summary' }));
|
||||
*
|
||||
* // Note that, when there are child classes inheriting from a constructor,
|
||||
* // the constructor also shows up in the prototype chain of the child
|
||||
* // classes's prototoype, so the child classes's prototoype would also be
|
||||
* // included in the result.
|
||||
* console.log(queryObjects(A)); // 3
|
||||
* // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ]
|
||||
* console.log(queryObjects(A, { format: 'summary' }));
|
||||
* ```
|
||||
* @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap.
|
||||
* @since v20.13.0
|
||||
* @experimental
|
||||
*/
|
||||
function queryObjects(ctor: Function): number | string[];
|
||||
function queryObjects(ctor: Function, options: { format: "count" }): number;
|
||||
function queryObjects(ctor: Function, options: { format: "summary" }): string[];
|
||||
/**
|
||||
* Generates a snapshot of the current V8 heap and returns a Readable
|
||||
* Stream that may be used to read the JSON serialized representation.
|
||||
* This JSON stream format is intended to be used with tools such as
|
||||
* Chrome DevTools. The JSON schema is undocumented and specific to the
|
||||
* V8 engine. Therefore, the schema may change from one version of V8 to the next.
|
||||
*
|
||||
* Creating a heap snapshot requires memory about twice the size of the heap at
|
||||
* the time the snapshot is created. This results in the risk of OOM killers
|
||||
* terminating the process.
|
||||
*
|
||||
* Generating a snapshot is a synchronous operation which blocks the event loop
|
||||
* for a duration depending on the heap size.
|
||||
*
|
||||
* ```js
|
||||
* // Print heap snapshot to the console
|
||||
* import v8 from 'node:v8';
|
||||
* const stream = v8.getHeapSnapshot();
|
||||
* stream.pipe(process.stdout);
|
||||
* ```
|
||||
* @since v11.13.0
|
||||
* @return A Readable containing the V8 heap snapshot.
|
||||
*/
|
||||
function getHeapSnapshot(options?: HeapSnapshotOptions): Readable;
|
||||
/**
|
||||
* Generates a snapshot of the current V8 heap and writes it to a JSON
|
||||
* file. This file is intended to be used with tools such as Chrome
|
||||
* DevTools. The JSON schema is undocumented and specific to the V8
|
||||
* engine, and may change from one version of V8 to the next.
|
||||
*
|
||||
* A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will
|
||||
* not contain any information about the workers, and vice versa.
|
||||
*
|
||||
* Creating a heap snapshot requires memory about twice the size of the heap at
|
||||
* the time the snapshot is created. This results in the risk of OOM killers
|
||||
* terminating the process.
|
||||
*
|
||||
* Generating a snapshot is a synchronous operation which blocks the event loop
|
||||
* for a duration depending on the heap size.
|
||||
*
|
||||
* ```js
|
||||
* import { writeHeapSnapshot } from 'node:v8';
|
||||
* import {
|
||||
* Worker,
|
||||
* isMainThread,
|
||||
* parentPort,
|
||||
* } from 'node:worker_threads';
|
||||
*
|
||||
* if (isMainThread) {
|
||||
* const worker = new Worker(__filename);
|
||||
*
|
||||
* worker.once('message', (filename) => {
|
||||
* console.log(`worker heapdump: ${filename}`);
|
||||
* // Now get a heapdump for the main thread.
|
||||
* console.log(`main thread heapdump: ${writeHeapSnapshot()}`);
|
||||
* });
|
||||
*
|
||||
* // Tell the worker to create a heapdump.
|
||||
* worker.postMessage('heapdump');
|
||||
* } else {
|
||||
* parentPort.once('message', (message) => {
|
||||
* if (message === 'heapdump') {
|
||||
* // Generate a heapdump for the worker
|
||||
* // and return the filename to the parent.
|
||||
* parentPort.postMessage(writeHeapSnapshot());
|
||||
* }
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
* @since v11.13.0
|
||||
* @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be
|
||||
* generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a
|
||||
* worker thread.
|
||||
* @return The filename where the snapshot was saved.
|
||||
*/
|
||||
function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string;
|
||||
/**
|
||||
* Get statistics about code and its metadata in the heap, see
|
||||
* V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the
|
||||
* following properties:
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* code_and_metadata_size: 212208,
|
||||
* bytecode_and_metadata_size: 161368,
|
||||
* external_script_source_size: 1410794,
|
||||
* cpu_profiler_metadata_size: 0,
|
||||
* }
|
||||
* ```
|
||||
* @since v12.8.0
|
||||
*/
|
||||
function getHeapCodeStatistics(): HeapCodeStatistics;
|
||||
/**
|
||||
* @since v24.12.0
|
||||
*/
|
||||
interface SyncCPUProfileHandle {
|
||||
/**
|
||||
* Stopping collecting the profile and return the profile data.
|
||||
* @since v24.12.0
|
||||
*/
|
||||
stop(): string;
|
||||
/**
|
||||
* Stopping collecting the profile and the profile will be discarded.
|
||||
* @since v24.12.0
|
||||
*/
|
||||
[Symbol.dispose](): void;
|
||||
}
|
||||
/**
|
||||
* @since v24.8.0
|
||||
*/
|
||||
interface CPUProfileHandle {
|
||||
/**
|
||||
* Stopping collecting the profile, then return a Promise that fulfills with an error or the
|
||||
* profile data.
|
||||
* @since v24.8.0
|
||||
*/
|
||||
stop(): Promise<string>;
|
||||
/**
|
||||
* Stopping collecting the profile and the profile will be discarded.
|
||||
* @since v24.8.0
|
||||
*/
|
||||
[Symbol.asyncDispose](): Promise<void>;
|
||||
}
|
||||
/**
|
||||
* @since v24.9.0
|
||||
*/
|
||||
interface HeapProfileHandle {
|
||||
/**
|
||||
* Stopping collecting the profile, then return a Promise that fulfills with an error or the
|
||||
* profile data.
|
||||
* @since v24.9.0
|
||||
*/
|
||||
stop(): Promise<string>;
|
||||
/**
|
||||
* Stopping collecting the profile and the profile will be discarded.
|
||||
* @since v24.9.0
|
||||
*/
|
||||
[Symbol.asyncDispose](): Promise<void>;
|
||||
}
|
||||
/**
|
||||
* V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string.
|
||||
* If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true;
|
||||
* otherwise, it returns false.
|
||||
*
|
||||
* If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`.
|
||||
* Sometimes a `Latin-1` string may also be represented as `UTF16`.
|
||||
*
|
||||
* ```js
|
||||
* const { isStringOneByteRepresentation } = require('node:v8');
|
||||
*
|
||||
* const Encoding = {
|
||||
* latin1: 1,
|
||||
* utf16le: 2,
|
||||
* };
|
||||
* const buffer = Buffer.alloc(100);
|
||||
* function writeString(input) {
|
||||
* if (isStringOneByteRepresentation(input)) {
|
||||
* buffer.writeUint8(Encoding.latin1);
|
||||
* buffer.writeUint32LE(input.length, 1);
|
||||
* buffer.write(input, 5, 'latin1');
|
||||
* } else {
|
||||
* buffer.writeUint8(Encoding.utf16le);
|
||||
* buffer.writeUint32LE(input.length * 2, 1);
|
||||
* buffer.write(input, 5, 'utf16le');
|
||||
* }
|
||||
* }
|
||||
* writeString('hello');
|
||||
* writeString('你好');
|
||||
* ```
|
||||
* @since v23.10.0, v22.15.0
|
||||
*/
|
||||
function isStringOneByteRepresentation(content: string): boolean;
|
||||
/**
|
||||
* Starting a CPU profile then return a `SyncCPUProfileHandle` object. This API supports `using` syntax.
|
||||
*
|
||||
* ```js
|
||||
* const handle = v8.startCpuProfile();
|
||||
* const profile = handle.stop();
|
||||
* console.log(profile);
|
||||
* ```
|
||||
* @since v24.12.0
|
||||
*/
|
||||
function startCpuProfile(): SyncCPUProfileHandle;
|
||||
/**
|
||||
* @since v8.0.0
|
||||
*/
|
||||
class Serializer {
|
||||
/**
|
||||
* Writes out a header, which includes the serialization format version.
|
||||
*/
|
||||
writeHeader(): void;
|
||||
/**
|
||||
* Serializes a JavaScript value and adds the serialized representation to the
|
||||
* internal buffer.
|
||||
*
|
||||
* This throws an error if `value` cannot be serialized.
|
||||
*/
|
||||
writeValue(val: any): boolean;
|
||||
/**
|
||||
* Returns the stored internal buffer. This serializer should not be used once
|
||||
* the buffer is released. Calling this method results in undefined behavior
|
||||
* if a previous write has failed.
|
||||
*/
|
||||
releaseBuffer(): NonSharedBuffer;
|
||||
/**
|
||||
* Marks an `ArrayBuffer` as having its contents transferred out of band.
|
||||
* Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`.
|
||||
* @param id A 32-bit unsigned integer.
|
||||
* @param arrayBuffer An `ArrayBuffer` instance.
|
||||
*/
|
||||
transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void;
|
||||
/**
|
||||
* Write a raw 32-bit unsigned integer.
|
||||
* For use inside of a custom `serializer._writeHostObject()`.
|
||||
*/
|
||||
writeUint32(value: number): void;
|
||||
/**
|
||||
* Write a raw 64-bit unsigned integer, split into high and low 32-bit parts.
|
||||
* For use inside of a custom `serializer._writeHostObject()`.
|
||||
*/
|
||||
writeUint64(hi: number, lo: number): void;
|
||||
/**
|
||||
* Write a JS `number` value.
|
||||
* For use inside of a custom `serializer._writeHostObject()`.
|
||||
*/
|
||||
writeDouble(value: number): void;
|
||||
/**
|
||||
* Write raw bytes into the serializer's internal buffer. The deserializer
|
||||
* will require a way to compute the length of the buffer.
|
||||
* For use inside of a custom `serializer._writeHostObject()`.
|
||||
*/
|
||||
writeRawBytes(buffer: NodeJS.ArrayBufferView): void;
|
||||
}
|
||||
/**
|
||||
* A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only
|
||||
* stores the part of their underlying `ArrayBuffer`s that they are referring to.
|
||||
* @since v8.0.0
|
||||
*/
|
||||
class DefaultSerializer extends Serializer {}
|
||||
/**
|
||||
* @since v8.0.0
|
||||
*/
|
||||
class Deserializer {
|
||||
constructor(data: NodeJS.TypedArray);
|
||||
/**
|
||||
* Reads and validates a header (including the format version).
|
||||
* May, for example, reject an invalid or unsupported wire format. In that case,
|
||||
* an `Error` is thrown.
|
||||
*/
|
||||
readHeader(): boolean;
|
||||
/**
|
||||
* Deserializes a JavaScript value from the buffer and returns it.
|
||||
*/
|
||||
readValue(): any;
|
||||
/**
|
||||
* Marks an `ArrayBuffer` as having its contents transferred out of band.
|
||||
* Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of
|
||||
* `SharedArrayBuffer`s).
|
||||
* @param id A 32-bit unsigned integer.
|
||||
* @param arrayBuffer An `ArrayBuffer` instance.
|
||||
*/
|
||||
transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void;
|
||||
/**
|
||||
* Reads the underlying wire format version. Likely mostly to be useful to
|
||||
* legacy code reading old wire format versions. May not be called before `.readHeader()`.
|
||||
*/
|
||||
getWireFormatVersion(): number;
|
||||
/**
|
||||
* Read a raw 32-bit unsigned integer and return it.
|
||||
* For use inside of a custom `deserializer._readHostObject()`.
|
||||
*/
|
||||
readUint32(): number;
|
||||
/**
|
||||
* Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries.
|
||||
* For use inside of a custom `deserializer._readHostObject()`.
|
||||
*/
|
||||
readUint64(): [number, number];
|
||||
/**
|
||||
* Read a JS `number` value.
|
||||
* For use inside of a custom `deserializer._readHostObject()`.
|
||||
*/
|
||||
readDouble(): number;
|
||||
/**
|
||||
* Read raw bytes from the deserializer's internal buffer. The `length` parameter
|
||||
* must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`.
|
||||
* For use inside of a custom `deserializer._readHostObject()`.
|
||||
*/
|
||||
readRawBytes(length: number): Buffer;
|
||||
}
|
||||
/**
|
||||
* A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`.
|
||||
* @since v8.0.0
|
||||
*/
|
||||
class DefaultDeserializer extends Deserializer {}
|
||||
/**
|
||||
* Uses a `DefaultSerializer` to serialize `value` into a buffer.
|
||||
*
|
||||
* `ERR_BUFFER_TOO_LARGE` will be thrown when trying to
|
||||
* serialize a huge object which requires buffer
|
||||
* larger than `buffer.constants.MAX_LENGTH`.
|
||||
* @since v8.0.0
|
||||
*/
|
||||
function serialize(value: any): NonSharedBuffer;
|
||||
/**
|
||||
* Uses a `DefaultDeserializer` with default options to read a JS value
|
||||
* from a buffer.
|
||||
* @since v8.0.0
|
||||
* @param buffer A buffer returned by {@link serialize}.
|
||||
*/
|
||||
function deserialize(buffer: NodeJS.ArrayBufferView): any;
|
||||
/**
|
||||
* The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple
|
||||
* times during the lifetime of the process. Each time the execution counter will
|
||||
* be reset and a new coverage report will be written to the directory specified
|
||||
* by `NODE_V8_COVERAGE`.
|
||||
*
|
||||
* When the process is about to exit, one last coverage will still be written to
|
||||
* disk unless {@link stopCoverage} is invoked before the process exits.
|
||||
* @since v15.1.0, v14.18.0, v12.22.0
|
||||
*/
|
||||
function takeCoverage(): void;
|
||||
/**
|
||||
* The `v8.stopCoverage()` method allows the user to stop the coverage collection
|
||||
* started by `NODE_V8_COVERAGE`, so that V8 can release the execution count
|
||||
* records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand.
|
||||
* @since v15.1.0, v14.18.0, v12.22.0
|
||||
*/
|
||||
function stopCoverage(): void;
|
||||
/**
|
||||
* The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once.
|
||||
* `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information.
|
||||
* @since v18.10.0, v16.18.0
|
||||
*/
|
||||
function setHeapSnapshotNearHeapLimit(limit: number): void;
|
||||
/**
|
||||
* This API collects GC data in current thread.
|
||||
* @since v19.6.0, v18.15.0
|
||||
*/
|
||||
class GCProfiler {
|
||||
/**
|
||||
* Start collecting GC data.
|
||||
* @since v19.6.0, v18.15.0
|
||||
*/
|
||||
start(): void;
|
||||
/**
|
||||
* Stop collecting GC data and return an object. The content of object
|
||||
* is as follows.
|
||||
*
|
||||
* ```json
|
||||
* {
|
||||
* "version": 1,
|
||||
* "startTime": 1674059033862,
|
||||
* "statistics": [
|
||||
* {
|
||||
* "gcType": "Scavenge",
|
||||
* "beforeGC": {
|
||||
* "heapStatistics": {
|
||||
* "totalHeapSize": 5005312,
|
||||
* "totalHeapSizeExecutable": 524288,
|
||||
* "totalPhysicalSize": 5226496,
|
||||
* "totalAvailableSize": 4341325216,
|
||||
* "totalGlobalHandlesSize": 8192,
|
||||
* "usedGlobalHandlesSize": 2112,
|
||||
* "usedHeapSize": 4883840,
|
||||
* "heapSizeLimit": 4345298944,
|
||||
* "mallocedMemory": 254128,
|
||||
* "externalMemory": 225138,
|
||||
* "peakMallocedMemory": 181760
|
||||
* },
|
||||
* "heapSpaceStatistics": [
|
||||
* {
|
||||
* "spaceName": "read_only_space",
|
||||
* "spaceSize": 0,
|
||||
* "spaceUsedSize": 0,
|
||||
* "spaceAvailableSize": 0,
|
||||
* "physicalSpaceSize": 0
|
||||
* }
|
||||
* ]
|
||||
* },
|
||||
* "cost": 1574.14,
|
||||
* "afterGC": {
|
||||
* "heapStatistics": {
|
||||
* "totalHeapSize": 6053888,
|
||||
* "totalHeapSizeExecutable": 524288,
|
||||
* "totalPhysicalSize": 5500928,
|
||||
* "totalAvailableSize": 4341101384,
|
||||
* "totalGlobalHandlesSize": 8192,
|
||||
* "usedGlobalHandlesSize": 2112,
|
||||
* "usedHeapSize": 4059096,
|
||||
* "heapSizeLimit": 4345298944,
|
||||
* "mallocedMemory": 254128,
|
||||
* "externalMemory": 225138,
|
||||
* "peakMallocedMemory": 181760
|
||||
* },
|
||||
* "heapSpaceStatistics": [
|
||||
* {
|
||||
* "spaceName": "read_only_space",
|
||||
* "spaceSize": 0,
|
||||
* "spaceUsedSize": 0,
|
||||
* "spaceAvailableSize": 0,
|
||||
* "physicalSpaceSize": 0
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* }
|
||||
* ],
|
||||
* "endTime": 1674059036865
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Here's an example.
|
||||
*
|
||||
* ```js
|
||||
* import { GCProfiler } from 'node:v8';
|
||||
* const profiler = new GCProfiler();
|
||||
* profiler.start();
|
||||
* setTimeout(() => {
|
||||
* console.log(profiler.stop());
|
||||
* }, 1000);
|
||||
* ```
|
||||
* @since v19.6.0, v18.15.0
|
||||
*/
|
||||
stop(): GCProfilerResult;
|
||||
}
|
||||
interface GCProfilerResult {
|
||||
version: number;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
statistics: Array<{
|
||||
gcType: string;
|
||||
cost: number;
|
||||
beforeGC: {
|
||||
heapStatistics: HeapStatistics;
|
||||
heapSpaceStatistics: HeapSpaceStatistics[];
|
||||
};
|
||||
afterGC: {
|
||||
heapStatistics: HeapStatistics;
|
||||
heapSpaceStatistics: HeapSpaceStatistics[];
|
||||
};
|
||||
}>;
|
||||
}
|
||||
interface HeapStatistics {
|
||||
totalHeapSize: number;
|
||||
totalHeapSizeExecutable: number;
|
||||
totalPhysicalSize: number;
|
||||
totalAvailableSize: number;
|
||||
totalGlobalHandlesSize: number;
|
||||
usedGlobalHandlesSize: number;
|
||||
usedHeapSize: number;
|
||||
heapSizeLimit: number;
|
||||
mallocedMemory: number;
|
||||
externalMemory: number;
|
||||
peakMallocedMemory: number;
|
||||
}
|
||||
interface HeapSpaceStatistics {
|
||||
spaceName: string;
|
||||
spaceSize: number;
|
||||
spaceUsedSize: number;
|
||||
spaceAvailableSize: number;
|
||||
physicalSpaceSize: number;
|
||||
}
|
||||
/**
|
||||
* Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will
|
||||
* happen if a promise is created without ever getting a continuation.
|
||||
* @since v17.1.0, v16.14.0
|
||||
* @param promise The promise being created.
|
||||
* @param parent The promise continued from, if applicable.
|
||||
*/
|
||||
interface Init {
|
||||
(promise: Promise<unknown>, parent: Promise<unknown>): void;
|
||||
}
|
||||
/**
|
||||
* Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming.
|
||||
*
|
||||
* The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise.
|
||||
* The before callback may be called many times in the case where many continuations have been made from the same promise.
|
||||
* @since v17.1.0, v16.14.0
|
||||
*/
|
||||
interface Before {
|
||||
(promise: Promise<unknown>): void;
|
||||
}
|
||||
/**
|
||||
* Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await.
|
||||
* @since v17.1.0, v16.14.0
|
||||
*/
|
||||
interface After {
|
||||
(promise: Promise<unknown>): void;
|
||||
}
|
||||
/**
|
||||
* Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or
|
||||
* {@link Promise.reject()}.
|
||||
* @since v17.1.0, v16.14.0
|
||||
*/
|
||||
interface Settled {
|
||||
(promise: Promise<unknown>): void;
|
||||
}
|
||||
/**
|
||||
* Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or
|
||||
* around an await, and when the promise resolves or rejects.
|
||||
*
|
||||
* Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and
|
||||
* `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop.
|
||||
* @since v17.1.0, v16.14.0
|
||||
*/
|
||||
interface HookCallbacks {
|
||||
init?: Init;
|
||||
before?: Before;
|
||||
after?: After;
|
||||
settled?: Settled;
|
||||
}
|
||||
interface PromiseHooks {
|
||||
/**
|
||||
* The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.
|
||||
* @since v17.1.0, v16.14.0
|
||||
* @param init The {@link Init | `init` callback} to call when a promise is created.
|
||||
* @return Call to stop the hook.
|
||||
*/
|
||||
onInit: (init: Init) => Function;
|
||||
/**
|
||||
* The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.
|
||||
* @since v17.1.0, v16.14.0
|
||||
* @param settled The {@link Settled | `settled` callback} to call when a promise is created.
|
||||
* @return Call to stop the hook.
|
||||
*/
|
||||
onSettled: (settled: Settled) => Function;
|
||||
/**
|
||||
* The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.
|
||||
* @since v17.1.0, v16.14.0
|
||||
* @param before The {@link Before | `before` callback} to call before a promise continuation executes.
|
||||
* @return Call to stop the hook.
|
||||
*/
|
||||
onBefore: (before: Before) => Function;
|
||||
/**
|
||||
* The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.
|
||||
* @since v17.1.0, v16.14.0
|
||||
* @param after The {@link After | `after` callback} to call after a promise continuation executes.
|
||||
* @return Call to stop the hook.
|
||||
*/
|
||||
onAfter: (after: After) => Function;
|
||||
/**
|
||||
* Registers functions to be called for different lifetime events of each promise.
|
||||
* The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime.
|
||||
* All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed.
|
||||
* The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop.
|
||||
* @since v17.1.0, v16.14.0
|
||||
* @param callbacks The {@link HookCallbacks | Hook Callbacks} to register
|
||||
* @return Used for disabling hooks
|
||||
*/
|
||||
createHook: (callbacks: HookCallbacks) => Function;
|
||||
}
|
||||
/**
|
||||
* The `promiseHooks` interface can be used to track promise lifecycle events.
|
||||
* @since v17.1.0, v16.14.0
|
||||
*/
|
||||
const promiseHooks: PromiseHooks;
|
||||
type StartupSnapshotCallbackFn = (args: any) => any;
|
||||
/**
|
||||
* The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots.
|
||||
*
|
||||
* ```bash
|
||||
* $ node --snapshot-blob snapshot.blob --build-snapshot entry.js
|
||||
* # This launches a process with the snapshot
|
||||
* $ node --snapshot-blob snapshot.blob
|
||||
* ```
|
||||
*
|
||||
* In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects
|
||||
* in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot.
|
||||
* For example, if the `entry.js` contains the following script:
|
||||
*
|
||||
* ```js
|
||||
* 'use strict';
|
||||
*
|
||||
* import fs from 'node:fs';
|
||||
* import zlib from 'node:zlib';
|
||||
* import path from 'node:path';
|
||||
* import assert from 'node:assert';
|
||||
*
|
||||
* import v8 from 'node:v8';
|
||||
*
|
||||
* class BookShelf {
|
||||
* storage = new Map();
|
||||
*
|
||||
* // Reading a series of files from directory and store them into storage.
|
||||
* constructor(directory, books) {
|
||||
* for (const book of books) {
|
||||
* this.storage.set(book, fs.readFileSync(path.join(directory, book)));
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* static compressAll(shelf) {
|
||||
* for (const [ book, content ] of shelf.storage) {
|
||||
* shelf.storage.set(book, zlib.gzipSync(content));
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* static decompressAll(shelf) {
|
||||
* for (const [ book, content ] of shelf.storage) {
|
||||
* shelf.storage.set(book, zlib.gunzipSync(content));
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* // __dirname here is where the snapshot script is placed
|
||||
* // during snapshot building time.
|
||||
* const shelf = new BookShelf(__dirname, [
|
||||
* 'book1.en_US.txt',
|
||||
* 'book1.es_ES.txt',
|
||||
* 'book2.zh_CN.txt',
|
||||
* ]);
|
||||
*
|
||||
* assert(v8.startupSnapshot.isBuildingSnapshot());
|
||||
* // On snapshot serialization, compress the books to reduce size.
|
||||
* v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf);
|
||||
* // On snapshot deserialization, decompress the books.
|
||||
* v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf);
|
||||
* v8.startupSnapshot.setDeserializeMainFunction((shelf) => {
|
||||
* // process.env and process.argv are refreshed during snapshot
|
||||
* // deserialization.
|
||||
* const lang = process.env.BOOK_LANG || 'en_US';
|
||||
* const book = process.argv[1];
|
||||
* const name = `${book}.${lang}.txt`;
|
||||
* console.log(shelf.storage.get(name));
|
||||
* }, shelf);
|
||||
* ```
|
||||
*
|
||||
* The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process:
|
||||
*
|
||||
* ```bash
|
||||
* $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1
|
||||
* # Prints content of book1.es_ES.txt deserialized from the snapshot.
|
||||
* ```
|
||||
*
|
||||
* Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot.
|
||||
*
|
||||
* @since v18.6.0, v16.17.0
|
||||
*/
|
||||
namespace startupSnapshot {
|
||||
/**
|
||||
* Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit.
|
||||
* This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization.
|
||||
* @since v18.6.0, v16.17.0
|
||||
*/
|
||||
function addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void;
|
||||
/**
|
||||
* Add a callback that will be called when the Node.js instance is deserialized from a snapshot.
|
||||
* The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or
|
||||
* to re-acquire resources that the application needs when the application is restarted from the snapshot.
|
||||
* @since v18.6.0, v16.17.0
|
||||
*/
|
||||
function addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void;
|
||||
/**
|
||||
* This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script.
|
||||
* If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized
|
||||
* data (if provided), otherwise an entry point script still needs to be provided to the deserialized application.
|
||||
* @since v18.6.0, v16.17.0
|
||||
*/
|
||||
function setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void;
|
||||
/**
|
||||
* Returns true if the Node.js instance is run to build a snapshot.
|
||||
* @since v18.6.0, v16.17.0
|
||||
*/
|
||||
function isBuildingSnapshot(): boolean;
|
||||
}
|
||||
}
|
||||
declare module "node:v8" {
|
||||
export * from "v8";
|
||||
}
|
||||
+1195
File diff suppressed because it is too large
Load Diff
+202
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* **The `node:wasi` module does not currently provide the**
|
||||
* **comprehensive file system security properties provided by some WASI runtimes.**
|
||||
* **Full support for secure file system sandboxing may or may not be implemented in**
|
||||
* **future. In the mean time, do not rely on it to run untrusted code.**
|
||||
*
|
||||
* The WASI API provides an implementation of the [WebAssembly System Interface](https://wasi.dev/) specification. WASI gives WebAssembly applications access to the underlying
|
||||
* operating system via a collection of POSIX-like functions.
|
||||
*
|
||||
* ```js
|
||||
* import { readFile } from 'node:fs/promises';
|
||||
* import { WASI } from 'node:wasi';
|
||||
* import { argv, env } from 'node:process';
|
||||
*
|
||||
* const wasi = new WASI({
|
||||
* version: 'preview1',
|
||||
* args: argv,
|
||||
* env,
|
||||
* preopens: {
|
||||
* '/local': '/some/real/path/that/wasm/can/access',
|
||||
* },
|
||||
* });
|
||||
*
|
||||
* const wasm = await WebAssembly.compile(
|
||||
* await readFile(new URL('./demo.wasm', import.meta.url)),
|
||||
* );
|
||||
* const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject());
|
||||
*
|
||||
* wasi.start(instance);
|
||||
* ```
|
||||
*
|
||||
* To run the above example, create a new WebAssembly text format file named `demo.wat`:
|
||||
*
|
||||
* ```text
|
||||
* (module
|
||||
* ;; Import the required fd_write WASI function which will write the given io vectors to stdout
|
||||
* ;; The function signature for fd_write is:
|
||||
* ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written
|
||||
* (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)))
|
||||
*
|
||||
* (memory 1)
|
||||
* (export "memory" (memory 0))
|
||||
*
|
||||
* ;; Write 'hello world\n' to memory at an offset of 8 bytes
|
||||
* ;; Note the trailing newline which is required for the text to appear
|
||||
* (data (i32.const 8) "hello world\n")
|
||||
*
|
||||
* (func $main (export "_start")
|
||||
* ;; Creating a new io vector within linear memory
|
||||
* (i32.store (i32.const 0) (i32.const 8)) ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string
|
||||
* (i32.store (i32.const 4) (i32.const 12)) ;; iov.iov_len - The length of the 'hello world\n' string
|
||||
*
|
||||
* (call $fd_write
|
||||
* (i32.const 1) ;; file_descriptor - 1 for stdout
|
||||
* (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0
|
||||
* (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.
|
||||
* (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written
|
||||
* )
|
||||
* drop ;; Discard the number of bytes written from the top of the stack
|
||||
* )
|
||||
* )
|
||||
* ```
|
||||
*
|
||||
* Use [wabt](https://github.com/WebAssembly/wabt) to compile `.wat` to `.wasm`
|
||||
*
|
||||
* ```bash
|
||||
* wat2wasm demo.wat
|
||||
* ```
|
||||
* @experimental
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/wasi.js)
|
||||
*/
|
||||
declare module "wasi" {
|
||||
interface WASIOptions {
|
||||
/**
|
||||
* An array of strings that the WebAssembly application will
|
||||
* see as command line arguments. The first argument is the virtual path to the
|
||||
* WASI command itself.
|
||||
* @default []
|
||||
*/
|
||||
args?: readonly string[] | undefined;
|
||||
/**
|
||||
* An object similar to `process.env` that the WebAssembly
|
||||
* application will see as its environment.
|
||||
* @default {}
|
||||
*/
|
||||
env?: object | undefined;
|
||||
/**
|
||||
* This object represents the WebAssembly application's
|
||||
* sandbox directory structure. The string keys of `preopens` are treated as
|
||||
* directories within the sandbox. The corresponding values in `preopens` are
|
||||
* the real paths to those directories on the host machine.
|
||||
*/
|
||||
preopens?: NodeJS.Dict<string> | undefined;
|
||||
/**
|
||||
* By default, when WASI applications call `__wasi_proc_exit()`
|
||||
* `wasi.start()` will return with the exit code specified rather than terminatng the process.
|
||||
* Setting this option to `false` will cause the Node.js process to exit with
|
||||
* the specified exit code instead.
|
||||
* @default true
|
||||
*/
|
||||
returnOnExit?: boolean | undefined;
|
||||
/**
|
||||
* The file descriptor used as standard input in the WebAssembly application.
|
||||
* @default 0
|
||||
*/
|
||||
stdin?: number | undefined;
|
||||
/**
|
||||
* The file descriptor used as standard output in the WebAssembly application.
|
||||
* @default 1
|
||||
*/
|
||||
stdout?: number | undefined;
|
||||
/**
|
||||
* The file descriptor used as standard error in the WebAssembly application.
|
||||
* @default 2
|
||||
*/
|
||||
stderr?: number | undefined;
|
||||
/**
|
||||
* The version of WASI requested.
|
||||
* Currently the only supported versions are `'unstable'` and `'preview1'`. This option is mandatory.
|
||||
* @since v19.8.0
|
||||
*/
|
||||
version: "unstable" | "preview1";
|
||||
}
|
||||
interface FinalizeBindingsOptions {
|
||||
/**
|
||||
* @default instance.exports.memory
|
||||
*/
|
||||
memory?: object | undefined;
|
||||
}
|
||||
/**
|
||||
* The `WASI` class provides the WASI system call API and additional convenience
|
||||
* methods for working with WASI-based applications. Each `WASI` instance
|
||||
* represents a distinct environment.
|
||||
* @since v13.3.0, v12.16.0
|
||||
*/
|
||||
class WASI {
|
||||
constructor(options?: WASIOptions);
|
||||
/**
|
||||
* Return an import object that can be passed to `WebAssembly.instantiate()` if no other WASM imports are needed beyond those provided by WASI.
|
||||
*
|
||||
* If version `unstable` was passed into the constructor it will return:
|
||||
*
|
||||
* ```js
|
||||
* { wasi_unstable: wasi.wasiImport }
|
||||
* ```
|
||||
*
|
||||
* If version `preview1` was passed into the constructor or no version was specified it will return:
|
||||
*
|
||||
* ```js
|
||||
* { wasi_snapshot_preview1: wasi.wasiImport }
|
||||
* ```
|
||||
* @since v19.8.0
|
||||
*/
|
||||
getImportObject(): object;
|
||||
/**
|
||||
* Attempt to begin execution of `instance` as a WASI command by invoking its `_start()` export. If `instance` does not contain a `_start()` export, or if `instance` contains an `_initialize()`
|
||||
* export, then an exception is thrown.
|
||||
*
|
||||
* `start()` requires that `instance` exports a [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) named `memory`. If
|
||||
* `instance` does not have a `memory` export an exception is thrown.
|
||||
*
|
||||
* If `start()` is called more than once, an exception is thrown.
|
||||
* @since v13.3.0, v12.16.0
|
||||
*/
|
||||
start(instance: object): number; // TODO: avoid DOM dependency until WASM moved to own lib.
|
||||
/**
|
||||
* Attempt to initialize `instance` as a WASI reactor by invoking its `_initialize()` export, if it is present. If `instance` contains a `_start()` export, then an exception is thrown.
|
||||
*
|
||||
* `initialize()` requires that `instance` exports a [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) named `memory`.
|
||||
* If `instance` does not have a `memory` export an exception is thrown.
|
||||
*
|
||||
* If `initialize()` is called more than once, an exception is thrown.
|
||||
* @since v14.6.0, v12.19.0
|
||||
*/
|
||||
initialize(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib.
|
||||
/**
|
||||
* Set up WASI host bindings to `instance` without calling `initialize()`
|
||||
* or `start()`. This method is useful when the WASI module is instantiated in
|
||||
* child threads for sharing the memory across threads.
|
||||
*
|
||||
* `finalizeBindings()` requires that either `instance` exports a
|
||||
* [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) named `memory` or user specify a
|
||||
* [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) object in `options.memory`. If the `memory` is invalid
|
||||
* an exception is thrown.
|
||||
*
|
||||
* `start()` and `initialize()` will call `finalizeBindings()` internally.
|
||||
* If `finalizeBindings()` is called more than once, an exception is thrown.
|
||||
* @since v24.4.0
|
||||
*/
|
||||
finalizeBindings(instance: object, options?: FinalizeBindingsOptions): void;
|
||||
/**
|
||||
* `wasiImport` is an object that implements the WASI system call API. This object
|
||||
* should be passed as the `wasi_snapshot_preview1` import during the instantiation
|
||||
* of a [`WebAssembly.Instance`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance).
|
||||
* @since v13.3.0, v12.16.0
|
||||
*/
|
||||
readonly wasiImport: NodeJS.Dict<any>; // TODO: Narrow to DOM types
|
||||
}
|
||||
}
|
||||
declare module "node:wasi" {
|
||||
export * from "wasi";
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
export {};
|
||||
|
||||
type _AbortController = typeof globalThis extends { onmessage: any } ? {} : AbortController;
|
||||
interface AbortController {
|
||||
readonly signal: AbortSignal;
|
||||
abort(reason?: any): void;
|
||||
}
|
||||
|
||||
type _AbortSignal = typeof globalThis extends { onmessage: any } ? {} : AbortSignal;
|
||||
interface AbortSignal extends EventTarget {
|
||||
readonly aborted: boolean;
|
||||
onabort: ((this: AbortSignal, ev: Event) => any) | null;
|
||||
readonly reason: any;
|
||||
throwIfAborted(): void;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface AbortController extends _AbortController {}
|
||||
var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T
|
||||
: {
|
||||
prototype: AbortController;
|
||||
new(): AbortController;
|
||||
};
|
||||
|
||||
interface AbortSignal extends _AbortSignal {}
|
||||
var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T
|
||||
: {
|
||||
prototype: AbortSignal;
|
||||
new(): AbortSignal;
|
||||
abort(reason?: any): AbortSignal;
|
||||
any(signals: AbortSignal[]): AbortSignal;
|
||||
timeout(milliseconds: number): AbortSignal;
|
||||
};
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
export {};
|
||||
|
||||
import { webcrypto } from "crypto";
|
||||
|
||||
declare global {
|
||||
var Crypto: typeof globalThis extends { onmessage: any; Crypto: infer T } ? T : {
|
||||
prototype: webcrypto.Crypto;
|
||||
new(): webcrypto.Crypto;
|
||||
};
|
||||
|
||||
var CryptoKey: typeof globalThis extends { onmessage: any; CryptoKey: infer T } ? T : {
|
||||
prototype: webcrypto.CryptoKey;
|
||||
new(): webcrypto.CryptoKey;
|
||||
};
|
||||
|
||||
var SubtleCrypto: typeof globalThis extends { onmessage: any; SubtleCrypto: infer T } ? T : {
|
||||
prototype: webcrypto.SubtleCrypto;
|
||||
new(): webcrypto.SubtleCrypto;
|
||||
supports(
|
||||
operation: string,
|
||||
algorithm: webcrypto.AlgorithmIdentifier,
|
||||
length?: number,
|
||||
): boolean;
|
||||
supports(
|
||||
operation: string,
|
||||
algorithm: webcrypto.AlgorithmIdentifier,
|
||||
additionalAlgorithm: webcrypto.AlgorithmIdentifier,
|
||||
): boolean;
|
||||
};
|
||||
|
||||
var crypto: typeof globalThis extends { onmessage: any; crypto: infer T } ? T : webcrypto.Crypto;
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
export {};
|
||||
|
||||
type _DOMException = typeof globalThis extends { onmessage: any } ? {} : DOMException;
|
||||
interface DOMException extends Error {
|
||||
readonly code: number;
|
||||
readonly message: string;
|
||||
readonly name: string;
|
||||
readonly INDEX_SIZE_ERR: 1;
|
||||
readonly DOMSTRING_SIZE_ERR: 2;
|
||||
readonly HIERARCHY_REQUEST_ERR: 3;
|
||||
readonly WRONG_DOCUMENT_ERR: 4;
|
||||
readonly INVALID_CHARACTER_ERR: 5;
|
||||
readonly NO_DATA_ALLOWED_ERR: 6;
|
||||
readonly NO_MODIFICATION_ALLOWED_ERR: 7;
|
||||
readonly NOT_FOUND_ERR: 8;
|
||||
readonly NOT_SUPPORTED_ERR: 9;
|
||||
readonly INUSE_ATTRIBUTE_ERR: 10;
|
||||
readonly INVALID_STATE_ERR: 11;
|
||||
readonly SYNTAX_ERR: 12;
|
||||
readonly INVALID_MODIFICATION_ERR: 13;
|
||||
readonly NAMESPACE_ERR: 14;
|
||||
readonly INVALID_ACCESS_ERR: 15;
|
||||
readonly VALIDATION_ERR: 16;
|
||||
readonly TYPE_MISMATCH_ERR: 17;
|
||||
readonly SECURITY_ERR: 18;
|
||||
readonly NETWORK_ERR: 19;
|
||||
readonly ABORT_ERR: 20;
|
||||
readonly URL_MISMATCH_ERR: 21;
|
||||
readonly QUOTA_EXCEEDED_ERR: 22;
|
||||
readonly TIMEOUT_ERR: 23;
|
||||
readonly INVALID_NODE_TYPE_ERR: 24;
|
||||
readonly DATA_CLONE_ERR: 25;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface DOMException extends _DOMException {}
|
||||
var DOMException: typeof globalThis extends { onmessage: any; DOMException: infer T } ? T
|
||||
: {
|
||||
prototype: DOMException;
|
||||
new(message?: string, name?: string): DOMException;
|
||||
new(message?: string, options?: { name?: string; cause?: unknown }): DOMException;
|
||||
readonly INDEX_SIZE_ERR: 1;
|
||||
readonly DOMSTRING_SIZE_ERR: 2;
|
||||
readonly HIERARCHY_REQUEST_ERR: 3;
|
||||
readonly WRONG_DOCUMENT_ERR: 4;
|
||||
readonly INVALID_CHARACTER_ERR: 5;
|
||||
readonly NO_DATA_ALLOWED_ERR: 6;
|
||||
readonly NO_MODIFICATION_ALLOWED_ERR: 7;
|
||||
readonly NOT_FOUND_ERR: 8;
|
||||
readonly NOT_SUPPORTED_ERR: 9;
|
||||
readonly INUSE_ATTRIBUTE_ERR: 10;
|
||||
readonly INVALID_STATE_ERR: 11;
|
||||
readonly SYNTAX_ERR: 12;
|
||||
readonly INVALID_MODIFICATION_ERR: 13;
|
||||
readonly NAMESPACE_ERR: 14;
|
||||
readonly INVALID_ACCESS_ERR: 15;
|
||||
readonly VALIDATION_ERR: 16;
|
||||
readonly TYPE_MISMATCH_ERR: 17;
|
||||
readonly SECURITY_ERR: 18;
|
||||
readonly NETWORK_ERR: 19;
|
||||
readonly ABORT_ERR: 20;
|
||||
readonly URL_MISMATCH_ERR: 21;
|
||||
readonly QUOTA_EXCEEDED_ERR: 22;
|
||||
readonly TIMEOUT_ERR: 23;
|
||||
readonly INVALID_NODE_TYPE_ERR: 24;
|
||||
readonly DATA_CLONE_ERR: 25;
|
||||
};
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
export {};
|
||||
|
||||
interface AddEventListenerOptions extends EventListenerOptions {
|
||||
once?: boolean;
|
||||
passive?: boolean;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
type _CustomEvent<T = any> = typeof globalThis extends { onmessage: any } ? {} : CustomEvent<T>;
|
||||
interface CustomEvent<T = any> extends Event {
|
||||
readonly detail: T;
|
||||
}
|
||||
|
||||
interface CustomEventInit<T = any> extends EventInit {
|
||||
detail?: T;
|
||||
}
|
||||
|
||||
type _Event = typeof globalThis extends { onmessage: any } ? {} : Event;
|
||||
interface Event {
|
||||
readonly bubbles: boolean;
|
||||
cancelBubble: boolean;
|
||||
readonly cancelable: boolean;
|
||||
readonly composed: boolean;
|
||||
readonly currentTarget: EventTarget | null;
|
||||
readonly defaultPrevented: boolean;
|
||||
readonly eventPhase: 0 | 2;
|
||||
readonly isTrusted: boolean;
|
||||
returnValue: boolean;
|
||||
readonly srcElement: EventTarget | null;
|
||||
readonly target: EventTarget | null;
|
||||
readonly timeStamp: number;
|
||||
readonly type: string;
|
||||
composedPath(): [EventTarget?];
|
||||
initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void;
|
||||
preventDefault(): void;
|
||||
stopImmediatePropagation(): void;
|
||||
stopPropagation(): void;
|
||||
}
|
||||
|
||||
interface EventInit {
|
||||
bubbles?: boolean;
|
||||
cancelable?: boolean;
|
||||
composed?: boolean;
|
||||
}
|
||||
|
||||
interface EventListener {
|
||||
(evt: Event): void;
|
||||
}
|
||||
|
||||
interface EventListenerObject {
|
||||
handleEvent(object: Event): void;
|
||||
}
|
||||
|
||||
type _EventListenerOptions = typeof globalThis extends { onmessage: any } ? {} : EventListenerOptions;
|
||||
interface EventListenerOptions {
|
||||
capture?: boolean;
|
||||
}
|
||||
|
||||
type _EventTarget = typeof globalThis extends { onmessage: any } ? {} : EventTarget;
|
||||
interface EventTarget {
|
||||
addEventListener(
|
||||
type: string,
|
||||
listener: EventListener | EventListenerObject,
|
||||
options?: AddEventListenerOptions | boolean,
|
||||
): void;
|
||||
dispatchEvent(event: Event): boolean;
|
||||
removeEventListener(
|
||||
type: string,
|
||||
listener: EventListener | EventListenerObject,
|
||||
options?: EventListenerOptions | boolean,
|
||||
): void;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface CustomEvent<T = any> extends _CustomEvent<T> {}
|
||||
var CustomEvent: typeof globalThis extends { onmessage: any; CustomEvent: infer T } ? T
|
||||
: {
|
||||
prototype: CustomEvent;
|
||||
new<T>(type: string, eventInitDict?: CustomEventInit<T>): CustomEvent<T>;
|
||||
};
|
||||
|
||||
interface Event extends _Event {}
|
||||
var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T
|
||||
: {
|
||||
prototype: Event;
|
||||
new(type: string, eventInitDict?: EventInit): Event;
|
||||
};
|
||||
|
||||
interface EventListenerOptions extends _EventListenerOptions {}
|
||||
|
||||
interface EventTarget extends _EventTarget {}
|
||||
var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T
|
||||
: {
|
||||
prototype: EventTarget;
|
||||
new(): EventTarget;
|
||||
};
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
export {};
|
||||
|
||||
import * as undici from "undici-types";
|
||||
|
||||
type _CloseEvent = typeof globalThis extends { onmessage: any } ? {} : undici.CloseEvent;
|
||||
type _CloseEventInit = typeof globalThis extends { onmessage: any } ? {} : undici.CloseEventInit;
|
||||
type _EventSource = typeof globalThis extends { onmessage: any } ? {} : undici.EventSource;
|
||||
type _EventSourceInit = typeof globalThis extends { onmessage: any } ? {} : undici.EventSourceInit;
|
||||
type _FormData = typeof globalThis extends { onmessage: any } ? {} : undici.FormData;
|
||||
type _Headers = typeof globalThis extends { onmessage: any } ? {} : undici.Headers;
|
||||
type _MessageEvent = typeof globalThis extends { onmessage: any } ? {} : undici.MessageEvent;
|
||||
type _MessageEventInit = typeof globalThis extends { onmessage: any } ? {} : undici.MessageEventInit;
|
||||
type _Request = typeof globalThis extends { onmessage: any } ? {} : undici.Request;
|
||||
type _RequestInit = typeof globalThis extends { onmessage: any } ? {} : undici.RequestInit;
|
||||
type _Response = typeof globalThis extends { onmessage: any } ? {} : undici.Response;
|
||||
type _ResponseInit = typeof globalThis extends { onmessage: any } ? {} : undici.ResponseInit;
|
||||
type _WebSocket = typeof globalThis extends { onmessage: any } ? {} : undici.WebSocket;
|
||||
type _WebSocketInit = typeof globalThis extends { onmessage: any } ? {} : undici.WebSocketInit;
|
||||
|
||||
declare global {
|
||||
function fetch(
|
||||
input: string | URL | Request,
|
||||
init?: RequestInit,
|
||||
): Promise<Response>;
|
||||
|
||||
interface CloseEvent extends _CloseEvent {}
|
||||
var CloseEvent: typeof globalThis extends { onmessage: any; CloseEvent: infer T } ? T : typeof undici.CloseEvent;
|
||||
|
||||
interface CloseEventInit extends _CloseEventInit {}
|
||||
|
||||
interface EventSource extends _EventSource {}
|
||||
var EventSource: typeof globalThis extends { onmessage: any; EventSource: infer T } ? T : typeof undici.EventSource;
|
||||
|
||||
interface EventSourceInit extends _EventSourceInit {}
|
||||
|
||||
interface FormData extends _FormData {}
|
||||
var FormData: typeof globalThis extends { onmessage: any; FormData: infer T } ? T : typeof undici.FormData;
|
||||
|
||||
interface Headers extends _Headers {}
|
||||
var Headers: typeof globalThis extends { onmessage: any; Headers: infer T } ? T : typeof undici.Headers;
|
||||
|
||||
interface MessageEvent extends _MessageEvent {}
|
||||
var MessageEvent: typeof globalThis extends { onmessage: any; MessageEvent: infer T } ? T
|
||||
: typeof undici.MessageEvent;
|
||||
|
||||
interface MessageEventInit extends _MessageEventInit {}
|
||||
|
||||
interface Request extends _Request {}
|
||||
var Request: typeof globalThis extends { onmessage: any; Request: infer T } ? T : typeof undici.Request;
|
||||
|
||||
interface RequestInit extends _RequestInit {}
|
||||
|
||||
interface Response extends _Response {}
|
||||
var Response: typeof globalThis extends { onmessage: any; Response: infer T } ? T : typeof undici.Response;
|
||||
|
||||
interface ResponseInit extends _ResponseInit {}
|
||||
|
||||
interface WebSocket extends _WebSocket {}
|
||||
var WebSocket: typeof globalThis extends { onmessage: any; WebSocket: infer T } ? T : typeof undici.WebSocket;
|
||||
|
||||
interface WebSocketInit extends _WebSocketInit {}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
export {};
|
||||
|
||||
import { LockManager } from "worker_threads";
|
||||
|
||||
// lib.webworker has `WorkerNavigator` rather than `Navigator`, so conditionals use `onabort` instead of `onmessage`
|
||||
type _Navigator = typeof globalThis extends { onabort: any } ? {} : Navigator;
|
||||
interface Navigator {
|
||||
readonly hardwareConcurrency: number;
|
||||
readonly language: string;
|
||||
readonly languages: readonly string[];
|
||||
readonly locks: LockManager;
|
||||
readonly platform: string;
|
||||
readonly userAgent: string;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Navigator extends _Navigator {}
|
||||
var Navigator: typeof globalThis extends { onabort: any; Navigator: infer T } ? T : {
|
||||
prototype: Navigator;
|
||||
new(): Navigator;
|
||||
};
|
||||
|
||||
// Needs conditional inference for lib.dom and lib.webworker compatibility
|
||||
var navigator: typeof globalThis extends { onmessage: any; navigator: infer T } ? T : Navigator;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
export {};
|
||||
|
||||
// These interfaces are absent from lib.webworker, so the conditionals use `onabort` rather than `onmessage`
|
||||
type _Storage = typeof globalThis extends { onabort: any } ? {} : Storage;
|
||||
interface Storage {
|
||||
readonly length: number;
|
||||
clear(): void;
|
||||
getItem(key: string): string | null;
|
||||
key(index: number): string | null;
|
||||
removeItem(key: string): void;
|
||||
setItem(key: string, value: string): void;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Storage extends _Storage {}
|
||||
var Storage: typeof globalThis extends { onabort: any; Storage: infer T } ? T : {
|
||||
prototype: Storage;
|
||||
new(): Storage;
|
||||
};
|
||||
|
||||
var localStorage: Storage;
|
||||
var sessionStorage: Storage;
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
export {};
|
||||
|
||||
import * as webstreams from "stream/web";
|
||||
|
||||
type _CompressionStream = typeof globalThis extends { onmessage: any } ? {} : webstreams.CompressionStream;
|
||||
type _DecompressionStream = typeof globalThis extends { onmessage: any } ? {} : webstreams.DecompressionStream;
|
||||
|
||||
declare global {
|
||||
interface CompressionStream extends _CompressionStream {}
|
||||
var CompressionStream: typeof globalThis extends {
|
||||
onmessage: any;
|
||||
CompressionStream: infer T;
|
||||
} ? T
|
||||
: typeof webstreams.CompressionStream;
|
||||
|
||||
interface DecompressionStream extends _DecompressionStream {}
|
||||
var DecompressionStream: typeof globalThis extends {
|
||||
onmessage: any;
|
||||
DecompressionStream: infer T;
|
||||
} ? T
|
||||
: typeof webstreams.DecompressionStream;
|
||||
}
|
||||
+894
@@ -0,0 +1,894 @@
|
||||
/**
|
||||
* The `node:worker_threads` module enables the use of threads that execute
|
||||
* JavaScript in parallel. To access it:
|
||||
*
|
||||
* ```js
|
||||
* import worker_threads from 'node:worker_threads';
|
||||
* ```
|
||||
*
|
||||
* Workers (threads) are useful for performing CPU-intensive JavaScript operations.
|
||||
* They do not help much with I/O-intensive work. The Node.js built-in
|
||||
* asynchronous I/O operations are more efficient than Workers can be.
|
||||
*
|
||||
* Unlike `child_process` or `cluster`, `worker_threads` can share memory. They do
|
||||
* so by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer` instances.
|
||||
*
|
||||
* ```js
|
||||
* import {
|
||||
* Worker,
|
||||
* isMainThread,
|
||||
* parentPort,
|
||||
* workerData,
|
||||
* } from 'node:worker_threads';
|
||||
*
|
||||
* if (!isMainThread) {
|
||||
* const { parse } = await import('some-js-parsing-library');
|
||||
* const script = workerData;
|
||||
* parentPort.postMessage(parse(script));
|
||||
* }
|
||||
*
|
||||
* export default function parseJSAsync(script) {
|
||||
* return new Promise((resolve, reject) => {
|
||||
* const worker = new Worker(new URL(import.meta.url), {
|
||||
* workerData: script,
|
||||
* });
|
||||
* worker.on('message', resolve);
|
||||
* worker.on('error', reject);
|
||||
* worker.on('exit', (code) => {
|
||||
* if (code !== 0)
|
||||
* reject(new Error(`Worker stopped with exit code ${code}`));
|
||||
* });
|
||||
* });
|
||||
* };
|
||||
* ```
|
||||
*
|
||||
* The above example spawns a Worker thread for each `parseJSAsync()` call. In
|
||||
* practice, use a pool of Workers for these kinds of tasks. Otherwise, the
|
||||
* overhead of creating Workers would likely exceed their benefit.
|
||||
*
|
||||
* When implementing a worker pool, use the `AsyncResource` API to inform
|
||||
* diagnostic tools (e.g. to provide asynchronous stack traces) about the
|
||||
* correlation between tasks and their outcomes. See `"Using AsyncResource for a Worker thread pool"` in the `async_hooks` documentation for an example implementation.
|
||||
*
|
||||
* Worker threads inherit non-process-specific options by default. Refer to `Worker constructor options` to know how to customize worker thread options,
|
||||
* specifically `argv` and `execArgv` options.
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/worker_threads.js)
|
||||
*/
|
||||
declare module "worker_threads" {
|
||||
import { Context } from "node:vm";
|
||||
import { EventEmitter, NodeEventTarget } from "node:events";
|
||||
import { FileHandle } from "node:fs/promises";
|
||||
import { Performance } from "node:perf_hooks";
|
||||
import { Readable, Writable } from "node:stream";
|
||||
import { ReadableStream, TransformStream, WritableStream } from "node:stream/web";
|
||||
import { URL } from "node:url";
|
||||
import { CPUProfileHandle, HeapInfo, HeapProfileHandle } from "node:v8";
|
||||
import { MessageEvent } from "undici-types";
|
||||
const isInternalThread: boolean;
|
||||
const isMainThread: boolean;
|
||||
const parentPort: null | MessagePort;
|
||||
const resourceLimits: ResourceLimits;
|
||||
const SHARE_ENV: unique symbol;
|
||||
const threadId: number;
|
||||
const threadName: string | null;
|
||||
const workerData: any;
|
||||
/**
|
||||
* Instances of the `worker.MessageChannel` class represent an asynchronous,
|
||||
* two-way communications channel.
|
||||
* The `MessageChannel` has no methods of its own. `new MessageChannel()` yields an object with `port1` and `port2` properties, which refer to linked `MessagePort` instances.
|
||||
*
|
||||
* ```js
|
||||
* import { MessageChannel } from 'node:worker_threads';
|
||||
*
|
||||
* const { port1, port2 } = new MessageChannel();
|
||||
* port1.on('message', (message) => console.log('received', message));
|
||||
* port2.postMessage({ foo: 'bar' });
|
||||
* // Prints: received { foo: 'bar' } from the `port1.on('message')` listener
|
||||
* ```
|
||||
* @since v10.5.0
|
||||
*/
|
||||
class MessageChannel {
|
||||
readonly port1: MessagePort;
|
||||
readonly port2: MessagePort;
|
||||
}
|
||||
interface WorkerPerformance extends Pick<Performance, "eventLoopUtilization"> {}
|
||||
type Transferable =
|
||||
| ArrayBuffer
|
||||
| MessagePort
|
||||
| AbortSignal
|
||||
| FileHandle
|
||||
| ReadableStream
|
||||
| WritableStream
|
||||
| TransformStream;
|
||||
/** @deprecated Use `import { Transferable } from "node:worker_threads"` instead. */
|
||||
// TODO: remove in a future major @types/node version.
|
||||
type TransferListItem = Transferable;
|
||||
/**
|
||||
* Instances of the `worker.MessagePort` class represent one end of an
|
||||
* asynchronous, two-way communications channel. It can be used to transfer
|
||||
* structured data, memory regions and other `MessagePort`s between different `Worker`s.
|
||||
*
|
||||
* This implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) s.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
class MessagePort implements EventTarget {
|
||||
/**
|
||||
* Disables further sending of messages on either side of the connection.
|
||||
* This method can be called when no further communication will happen over this `MessagePort`.
|
||||
*
|
||||
* The `'close' event` is emitted on both `MessagePort` instances that
|
||||
* are part of the channel.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
close(): void;
|
||||
/**
|
||||
* Sends a JavaScript value to the receiving side of this channel. `value` is transferred in a way which is compatible with
|
||||
* the [HTML structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
|
||||
*
|
||||
* In particular, the significant differences to `JSON` are:
|
||||
*
|
||||
* * `value` may contain circular references.
|
||||
* * `value` may contain instances of builtin JS types such as `RegExp`s, `BigInt`s, `Map`s, `Set`s, etc.
|
||||
* * `value` may contain typed arrays, both using `ArrayBuffer`s
|
||||
* and `SharedArrayBuffer`s.
|
||||
* * `value` may contain [`WebAssembly.Module`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module) instances.
|
||||
* * `value` may not contain native (C++-backed) objects other than:
|
||||
*
|
||||
* ```js
|
||||
* import { MessageChannel } from 'node:worker_threads';
|
||||
* const { port1, port2 } = new MessageChannel();
|
||||
*
|
||||
* port1.on('message', (message) => console.log(message));
|
||||
*
|
||||
* const circularData = {};
|
||||
* circularData.foo = circularData;
|
||||
* // Prints: { foo: [Circular] }
|
||||
* port2.postMessage(circularData);
|
||||
* ```
|
||||
*
|
||||
* `transferList` may be a list of [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), `MessagePort`, and `FileHandle` objects.
|
||||
* After transferring, they are not usable on the sending side of the channel
|
||||
* anymore (even if they are not contained in `value`). Unlike with `child processes`, transferring handles such as network sockets is currently
|
||||
* not supported.
|
||||
*
|
||||
* If `value` contains [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances, those are accessible
|
||||
* from either thread. They cannot be listed in `transferList`.
|
||||
*
|
||||
* `value` may still contain `ArrayBuffer` instances that are not in `transferList`; in that case, the underlying memory is copied rather than moved.
|
||||
*
|
||||
* ```js
|
||||
* import { MessageChannel } from 'node:worker_threads';
|
||||
* const { port1, port2 } = new MessageChannel();
|
||||
*
|
||||
* port1.on('message', (message) => console.log(message));
|
||||
*
|
||||
* const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
|
||||
* // This posts a copy of `uint8Array`:
|
||||
* port2.postMessage(uint8Array);
|
||||
* // This does not copy data, but renders `uint8Array` unusable:
|
||||
* port2.postMessage(uint8Array, [ uint8Array.buffer ]);
|
||||
*
|
||||
* // The memory for the `sharedUint8Array` is accessible from both the
|
||||
* // original and the copy received by `.on('message')`:
|
||||
* const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
|
||||
* port2.postMessage(sharedUint8Array);
|
||||
*
|
||||
* // This transfers a freshly created message port to the receiver.
|
||||
* // This can be used, for example, to create communication channels between
|
||||
* // multiple `Worker` threads that are children of the same parent thread.
|
||||
* const otherChannel = new MessageChannel();
|
||||
* port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
|
||||
* ```
|
||||
*
|
||||
* The message object is cloned immediately, and can be modified after
|
||||
* posting without having side effects.
|
||||
*
|
||||
* For more information on the serialization and deserialization mechanisms
|
||||
* behind this API, see the `serialization API of the node:v8 module`.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
postMessage(value: any, transferList?: readonly Transferable[]): void;
|
||||
/**
|
||||
* If true, the `MessagePort` object will keep the Node.js event loop active.
|
||||
* @since v18.1.0, v16.17.0
|
||||
*/
|
||||
hasRef(): boolean;
|
||||
/**
|
||||
* Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed port does _not_ let the program exit if it's the only active handle left (the default
|
||||
* behavior). If the port is `ref()`ed, calling `ref()` again has no effect.
|
||||
*
|
||||
* If listeners are attached or removed using `.on('message')`, the port
|
||||
* is `ref()`ed and `unref()`ed automatically depending on whether
|
||||
* listeners for the event exist.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
ref(): void;
|
||||
/**
|
||||
* Calling `unref()` on a port allows the thread to exit if this is the only
|
||||
* active handle in the event system. If the port is already `unref()`ed calling `unref()` again has no effect.
|
||||
*
|
||||
* If listeners are attached or removed using `.on('message')`, the port is `ref()`ed and `unref()`ed automatically depending on whether
|
||||
* listeners for the event exist.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
unref(): void;
|
||||
/**
|
||||
* Starts receiving messages on this `MessagePort`. When using this port
|
||||
* as an event emitter, this is called automatically once `'message'` listeners are attached.
|
||||
*
|
||||
* This method exists for parity with the Web `MessagePort` API. In Node.js,
|
||||
* it is only useful for ignoring messages when no event listener is present.
|
||||
* Node.js also diverges in its handling of `.onmessage`. Setting it
|
||||
* automatically calls `.start()`, but unsetting it lets messages queue up
|
||||
* until a new handler is set or the port is discarded.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
start(): void;
|
||||
addListener(event: "close", listener: (ev: Event) => void): this;
|
||||
addListener(event: "message", listener: (value: any) => void): this;
|
||||
addListener(event: "messageerror", listener: (error: Error) => void): this;
|
||||
addListener(event: string, listener: (arg: any) => void): this;
|
||||
emit(event: "close", ev: Event): boolean;
|
||||
emit(event: "message", value: any): boolean;
|
||||
emit(event: "messageerror", error: Error): boolean;
|
||||
emit(event: string, arg: any): boolean;
|
||||
off(event: "close", listener: (ev: Event) => void, options?: EventListenerOptions): this;
|
||||
off(event: "message", listener: (value: any) => void, options?: EventListenerOptions): this;
|
||||
off(event: "messageerror", listener: (error: Error) => void, options?: EventListenerOptions): this;
|
||||
off(event: string, listener: (arg: any) => void, options?: EventListenerOptions): this;
|
||||
on(event: "close", listener: (ev: Event) => void): this;
|
||||
on(event: "message", listener: (value: any) => void): this;
|
||||
on(event: "messageerror", listener: (error: Error) => void): this;
|
||||
on(event: string, listener: (arg: any) => void): this;
|
||||
once(event: "close", listener: (ev: Event) => void): this;
|
||||
once(event: "message", listener: (value: any) => void): this;
|
||||
once(event: "messageerror", listener: (error: Error) => void): this;
|
||||
once(event: string, listener: (arg: any) => void): this;
|
||||
removeListener(event: "close", listener: (ev: Event) => void, options?: EventListenerOptions): this;
|
||||
removeListener(event: "message", listener: (value: any) => void, options?: EventListenerOptions): this;
|
||||
removeListener(event: "messageerror", listener: (error: Error) => void, options?: EventListenerOptions): this;
|
||||
removeListener(event: string, listener: (arg: any) => void, options?: EventListenerOptions): this;
|
||||
}
|
||||
interface MessagePort extends NodeEventTarget {}
|
||||
interface WorkerOptions {
|
||||
/**
|
||||
* List of arguments which would be stringified and appended to
|
||||
* `process.argv` in the worker. This is mostly similar to the `workerData`
|
||||
* but the values will be available on the global `process.argv` as if they
|
||||
* were passed as CLI options to the script.
|
||||
*/
|
||||
argv?: any[] | undefined;
|
||||
env?: NodeJS.Dict<string> | typeof SHARE_ENV | undefined;
|
||||
eval?: boolean | undefined;
|
||||
workerData?: any;
|
||||
stdin?: boolean | undefined;
|
||||
stdout?: boolean | undefined;
|
||||
stderr?: boolean | undefined;
|
||||
execArgv?: string[] | undefined;
|
||||
resourceLimits?: ResourceLimits | undefined;
|
||||
/**
|
||||
* Additional data to send in the first worker message.
|
||||
*/
|
||||
transferList?: Transferable[] | undefined;
|
||||
/**
|
||||
* @default true
|
||||
*/
|
||||
trackUnmanagedFds?: boolean | undefined;
|
||||
/**
|
||||
* An optional `name` to be appended to the worker title
|
||||
* for debugging/identification purposes, making the final title as
|
||||
* `[worker ${id}] ${name}`.
|
||||
*/
|
||||
name?: string | undefined;
|
||||
}
|
||||
interface ResourceLimits {
|
||||
/**
|
||||
* The maximum size of a heap space for recently created objects.
|
||||
*/
|
||||
maxYoungGenerationSizeMb?: number | undefined;
|
||||
/**
|
||||
* The maximum size of the main heap in MB.
|
||||
*/
|
||||
maxOldGenerationSizeMb?: number | undefined;
|
||||
/**
|
||||
* The size of a pre-allocated memory range used for generated code.
|
||||
*/
|
||||
codeRangeSizeMb?: number | undefined;
|
||||
/**
|
||||
* The default maximum stack size for the thread. Small values may lead to unusable Worker instances.
|
||||
* @default 4
|
||||
*/
|
||||
stackSizeMb?: number | undefined;
|
||||
}
|
||||
/**
|
||||
* The `Worker` class represents an independent JavaScript execution thread.
|
||||
* Most Node.js APIs are available inside of it.
|
||||
*
|
||||
* Notable differences inside a Worker environment are:
|
||||
*
|
||||
* * The `process.stdin`, `process.stdout`, and `process.stderr` streams may be redirected by the parent thread.
|
||||
* * The `import { isMainThread } from 'node:worker_threads'` variable is set to `false`.
|
||||
* * The `import { parentPort } from 'node:worker_threads'` message port is available.
|
||||
* * `process.exit()` does not stop the whole program, just the single thread,
|
||||
* and `process.abort()` is not available.
|
||||
* * `process.chdir()` and `process` methods that set group or user ids
|
||||
* are not available.
|
||||
* * `process.env` is a copy of the parent thread's environment variables,
|
||||
* unless otherwise specified. Changes to one copy are not visible in other
|
||||
* threads, and are not visible to native add-ons (unless `worker.SHARE_ENV` is passed as the `env` option to the `Worker` constructor). On Windows, unlike the main thread, a copy of the
|
||||
* environment variables operates in a case-sensitive manner.
|
||||
* * `process.title` cannot be modified.
|
||||
* * Signals are not delivered through `process.on('...')`.
|
||||
* * Execution may stop at any point as a result of `worker.terminate()` being invoked.
|
||||
* * IPC channels from parent processes are not accessible.
|
||||
* * The `trace_events` module is not supported.
|
||||
* * Native add-ons can only be loaded from multiple threads if they fulfill `certain conditions`.
|
||||
*
|
||||
* Creating `Worker` instances inside of other `Worker`s is possible.
|
||||
*
|
||||
* Like [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and the `node:cluster module`, two-way communication
|
||||
* can be achieved through inter-thread message passing. Internally, a `Worker` has
|
||||
* a built-in pair of `MessagePort` s that are already associated with each
|
||||
* other when the `Worker` is created. While the `MessagePort` object on the parent
|
||||
* side is not directly exposed, its functionalities are exposed through `worker.postMessage()` and the `worker.on('message')` event
|
||||
* on the `Worker` object for the parent thread.
|
||||
*
|
||||
* To create custom messaging channels (which is encouraged over using the default
|
||||
* global channel because it facilitates separation of concerns), users can create
|
||||
* a `MessageChannel` object on either thread and pass one of the`MessagePort`s on that `MessageChannel` to the other thread through a
|
||||
* pre-existing channel, such as the global one.
|
||||
*
|
||||
* See `port.postMessage()` for more information on how messages are passed,
|
||||
* and what kind of JavaScript values can be successfully transported through
|
||||
* the thread barrier.
|
||||
*
|
||||
* ```js
|
||||
* import assert from 'node:assert';
|
||||
* import {
|
||||
* Worker, MessageChannel, MessagePort, isMainThread, parentPort,
|
||||
* } from 'node:worker_threads';
|
||||
* if (isMainThread) {
|
||||
* const worker = new Worker(__filename);
|
||||
* const subChannel = new MessageChannel();
|
||||
* worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);
|
||||
* subChannel.port2.on('message', (value) => {
|
||||
* console.log('received:', value);
|
||||
* });
|
||||
* } else {
|
||||
* parentPort.once('message', (value) => {
|
||||
* assert(value.hereIsYourPort instanceof MessagePort);
|
||||
* value.hereIsYourPort.postMessage('the worker is sending this');
|
||||
* value.hereIsYourPort.close();
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
* @since v10.5.0
|
||||
*/
|
||||
class Worker extends EventEmitter {
|
||||
/**
|
||||
* If `stdin: true` was passed to the `Worker` constructor, this is a
|
||||
* writable stream. The data written to this stream will be made available in
|
||||
* the worker thread as `process.stdin`.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
readonly stdin: Writable | null;
|
||||
/**
|
||||
* This is a readable stream which contains data written to `process.stdout` inside the worker thread. If `stdout: true` was not passed to the `Worker` constructor, then data is piped to the
|
||||
* parent thread's `process.stdout` stream.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
readonly stdout: Readable;
|
||||
/**
|
||||
* This is a readable stream which contains data written to `process.stderr` inside the worker thread. If `stderr: true` was not passed to the `Worker` constructor, then data is piped to the
|
||||
* parent thread's `process.stderr` stream.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
readonly stderr: Readable;
|
||||
/**
|
||||
* An integer identifier for the referenced thread. Inside the worker thread,
|
||||
* it is available as `import { threadId } from 'node:worker_threads'`.
|
||||
* This value is unique for each `Worker` instance inside a single process.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
readonly threadId: number;
|
||||
/**
|
||||
* A string identifier for the referenced thread or null if the thread is not running.
|
||||
* Inside the worker thread, it is available as `require('node:worker_threads').threadName`.
|
||||
* @since v24.6.0
|
||||
*/
|
||||
readonly threadName: string | null;
|
||||
/**
|
||||
* Provides the set of JS engine resource constraints for this Worker thread.
|
||||
* If the `resourceLimits` option was passed to the `Worker` constructor,
|
||||
* this matches its values.
|
||||
*
|
||||
* If the worker has stopped, the return value is an empty object.
|
||||
* @since v13.2.0, v12.16.0
|
||||
*/
|
||||
readonly resourceLimits?: ResourceLimits | undefined;
|
||||
/**
|
||||
* An object that can be used to query performance information from a worker
|
||||
* instance.
|
||||
* @since v15.1.0, v14.17.0, v12.22.0
|
||||
*/
|
||||
readonly performance: WorkerPerformance;
|
||||
/**
|
||||
* @param filename The path to the Worker’s main script or module.
|
||||
* Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with ./ or ../,
|
||||
* or a WHATWG URL object using file: protocol. If options.eval is true, this is a string containing JavaScript code rather than a path.
|
||||
*/
|
||||
constructor(filename: string | URL, options?: WorkerOptions);
|
||||
/**
|
||||
* Send a message to the worker that is received via `require('node:worker_threads').parentPort.on('message')`.
|
||||
* See `port.postMessage()` for more details.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
postMessage(value: any, transferList?: readonly Transferable[]): void;
|
||||
/**
|
||||
* Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does _not_ let the program exit if it's the only active handle left (the default
|
||||
* behavior). If the worker is `ref()`ed, calling `ref()` again has
|
||||
* no effect.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
ref(): void;
|
||||
/**
|
||||
* Calling `unref()` on a worker allows the thread to exit if this is the only
|
||||
* active handle in the event system. If the worker is already `unref()`ed calling `unref()` again has no effect.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
unref(): void;
|
||||
/**
|
||||
* Stop all JavaScript execution in the worker thread as soon as possible.
|
||||
* Returns a Promise for the exit code that is fulfilled when the `'exit' event` is emitted.
|
||||
* @since v10.5.0
|
||||
*/
|
||||
terminate(): Promise<number>;
|
||||
/**
|
||||
* This method returns a `Promise` that will resolve to an object identical to {@link process.threadCpuUsage()},
|
||||
* or reject with an [`ERR_WORKER_NOT_RUNNING`](https://nodejs.org/docs/latest-v24.x/api/errors.html#err_worker_not_running) error if the worker is no longer running.
|
||||
* This methods allows the statistics to be observed from outside the actual thread.
|
||||
* @since v24.6.0
|
||||
*/
|
||||
cpuUsage(prev?: NodeJS.CpuUsage): Promise<NodeJS.CpuUsage>;
|
||||
/**
|
||||
* Returns a readable stream for a V8 snapshot of the current state of the Worker.
|
||||
* See `v8.getHeapSnapshot()` for more details.
|
||||
*
|
||||
* If the Worker thread is no longer running, which may occur before the `'exit' event` is emitted, the returned `Promise` is rejected
|
||||
* immediately with an `ERR_WORKER_NOT_RUNNING` error.
|
||||
* @since v13.9.0, v12.17.0
|
||||
* @return A promise for a Readable Stream containing a V8 heap snapshot
|
||||
*/
|
||||
getHeapSnapshot(): Promise<Readable>;
|
||||
/**
|
||||
* This method returns a `Promise` that will resolve to an object identical to `v8.getHeapStatistics()`,
|
||||
* or reject with an `ERR_WORKER_NOT_RUNNING` error if the worker is no longer running.
|
||||
* This methods allows the statistics to be observed from outside the actual thread.
|
||||
* @since v24.0.0
|
||||
*/
|
||||
getHeapStatistics(): Promise<HeapInfo>;
|
||||
/**
|
||||
* Starting a CPU profile then return a Promise that fulfills with an error
|
||||
* or an `CPUProfileHandle` object. This API supports `await using` syntax.
|
||||
*
|
||||
* ```js
|
||||
* const { Worker } = require('node:worker_threads');
|
||||
*
|
||||
* const worker = new Worker(`
|
||||
* const { parentPort } = require('worker_threads');
|
||||
* parentPort.on('message', () => {});
|
||||
* `, { eval: true });
|
||||
*
|
||||
* worker.on('online', async () => {
|
||||
* const handle = await worker.startCpuProfile();
|
||||
* const profile = await handle.stop();
|
||||
* console.log(profile);
|
||||
* worker.terminate();
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* `await using` example.
|
||||
*
|
||||
* ```js
|
||||
* const { Worker } = require('node:worker_threads');
|
||||
*
|
||||
* const w = new Worker(`
|
||||
* const { parentPort } = require('node:worker_threads');
|
||||
* parentPort.on('message', () => {});
|
||||
* `, { eval: true });
|
||||
*
|
||||
* w.on('online', async () => {
|
||||
* // Stop profile automatically when return and profile will be discarded
|
||||
* await using handle = await w.startCpuProfile();
|
||||
* });
|
||||
* ```
|
||||
* @since v24.8.0
|
||||
*/
|
||||
startCpuProfile(): Promise<CPUProfileHandle>;
|
||||
/**
|
||||
* Starting a Heap profile then return a Promise that fulfills with an error
|
||||
* or an `HeapProfileHandle` object. This API supports `await using` syntax.
|
||||
*
|
||||
* ```js
|
||||
* const { Worker } = require('node:worker_threads');
|
||||
*
|
||||
* const worker = new Worker(`
|
||||
* const { parentPort } = require('worker_threads');
|
||||
* parentPort.on('message', () => {});
|
||||
* `, { eval: true });
|
||||
*
|
||||
* worker.on('online', async () => {
|
||||
* const handle = await worker.startHeapProfile();
|
||||
* const profile = await handle.stop();
|
||||
* console.log(profile);
|
||||
* worker.terminate();
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* `await using` example.
|
||||
*
|
||||
* ```js
|
||||
* const { Worker } = require('node:worker_threads');
|
||||
*
|
||||
* const w = new Worker(`
|
||||
* const { parentPort } = require('node:worker_threads');
|
||||
* parentPort.on('message', () => {});
|
||||
* `, { eval: true });
|
||||
*
|
||||
* w.on('online', async () => {
|
||||
* // Stop profile automatically when return and profile will be discarded
|
||||
* await using handle = await w.startHeapProfile();
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
startHeapProfile(): Promise<HeapProfileHandle>;
|
||||
/**
|
||||
* Calls `worker.terminate()` when the dispose scope is exited.
|
||||
*
|
||||
* ```js
|
||||
* async function example() {
|
||||
* await using worker = new Worker('for (;;) {}', { eval: true });
|
||||
* // Worker is automatically terminate when the scope is exited.
|
||||
* }
|
||||
* ```
|
||||
* @since v24.2.0
|
||||
*/
|
||||
[Symbol.asyncDispose](): Promise<void>;
|
||||
addListener(event: "error", listener: (err: any) => void): this;
|
||||
addListener(event: "exit", listener: (exitCode: number) => void): this;
|
||||
addListener(event: "message", listener: (value: any) => void): this;
|
||||
addListener(event: "messageerror", listener: (error: Error) => void): this;
|
||||
addListener(event: "online", listener: () => void): this;
|
||||
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||
emit(event: "error", err: any): boolean;
|
||||
emit(event: "exit", exitCode: number): boolean;
|
||||
emit(event: "message", value: any): boolean;
|
||||
emit(event: "messageerror", error: Error): boolean;
|
||||
emit(event: "online"): boolean;
|
||||
emit(event: string | symbol, ...args: any[]): boolean;
|
||||
on(event: "error", listener: (err: any) => void): this;
|
||||
on(event: "exit", listener: (exitCode: number) => void): this;
|
||||
on(event: "message", listener: (value: any) => void): this;
|
||||
on(event: "messageerror", listener: (error: Error) => void): this;
|
||||
on(event: "online", listener: () => void): this;
|
||||
on(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||
once(event: "error", listener: (err: any) => void): this;
|
||||
once(event: "exit", listener: (exitCode: number) => void): this;
|
||||
once(event: "message", listener: (value: any) => void): this;
|
||||
once(event: "messageerror", listener: (error: Error) => void): this;
|
||||
once(event: "online", listener: () => void): this;
|
||||
once(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||
prependListener(event: "error", listener: (err: any) => void): this;
|
||||
prependListener(event: "exit", listener: (exitCode: number) => void): this;
|
||||
prependListener(event: "message", listener: (value: any) => void): this;
|
||||
prependListener(event: "messageerror", listener: (error: Error) => void): this;
|
||||
prependListener(event: "online", listener: () => void): this;
|
||||
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||
prependOnceListener(event: "error", listener: (err: any) => void): this;
|
||||
prependOnceListener(event: "exit", listener: (exitCode: number) => void): this;
|
||||
prependOnceListener(event: "message", listener: (value: any) => void): this;
|
||||
prependOnceListener(event: "messageerror", listener: (error: Error) => void): this;
|
||||
prependOnceListener(event: "online", listener: () => void): this;
|
||||
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||
removeListener(event: "error", listener: (err: any) => void): this;
|
||||
removeListener(event: "exit", listener: (exitCode: number) => void): this;
|
||||
removeListener(event: "message", listener: (value: any) => void): this;
|
||||
removeListener(event: "messageerror", listener: (error: Error) => void): this;
|
||||
removeListener(event: "online", listener: () => void): this;
|
||||
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||
off(event: "error", listener: (err: any) => void): this;
|
||||
off(event: "exit", listener: (exitCode: number) => void): this;
|
||||
off(event: "message", listener: (value: any) => void): this;
|
||||
off(event: "messageerror", listener: (error: Error) => void): this;
|
||||
off(event: "online", listener: () => void): this;
|
||||
off(event: string | symbol, listener: (...args: any[]) => void): this;
|
||||
}
|
||||
interface BroadcastChannel extends NodeJS.RefCounted {}
|
||||
/**
|
||||
* Instances of `BroadcastChannel` allow asynchronous one-to-many communication
|
||||
* with all other `BroadcastChannel` instances bound to the same channel name.
|
||||
*
|
||||
* ```js
|
||||
* 'use strict';
|
||||
*
|
||||
* import {
|
||||
* isMainThread,
|
||||
* BroadcastChannel,
|
||||
* Worker,
|
||||
* } from 'node:worker_threads';
|
||||
*
|
||||
* const bc = new BroadcastChannel('hello');
|
||||
*
|
||||
* if (isMainThread) {
|
||||
* let c = 0;
|
||||
* bc.onmessage = (event) => {
|
||||
* console.log(event.data);
|
||||
* if (++c === 10) bc.close();
|
||||
* };
|
||||
* for (let n = 0; n < 10; n++)
|
||||
* new Worker(__filename);
|
||||
* } else {
|
||||
* bc.postMessage('hello from every worker');
|
||||
* bc.close();
|
||||
* }
|
||||
* ```
|
||||
* @since v15.4.0
|
||||
*/
|
||||
class BroadcastChannel extends EventTarget {
|
||||
readonly name: string;
|
||||
/**
|
||||
* Invoked with a single \`MessageEvent\` argument when a message is received.
|
||||
* @since v15.4.0
|
||||
*/
|
||||
onmessage: (message: MessageEvent) => void;
|
||||
/**
|
||||
* Invoked with a received message cannot be deserialized.
|
||||
* @since v15.4.0
|
||||
*/
|
||||
onmessageerror: (message: MessageEvent) => void;
|
||||
constructor(name: string);
|
||||
/**
|
||||
* Closes the `BroadcastChannel` connection.
|
||||
* @since v15.4.0
|
||||
*/
|
||||
close(): void;
|
||||
/**
|
||||
* @since v15.4.0
|
||||
* @param message Any cloneable JavaScript value.
|
||||
*/
|
||||
postMessage(message: unknown): void;
|
||||
}
|
||||
interface Lock {
|
||||
readonly mode: LockMode;
|
||||
readonly name: string;
|
||||
}
|
||||
interface LockGrantedCallback<T> {
|
||||
(lock: Lock | null): T;
|
||||
}
|
||||
interface LockInfo {
|
||||
clientId: string;
|
||||
mode: LockMode;
|
||||
name: string;
|
||||
}
|
||||
interface LockManager {
|
||||
query(): Promise<LockManagerSnapshot>;
|
||||
request<T>(name: string, callback: LockGrantedCallback<T>): Promise<Awaited<T>>;
|
||||
request<T>(name: string, options: LockOptions, callback: LockGrantedCallback<T>): Promise<Awaited<T>>;
|
||||
}
|
||||
interface LockManagerSnapshot {
|
||||
held: LockInfo[];
|
||||
pending: LockInfo[];
|
||||
}
|
||||
type LockMode = "exclusive" | "shared";
|
||||
interface LockOptions {
|
||||
ifAvailable?: boolean;
|
||||
mode?: LockMode;
|
||||
signal?: AbortSignal;
|
||||
steal?: boolean;
|
||||
}
|
||||
var locks: LockManager;
|
||||
/**
|
||||
* Mark an object as not transferable. If `object` occurs in the transfer list of
|
||||
* a {@link MessagePort.postMessage port.postMessage()} call, it is ignored.
|
||||
*
|
||||
* In particular, this makes sense for objects that can be cloned, rather than
|
||||
* transferred, and which are used by other objects on the sending side.
|
||||
* For example, Node.js marks the `ArrayBuffer`s it uses for its `Buffer pool` with this.
|
||||
*
|
||||
* This operation cannot be undone.
|
||||
*
|
||||
* ```js
|
||||
* import { MessageChannel, markAsUntransferable } from 'node:worker_threads';
|
||||
*
|
||||
* const pooledBuffer = new ArrayBuffer(8);
|
||||
* const typedArray1 = new Uint8Array(pooledBuffer);
|
||||
* const typedArray2 = new Float64Array(pooledBuffer);
|
||||
*
|
||||
* markAsUntransferable(pooledBuffer);
|
||||
*
|
||||
* const { port1 } = new MessageChannel();
|
||||
* port1.postMessage(typedArray1, [ typedArray1.buffer ]);
|
||||
*
|
||||
* // The following line prints the contents of typedArray1 -- it still owns
|
||||
* // its memory and has been cloned, not transferred. Without
|
||||
* // `markAsUntransferable()`, this would print an empty Uint8Array.
|
||||
* // typedArray2 is intact as well.
|
||||
* console.log(typedArray1);
|
||||
* console.log(typedArray2);
|
||||
* ```
|
||||
*
|
||||
* There is no equivalent to this API in browsers.
|
||||
* @since v14.5.0, v12.19.0
|
||||
*/
|
||||
function markAsUntransferable(object: object): void;
|
||||
/**
|
||||
* Check if an object is marked as not transferable with
|
||||
* {@link markAsUntransferable}.
|
||||
* @since v21.0.0
|
||||
*/
|
||||
function isMarkedAsUntransferable(object: object): boolean;
|
||||
/**
|
||||
* Mark an object as not cloneable. If `object` is used as `message` in
|
||||
* a `port.postMessage()` call, an error is thrown. This is a no-op if `object` is a
|
||||
* primitive value.
|
||||
*
|
||||
* This has no effect on `ArrayBuffer`, or any `Buffer` like objects.
|
||||
*
|
||||
* This operation cannot be undone.
|
||||
*
|
||||
* ```js
|
||||
* const { markAsUncloneable } = require('node:worker_threads');
|
||||
*
|
||||
* const anyObject = { foo: 'bar' };
|
||||
* markAsUncloneable(anyObject);
|
||||
* const { port1 } = new MessageChannel();
|
||||
* try {
|
||||
* // This will throw an error, because anyObject is not cloneable.
|
||||
* port1.postMessage(anyObject)
|
||||
* } catch (error) {
|
||||
* // error.name === 'DataCloneError'
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* There is no equivalent to this API in browsers.
|
||||
* @since v22.10.0
|
||||
*/
|
||||
function markAsUncloneable(object: object): void;
|
||||
/**
|
||||
* Transfer a `MessagePort` to a different `vm` Context. The original `port` object is rendered unusable, and the returned `MessagePort` instance
|
||||
* takes its place.
|
||||
*
|
||||
* The returned `MessagePort` is an object in the target context and
|
||||
* inherits from its global `Object` class. Objects passed to the [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage) listener are also created in the
|
||||
* target context
|
||||
* and inherit from its global `Object` class.
|
||||
*
|
||||
* However, the created `MessagePort` no longer inherits from [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget), and only
|
||||
* [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage) can be used to receive
|
||||
* events using it.
|
||||
* @since v11.13.0
|
||||
* @param port The message port to transfer.
|
||||
* @param contextifiedSandbox A `contextified` object as returned by the `vm.createContext()` method.
|
||||
*/
|
||||
function moveMessagePortToContext(port: MessagePort, contextifiedSandbox: Context): MessagePort;
|
||||
/**
|
||||
* Receive a single message from a given `MessagePort`. If no message is available,`undefined` is returned, otherwise an object with a single `message` property
|
||||
* that contains the message payload, corresponding to the oldest message in the `MessagePort`'s queue.
|
||||
*
|
||||
* ```js
|
||||
* import { MessageChannel, receiveMessageOnPort } from 'node:worker_threads';
|
||||
* const { port1, port2 } = new MessageChannel();
|
||||
* port1.postMessage({ hello: 'world' });
|
||||
*
|
||||
* console.log(receiveMessageOnPort(port2));
|
||||
* // Prints: { message: { hello: 'world' } }
|
||||
* console.log(receiveMessageOnPort(port2));
|
||||
* // Prints: undefined
|
||||
* ```
|
||||
*
|
||||
* When this function is used, no `'message'` event is emitted and the `onmessage` listener is not invoked.
|
||||
* @since v12.3.0
|
||||
*/
|
||||
function receiveMessageOnPort(port: MessagePort):
|
||||
| {
|
||||
message: any;
|
||||
}
|
||||
| undefined;
|
||||
type Serializable = string | object | number | boolean | bigint;
|
||||
/**
|
||||
* Within a worker thread, `worker.getEnvironmentData()` returns a clone
|
||||
* of data passed to the spawning thread's `worker.setEnvironmentData()`.
|
||||
* Every new `Worker` receives its own copy of the environment data
|
||||
* automatically.
|
||||
*
|
||||
* ```js
|
||||
* import {
|
||||
* Worker,
|
||||
* isMainThread,
|
||||
* setEnvironmentData,
|
||||
* getEnvironmentData,
|
||||
* } from 'node:worker_threads';
|
||||
*
|
||||
* if (isMainThread) {
|
||||
* setEnvironmentData('Hello', 'World!');
|
||||
* const worker = new Worker(new URL(import.meta.url));
|
||||
* } else {
|
||||
* console.log(getEnvironmentData('Hello')); // Prints 'World!'.
|
||||
* }
|
||||
* ```
|
||||
* @since v15.12.0, v14.18.0
|
||||
* @param key Any arbitrary, cloneable JavaScript value that can be used as a {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map Map} key.
|
||||
*/
|
||||
function getEnvironmentData(key: Serializable): Serializable;
|
||||
/**
|
||||
* The `worker.setEnvironmentData()` API sets the content of `worker.getEnvironmentData()` in the current thread and all new `Worker` instances spawned from the current context.
|
||||
* @since v15.12.0, v14.18.0
|
||||
* @param key Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.
|
||||
* @param value Any arbitrary, cloneable JavaScript value that will be cloned and passed automatically to all new `Worker` instances. If `value` is passed as `undefined`, any previously set value
|
||||
* for the `key` will be deleted.
|
||||
*/
|
||||
function setEnvironmentData(key: Serializable, value?: Serializable): void;
|
||||
/**
|
||||
* Sends a value to another worker, identified by its thread ID.
|
||||
* @param threadId The target thread ID. If the thread ID is invalid, a `ERR_WORKER_MESSAGING_FAILED` error will be thrown.
|
||||
* If the target thread ID is the current thread ID, a `ERR_WORKER_MESSAGING_SAME_THREAD` error will be thrown.
|
||||
* @param value The value to send.
|
||||
* @param transferList If one or more `MessagePort`-like objects are passed in value, a `transferList` is required for those items
|
||||
* or `ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST` is thrown. See `port.postMessage()` for more information.
|
||||
* @param timeout Time to wait for the message to be delivered in milliseconds. By default it's `undefined`, which means wait forever.
|
||||
* If the operation times out, a `ERR_WORKER_MESSAGING_TIMEOUT` error is thrown.
|
||||
* @since v22.5.0
|
||||
*/
|
||||
function postMessageToThread(threadId: number, value: any, timeout?: number): Promise<void>;
|
||||
function postMessageToThread(
|
||||
threadId: number,
|
||||
value: any,
|
||||
transferList: readonly Transferable[],
|
||||
timeout?: number,
|
||||
): Promise<void>;
|
||||
|
||||
import {
|
||||
BroadcastChannel as _BroadcastChannel,
|
||||
MessageChannel as _MessageChannel,
|
||||
MessagePort as _MessagePort,
|
||||
} from "worker_threads";
|
||||
global {
|
||||
function structuredClone<T>(
|
||||
value: T,
|
||||
options?: { transfer?: Transferable[] },
|
||||
): T;
|
||||
/**
|
||||
* `BroadcastChannel` class is a global reference for `import { BroadcastChannel } from 'worker_threads'`
|
||||
* https://nodejs.org/api/globals.html#broadcastchannel
|
||||
* @since v18.0.0
|
||||
*/
|
||||
var BroadcastChannel: typeof globalThis extends {
|
||||
onmessage: any;
|
||||
BroadcastChannel: infer T;
|
||||
} ? T
|
||||
: typeof _BroadcastChannel;
|
||||
/**
|
||||
* `MessageChannel` class is a global reference for `import { MessageChannel } from 'worker_threads'`
|
||||
* https://nodejs.org/api/globals.html#messagechannel
|
||||
* @since v15.0.0
|
||||
*/
|
||||
var MessageChannel: typeof globalThis extends {
|
||||
onmessage: any;
|
||||
MessageChannel: infer T;
|
||||
} ? T
|
||||
: typeof _MessageChannel;
|
||||
/**
|
||||
* `MessagePort` class is a global reference for `import { MessagePort } from 'worker_threads'`
|
||||
* https://nodejs.org/api/globals.html#messageport
|
||||
* @since v15.0.0
|
||||
*/
|
||||
var MessagePort: typeof globalThis extends {
|
||||
onmessage: any;
|
||||
MessagePort: infer T;
|
||||
} ? T
|
||||
: typeof _MessagePort;
|
||||
}
|
||||
}
|
||||
declare module "node:worker_threads" {
|
||||
export * from "worker_threads";
|
||||
}
|
||||
+745
@@ -0,0 +1,745 @@
|
||||
/**
|
||||
* The `node:zlib` module provides compression functionality implemented using
|
||||
* Gzip, Deflate/Inflate, and Brotli.
|
||||
*
|
||||
* To access it:
|
||||
*
|
||||
* ```js
|
||||
* import zlib from 'node:zlib';
|
||||
* ```
|
||||
*
|
||||
* Compression and decompression are built around the Node.js
|
||||
* [Streams API](https://nodejs.org/docs/latest-v24.x/api/stream.html).
|
||||
*
|
||||
* Compressing or decompressing a stream (such as a file) can be accomplished by
|
||||
* piping the source stream through a `zlib` `Transform` stream into a destination
|
||||
* stream:
|
||||
*
|
||||
* ```js
|
||||
* import { createGzip } from 'node:zlib';
|
||||
* import { pipeline } from 'node:stream';
|
||||
* import {
|
||||
* createReadStream,
|
||||
* createWriteStream,
|
||||
* } from 'node:fs';
|
||||
*
|
||||
* const gzip = createGzip();
|
||||
* const source = createReadStream('input.txt');
|
||||
* const destination = createWriteStream('input.txt.gz');
|
||||
*
|
||||
* pipeline(source, gzip, destination, (err) => {
|
||||
* if (err) {
|
||||
* console.error('An error occurred:', err);
|
||||
* process.exitCode = 1;
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* // Or, Promisified
|
||||
*
|
||||
* import { promisify } from 'node:util';
|
||||
* const pipe = promisify(pipeline);
|
||||
*
|
||||
* async function do_gzip(input, output) {
|
||||
* const gzip = createGzip();
|
||||
* const source = createReadStream(input);
|
||||
* const destination = createWriteStream(output);
|
||||
* await pipe(source, gzip, destination);
|
||||
* }
|
||||
*
|
||||
* do_gzip('input.txt', 'input.txt.gz')
|
||||
* .catch((err) => {
|
||||
* console.error('An error occurred:', err);
|
||||
* process.exitCode = 1;
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* It is also possible to compress or decompress data in a single step:
|
||||
*
|
||||
* ```js
|
||||
* import { deflate, unzip } from 'node:zlib';
|
||||
*
|
||||
* const input = '.................................';
|
||||
* deflate(input, (err, buffer) => {
|
||||
* if (err) {
|
||||
* console.error('An error occurred:', err);
|
||||
* process.exitCode = 1;
|
||||
* }
|
||||
* console.log(buffer.toString('base64'));
|
||||
* });
|
||||
*
|
||||
* const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
|
||||
* unzip(buffer, (err, buffer) => {
|
||||
* if (err) {
|
||||
* console.error('An error occurred:', err);
|
||||
* process.exitCode = 1;
|
||||
* }
|
||||
* console.log(buffer.toString());
|
||||
* });
|
||||
*
|
||||
* // Or, Promisified
|
||||
*
|
||||
* import { promisify } from 'node:util';
|
||||
* const do_unzip = promisify(unzip);
|
||||
*
|
||||
* do_unzip(buffer)
|
||||
* .then((buf) => console.log(buf.toString()))
|
||||
* .catch((err) => {
|
||||
* console.error('An error occurred:', err);
|
||||
* process.exitCode = 1;
|
||||
* });
|
||||
* ```
|
||||
* @since v0.5.8
|
||||
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/zlib.js)
|
||||
*/
|
||||
declare module "zlib" {
|
||||
import { NonSharedBuffer } from "node:buffer";
|
||||
import * as stream from "node:stream";
|
||||
interface ZlibOptions {
|
||||
/**
|
||||
* @default constants.Z_NO_FLUSH
|
||||
*/
|
||||
flush?: number | undefined;
|
||||
/**
|
||||
* @default constants.Z_FINISH
|
||||
*/
|
||||
finishFlush?: number | undefined;
|
||||
/**
|
||||
* @default 16*1024
|
||||
*/
|
||||
chunkSize?: number | undefined;
|
||||
windowBits?: number | undefined;
|
||||
/** compression only */
|
||||
level?: number | undefined;
|
||||
/** compression only */
|
||||
memLevel?: number | undefined;
|
||||
/** compression only */
|
||||
strategy?: number | undefined;
|
||||
/** deflate/inflate only, empty dictionary by default */
|
||||
dictionary?: NodeJS.ArrayBufferView | ArrayBuffer | undefined;
|
||||
/**
|
||||
* If `true`, returns an object with `buffer` and `engine`.
|
||||
*/
|
||||
info?: boolean | undefined;
|
||||
/**
|
||||
* Limits output size when using convenience methods.
|
||||
* @default buffer.kMaxLength
|
||||
*/
|
||||
maxOutputLength?: number | undefined;
|
||||
}
|
||||
interface BrotliOptions {
|
||||
/**
|
||||
* @default constants.BROTLI_OPERATION_PROCESS
|
||||
*/
|
||||
flush?: number | undefined;
|
||||
/**
|
||||
* @default constants.BROTLI_OPERATION_FINISH
|
||||
*/
|
||||
finishFlush?: number | undefined;
|
||||
/**
|
||||
* @default 16*1024
|
||||
*/
|
||||
chunkSize?: number | undefined;
|
||||
params?:
|
||||
| {
|
||||
/**
|
||||
* Each key is a `constants.BROTLI_*` constant.
|
||||
*/
|
||||
[key: number]: boolean | number;
|
||||
}
|
||||
| undefined;
|
||||
/**
|
||||
* Limits output size when using [convenience methods](https://nodejs.org/docs/latest-v24.x/api/zlib.html#convenience-methods).
|
||||
* @default buffer.kMaxLength
|
||||
*/
|
||||
maxOutputLength?: number | undefined;
|
||||
/**
|
||||
* If `true`, returns an object with `buffer` and `engine`.
|
||||
*/
|
||||
info?: boolean | undefined;
|
||||
}
|
||||
interface ZstdOptions {
|
||||
/**
|
||||
* @default constants.ZSTD_e_continue
|
||||
*/
|
||||
flush?: number | undefined;
|
||||
/**
|
||||
* @default constants.ZSTD_e_end
|
||||
*/
|
||||
finishFlush?: number | undefined;
|
||||
/**
|
||||
* @default 16 * 1024
|
||||
*/
|
||||
chunkSize?: number | undefined;
|
||||
/**
|
||||
* Key-value object containing indexed
|
||||
* [Zstd parameters](https://nodejs.org/docs/latest-v24.x/api/zlib.html#zstd-constants).
|
||||
*/
|
||||
params?: { [key: number]: number | boolean } | undefined;
|
||||
/**
|
||||
* Limits output size when using
|
||||
* [convenience methods](https://nodejs.org/docs/latest-v24.x/api/zlib.html#convenience-methods).
|
||||
* @default buffer.kMaxLength
|
||||
*/
|
||||
maxOutputLength?: number | undefined;
|
||||
/**
|
||||
* If `true`, returns an object with `buffer` and `engine`.
|
||||
*/
|
||||
info?: boolean | undefined;
|
||||
/**
|
||||
* Optional dictionary used to improve compression efficiency when compressing or decompressing data that
|
||||
* shares common patterns with the dictionary.
|
||||
* @since v24.6.0
|
||||
*/
|
||||
dictionary?: NodeJS.ArrayBufferView | undefined;
|
||||
}
|
||||
interface Zlib {
|
||||
readonly bytesWritten: number;
|
||||
shell?: boolean | string | undefined;
|
||||
close(callback?: () => void): void;
|
||||
flush(kind?: number, callback?: () => void): void;
|
||||
flush(callback?: () => void): void;
|
||||
}
|
||||
interface ZlibParams {
|
||||
params(level: number, strategy: number, callback: () => void): void;
|
||||
}
|
||||
interface ZlibReset {
|
||||
reset(): void;
|
||||
}
|
||||
/**
|
||||
* @since v10.16.0
|
||||
*/
|
||||
class BrotliCompress extends stream.Transform {
|
||||
constructor(options?: BrotliOptions);
|
||||
}
|
||||
interface BrotliCompress extends stream.Transform, Zlib {}
|
||||
/**
|
||||
* @since v10.16.0
|
||||
*/
|
||||
class BrotliDecompress extends stream.Transform {
|
||||
constructor(options?: BrotliOptions);
|
||||
}
|
||||
interface BrotliDecompress extends stream.Transform, Zlib {}
|
||||
/**
|
||||
* @since v0.5.8
|
||||
*/
|
||||
class Gzip extends stream.Transform {
|
||||
constructor(options?: ZlibOptions);
|
||||
}
|
||||
interface Gzip extends stream.Transform, Zlib {}
|
||||
/**
|
||||
* @since v0.5.8
|
||||
*/
|
||||
class Gunzip extends stream.Transform {
|
||||
constructor(options?: ZlibOptions);
|
||||
}
|
||||
interface Gunzip extends stream.Transform, Zlib {}
|
||||
/**
|
||||
* @since v0.5.8
|
||||
*/
|
||||
class Deflate extends stream.Transform {
|
||||
constructor(options?: ZlibOptions);
|
||||
}
|
||||
interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams {}
|
||||
/**
|
||||
* @since v0.5.8
|
||||
*/
|
||||
class Inflate extends stream.Transform {
|
||||
constructor(options?: ZlibOptions);
|
||||
}
|
||||
interface Inflate extends stream.Transform, Zlib, ZlibReset {}
|
||||
/**
|
||||
* @since v0.5.8
|
||||
*/
|
||||
class DeflateRaw extends stream.Transform {
|
||||
constructor(options?: ZlibOptions);
|
||||
}
|
||||
interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams {}
|
||||
/**
|
||||
* @since v0.5.8
|
||||
*/
|
||||
class InflateRaw extends stream.Transform {
|
||||
constructor(options?: ZlibOptions);
|
||||
}
|
||||
interface InflateRaw extends stream.Transform, Zlib, ZlibReset {}
|
||||
/**
|
||||
* @since v0.5.8
|
||||
*/
|
||||
class Unzip extends stream.Transform {
|
||||
constructor(options?: ZlibOptions);
|
||||
}
|
||||
interface Unzip extends stream.Transform, Zlib {}
|
||||
/**
|
||||
* @since v22.15.0
|
||||
* @experimental
|
||||
*/
|
||||
class ZstdCompress extends stream.Transform {
|
||||
constructor(options?: ZstdOptions);
|
||||
}
|
||||
interface ZstdCompress extends stream.Transform, Zlib {}
|
||||
/**
|
||||
* @since v22.15.0
|
||||
* @experimental
|
||||
*/
|
||||
class ZstdDecompress extends stream.Transform {
|
||||
constructor(options?: ZstdOptions);
|
||||
}
|
||||
interface ZstdDecompress extends stream.Transform, Zlib {}
|
||||
/**
|
||||
* Computes a 32-bit [Cyclic Redundancy Check](https://en.wikipedia.org/wiki/Cyclic_redundancy_check) checksum of `data`.
|
||||
* If `value` is specified, it is used as the starting value of the checksum, otherwise, 0 is used as the starting value.
|
||||
* @param data When `data` is a string, it will be encoded as UTF-8 before being used for computation.
|
||||
* @param value An optional starting value. It must be a 32-bit unsigned integer. @default 0
|
||||
* @returns A 32-bit unsigned integer containing the checksum.
|
||||
* @since v22.2.0
|
||||
*/
|
||||
function crc32(data: string | NodeJS.ArrayBufferView, value?: number): number;
|
||||
/**
|
||||
* Creates and returns a new `BrotliCompress` object.
|
||||
* @since v11.7.0, v10.16.0
|
||||
*/
|
||||
function createBrotliCompress(options?: BrotliOptions): BrotliCompress;
|
||||
/**
|
||||
* Creates and returns a new `BrotliDecompress` object.
|
||||
* @since v11.7.0, v10.16.0
|
||||
*/
|
||||
function createBrotliDecompress(options?: BrotliOptions): BrotliDecompress;
|
||||
/**
|
||||
* Creates and returns a new `Gzip` object.
|
||||
* See `example`.
|
||||
* @since v0.5.8
|
||||
*/
|
||||
function createGzip(options?: ZlibOptions): Gzip;
|
||||
/**
|
||||
* Creates and returns a new `Gunzip` object.
|
||||
* @since v0.5.8
|
||||
*/
|
||||
function createGunzip(options?: ZlibOptions): Gunzip;
|
||||
/**
|
||||
* Creates and returns a new `Deflate` object.
|
||||
* @since v0.5.8
|
||||
*/
|
||||
function createDeflate(options?: ZlibOptions): Deflate;
|
||||
/**
|
||||
* Creates and returns a new `Inflate` object.
|
||||
* @since v0.5.8
|
||||
*/
|
||||
function createInflate(options?: ZlibOptions): Inflate;
|
||||
/**
|
||||
* Creates and returns a new `DeflateRaw` object.
|
||||
*
|
||||
* An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when `windowBits` is set to 8 for raw deflate streams. zlib would automatically set `windowBits` to 9 if was initially set to 8. Newer
|
||||
* versions of zlib will throw an exception,
|
||||
* so Node.js restored the original behavior of upgrading a value of 8 to 9,
|
||||
* since passing `windowBits = 9` to zlib actually results in a compressed stream
|
||||
* that effectively uses an 8-bit window only.
|
||||
* @since v0.5.8
|
||||
*/
|
||||
function createDeflateRaw(options?: ZlibOptions): DeflateRaw;
|
||||
/**
|
||||
* Creates and returns a new `InflateRaw` object.
|
||||
* @since v0.5.8
|
||||
*/
|
||||
function createInflateRaw(options?: ZlibOptions): InflateRaw;
|
||||
/**
|
||||
* Creates and returns a new `Unzip` object.
|
||||
* @since v0.5.8
|
||||
*/
|
||||
function createUnzip(options?: ZlibOptions): Unzip;
|
||||
/**
|
||||
* Creates and returns a new `ZstdCompress` object.
|
||||
* @since v22.15.0
|
||||
*/
|
||||
function createZstdCompress(options?: ZstdOptions): ZstdCompress;
|
||||
/**
|
||||
* Creates and returns a new `ZstdDecompress` object.
|
||||
* @since v22.15.0
|
||||
*/
|
||||
function createZstdDecompress(options?: ZstdOptions): ZstdDecompress;
|
||||
type InputType = string | ArrayBuffer | NodeJS.ArrayBufferView;
|
||||
type CompressCallback = (error: Error | null, result: NonSharedBuffer) => void;
|
||||
/**
|
||||
* @since v11.7.0, v10.16.0
|
||||
*/
|
||||
function brotliCompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void;
|
||||
function brotliCompress(buf: InputType, callback: CompressCallback): void;
|
||||
namespace brotliCompress {
|
||||
function __promisify__(buffer: InputType, options?: BrotliOptions): Promise<NonSharedBuffer>;
|
||||
}
|
||||
/**
|
||||
* Compress a chunk of data with `BrotliCompress`.
|
||||
* @since v11.7.0, v10.16.0
|
||||
*/
|
||||
function brotliCompressSync(buf: InputType, options?: BrotliOptions): NonSharedBuffer;
|
||||
/**
|
||||
* @since v11.7.0, v10.16.0
|
||||
*/
|
||||
function brotliDecompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void;
|
||||
function brotliDecompress(buf: InputType, callback: CompressCallback): void;
|
||||
namespace brotliDecompress {
|
||||
function __promisify__(buffer: InputType, options?: BrotliOptions): Promise<NonSharedBuffer>;
|
||||
}
|
||||
/**
|
||||
* Decompress a chunk of data with `BrotliDecompress`.
|
||||
* @since v11.7.0, v10.16.0
|
||||
*/
|
||||
function brotliDecompressSync(buf: InputType, options?: BrotliOptions): NonSharedBuffer;
|
||||
/**
|
||||
* @since v0.6.0
|
||||
*/
|
||||
function deflate(buf: InputType, callback: CompressCallback): void;
|
||||
function deflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
|
||||
namespace deflate {
|
||||
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
|
||||
}
|
||||
/**
|
||||
* Compress a chunk of data with `Deflate`.
|
||||
* @since v0.11.12
|
||||
*/
|
||||
function deflateSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
|
||||
/**
|
||||
* @since v0.6.0
|
||||
*/
|
||||
function deflateRaw(buf: InputType, callback: CompressCallback): void;
|
||||
function deflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
|
||||
namespace deflateRaw {
|
||||
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
|
||||
}
|
||||
/**
|
||||
* Compress a chunk of data with `DeflateRaw`.
|
||||
* @since v0.11.12
|
||||
*/
|
||||
function deflateRawSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
|
||||
/**
|
||||
* @since v0.6.0
|
||||
*/
|
||||
function gzip(buf: InputType, callback: CompressCallback): void;
|
||||
function gzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
|
||||
namespace gzip {
|
||||
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
|
||||
}
|
||||
/**
|
||||
* Compress a chunk of data with `Gzip`.
|
||||
* @since v0.11.12
|
||||
*/
|
||||
function gzipSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
|
||||
/**
|
||||
* @since v0.6.0
|
||||
*/
|
||||
function gunzip(buf: InputType, callback: CompressCallback): void;
|
||||
function gunzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
|
||||
namespace gunzip {
|
||||
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
|
||||
}
|
||||
/**
|
||||
* Decompress a chunk of data with `Gunzip`.
|
||||
* @since v0.11.12
|
||||
*/
|
||||
function gunzipSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
|
||||
/**
|
||||
* @since v0.6.0
|
||||
*/
|
||||
function inflate(buf: InputType, callback: CompressCallback): void;
|
||||
function inflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
|
||||
namespace inflate {
|
||||
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
|
||||
}
|
||||
/**
|
||||
* Decompress a chunk of data with `Inflate`.
|
||||
* @since v0.11.12
|
||||
*/
|
||||
function inflateSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
|
||||
/**
|
||||
* @since v0.6.0
|
||||
*/
|
||||
function inflateRaw(buf: InputType, callback: CompressCallback): void;
|
||||
function inflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
|
||||
namespace inflateRaw {
|
||||
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
|
||||
}
|
||||
/**
|
||||
* Decompress a chunk of data with `InflateRaw`.
|
||||
* @since v0.11.12
|
||||
*/
|
||||
function inflateRawSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
|
||||
/**
|
||||
* @since v0.6.0
|
||||
*/
|
||||
function unzip(buf: InputType, callback: CompressCallback): void;
|
||||
function unzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
|
||||
namespace unzip {
|
||||
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
|
||||
}
|
||||
/**
|
||||
* Decompress a chunk of data with `Unzip`.
|
||||
* @since v0.11.12
|
||||
*/
|
||||
function unzipSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
|
||||
/**
|
||||
* @since v22.15.0
|
||||
* @experimental
|
||||
*/
|
||||
function zstdCompress(buf: InputType, callback: CompressCallback): void;
|
||||
function zstdCompress(buf: InputType, options: ZstdOptions, callback: CompressCallback): void;
|
||||
namespace zstdCompress {
|
||||
function __promisify__(buffer: InputType, options?: ZstdOptions): Promise<NonSharedBuffer>;
|
||||
}
|
||||
/**
|
||||
* Compress a chunk of data with `ZstdCompress`.
|
||||
* @since v22.15.0
|
||||
* @experimental
|
||||
*/
|
||||
function zstdCompressSync(buf: InputType, options?: ZstdOptions): NonSharedBuffer;
|
||||
/**
|
||||
* @since v22.15.0
|
||||
* @experimental
|
||||
*/
|
||||
function zstdDecompress(buf: InputType, callback: CompressCallback): void;
|
||||
function zstdDecompress(buf: InputType, options: ZstdOptions, callback: CompressCallback): void;
|
||||
namespace zstdDecompress {
|
||||
function __promisify__(buffer: InputType, options?: ZstdOptions): Promise<NonSharedBuffer>;
|
||||
}
|
||||
/**
|
||||
* Decompress a chunk of data with `ZstdDecompress`.
|
||||
* @since v22.15.0
|
||||
* @experimental
|
||||
*/
|
||||
function zstdDecompressSync(buf: InputType, options?: ZstdOptions): NonSharedBuffer;
|
||||
namespace constants {
|
||||
const BROTLI_DECODE: number;
|
||||
const BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: number;
|
||||
const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: number;
|
||||
const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: number;
|
||||
const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: number;
|
||||
const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: number;
|
||||
const BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: number;
|
||||
const BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_DISTANCE: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_PADDING_1: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_PADDING_2: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_RESERVED: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: number;
|
||||
const BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: number;
|
||||
const BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: number;
|
||||
const BROTLI_DECODER_ERROR_UNREACHABLE: number;
|
||||
const BROTLI_DECODER_NEEDS_MORE_INPUT: number;
|
||||
const BROTLI_DECODER_NEEDS_MORE_OUTPUT: number;
|
||||
const BROTLI_DECODER_NO_ERROR: number;
|
||||
const BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: number;
|
||||
const BROTLI_DECODER_PARAM_LARGE_WINDOW: number;
|
||||
const BROTLI_DECODER_RESULT_ERROR: number;
|
||||
const BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: number;
|
||||
const BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: number;
|
||||
const BROTLI_DECODER_RESULT_SUCCESS: number;
|
||||
const BROTLI_DECODER_SUCCESS: number;
|
||||
const BROTLI_DEFAULT_MODE: number;
|
||||
const BROTLI_DEFAULT_QUALITY: number;
|
||||
const BROTLI_DEFAULT_WINDOW: number;
|
||||
const BROTLI_ENCODE: number;
|
||||
const BROTLI_LARGE_MAX_WINDOW_BITS: number;
|
||||
const BROTLI_MAX_INPUT_BLOCK_BITS: number;
|
||||
const BROTLI_MAX_QUALITY: number;
|
||||
const BROTLI_MAX_WINDOW_BITS: number;
|
||||
const BROTLI_MIN_INPUT_BLOCK_BITS: number;
|
||||
const BROTLI_MIN_QUALITY: number;
|
||||
const BROTLI_MIN_WINDOW_BITS: number;
|
||||
const BROTLI_MODE_FONT: number;
|
||||
const BROTLI_MODE_GENERIC: number;
|
||||
const BROTLI_MODE_TEXT: number;
|
||||
const BROTLI_OPERATION_EMIT_METADATA: number;
|
||||
const BROTLI_OPERATION_FINISH: number;
|
||||
const BROTLI_OPERATION_FLUSH: number;
|
||||
const BROTLI_OPERATION_PROCESS: number;
|
||||
const BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: number;
|
||||
const BROTLI_PARAM_LARGE_WINDOW: number;
|
||||
const BROTLI_PARAM_LGBLOCK: number;
|
||||
const BROTLI_PARAM_LGWIN: number;
|
||||
const BROTLI_PARAM_MODE: number;
|
||||
const BROTLI_PARAM_NDIRECT: number;
|
||||
const BROTLI_PARAM_NPOSTFIX: number;
|
||||
const BROTLI_PARAM_QUALITY: number;
|
||||
const BROTLI_PARAM_SIZE_HINT: number;
|
||||
const DEFLATE: number;
|
||||
const DEFLATERAW: number;
|
||||
const GUNZIP: number;
|
||||
const GZIP: number;
|
||||
const INFLATE: number;
|
||||
const INFLATERAW: number;
|
||||
const UNZIP: number;
|
||||
const ZLIB_VERNUM: number;
|
||||
const ZSTD_CLEVEL_DEFAULT: number;
|
||||
const ZSTD_COMPRESS: number;
|
||||
const ZSTD_DECOMPRESS: number;
|
||||
const ZSTD_btlazy2: number;
|
||||
const ZSTD_btopt: number;
|
||||
const ZSTD_btultra: number;
|
||||
const ZSTD_btultra2: number;
|
||||
const ZSTD_c_chainLog: number;
|
||||
const ZSTD_c_checksumFlag: number;
|
||||
const ZSTD_c_compressionLevel: number;
|
||||
const ZSTD_c_contentSizeFlag: number;
|
||||
const ZSTD_c_dictIDFlag: number;
|
||||
const ZSTD_c_enableLongDistanceMatching: number;
|
||||
const ZSTD_c_hashLog: number;
|
||||
const ZSTD_c_jobSize: number;
|
||||
const ZSTD_c_ldmBucketSizeLog: number;
|
||||
const ZSTD_c_ldmHashLog: number;
|
||||
const ZSTD_c_ldmHashRateLog: number;
|
||||
const ZSTD_c_ldmMinMatch: number;
|
||||
const ZSTD_c_minMatch: number;
|
||||
const ZSTD_c_nbWorkers: number;
|
||||
const ZSTD_c_overlapLog: number;
|
||||
const ZSTD_c_searchLog: number;
|
||||
const ZSTD_c_strategy: number;
|
||||
const ZSTD_c_targetLength: number;
|
||||
const ZSTD_c_windowLog: number;
|
||||
const ZSTD_d_windowLogMax: number;
|
||||
const ZSTD_dfast: number;
|
||||
const ZSTD_e_continue: number;
|
||||
const ZSTD_e_end: number;
|
||||
const ZSTD_e_flush: number;
|
||||
const ZSTD_error_GENERIC: number;
|
||||
const ZSTD_error_checksum_wrong: number;
|
||||
const ZSTD_error_corruption_detected: number;
|
||||
const ZSTD_error_dictionaryCreation_failed: number;
|
||||
const ZSTD_error_dictionary_corrupted: number;
|
||||
const ZSTD_error_dictionary_wrong: number;
|
||||
const ZSTD_error_dstBuffer_null: number;
|
||||
const ZSTD_error_dstSize_tooSmall: number;
|
||||
const ZSTD_error_frameParameter_unsupported: number;
|
||||
const ZSTD_error_frameParameter_windowTooLarge: number;
|
||||
const ZSTD_error_init_missing: number;
|
||||
const ZSTD_error_literals_headerWrong: number;
|
||||
const ZSTD_error_maxSymbolValue_tooLarge: number;
|
||||
const ZSTD_error_maxSymbolValue_tooSmall: number;
|
||||
const ZSTD_error_memory_allocation: number;
|
||||
const ZSTD_error_noForwardProgress_destFull: number;
|
||||
const ZSTD_error_noForwardProgress_inputEmpty: number;
|
||||
const ZSTD_error_no_error: number;
|
||||
const ZSTD_error_parameter_combination_unsupported: number;
|
||||
const ZSTD_error_parameter_outOfBound: number;
|
||||
const ZSTD_error_parameter_unsupported: number;
|
||||
const ZSTD_error_prefix_unknown: number;
|
||||
const ZSTD_error_srcSize_wrong: number;
|
||||
const ZSTD_error_stabilityCondition_notRespected: number;
|
||||
const ZSTD_error_stage_wrong: number;
|
||||
const ZSTD_error_tableLog_tooLarge: number;
|
||||
const ZSTD_error_version_unsupported: number;
|
||||
const ZSTD_error_workSpace_tooSmall: number;
|
||||
const ZSTD_fast: number;
|
||||
const ZSTD_greedy: number;
|
||||
const ZSTD_lazy: number;
|
||||
const ZSTD_lazy2: number;
|
||||
const Z_BEST_COMPRESSION: number;
|
||||
const Z_BEST_SPEED: number;
|
||||
const Z_BLOCK: number;
|
||||
const Z_BUF_ERROR: number;
|
||||
const Z_DATA_ERROR: number;
|
||||
const Z_DEFAULT_CHUNK: number;
|
||||
const Z_DEFAULT_COMPRESSION: number;
|
||||
const Z_DEFAULT_LEVEL: number;
|
||||
const Z_DEFAULT_MEMLEVEL: number;
|
||||
const Z_DEFAULT_STRATEGY: number;
|
||||
const Z_DEFAULT_WINDOWBITS: number;
|
||||
const Z_ERRNO: number;
|
||||
const Z_FILTERED: number;
|
||||
const Z_FINISH: number;
|
||||
const Z_FIXED: number;
|
||||
const Z_FULL_FLUSH: number;
|
||||
const Z_HUFFMAN_ONLY: number;
|
||||
const Z_MAX_CHUNK: number;
|
||||
const Z_MAX_LEVEL: number;
|
||||
const Z_MAX_MEMLEVEL: number;
|
||||
const Z_MAX_WINDOWBITS: number;
|
||||
const Z_MEM_ERROR: number;
|
||||
const Z_MIN_CHUNK: number;
|
||||
const Z_MIN_LEVEL: number;
|
||||
const Z_MIN_MEMLEVEL: number;
|
||||
const Z_MIN_WINDOWBITS: number;
|
||||
const Z_NEED_DICT: number;
|
||||
const Z_NO_COMPRESSION: number;
|
||||
const Z_NO_FLUSH: number;
|
||||
const Z_OK: number;
|
||||
const Z_PARTIAL_FLUSH: number;
|
||||
const Z_RLE: number;
|
||||
const Z_STREAM_END: number;
|
||||
const Z_STREAM_ERROR: number;
|
||||
const Z_SYNC_FLUSH: number;
|
||||
const Z_VERSION_ERROR: number;
|
||||
}
|
||||
// Allowed flush values.
|
||||
/** @deprecated Use `constants.Z_NO_FLUSH` */
|
||||
const Z_NO_FLUSH: number;
|
||||
/** @deprecated Use `constants.Z_PARTIAL_FLUSH` */
|
||||
const Z_PARTIAL_FLUSH: number;
|
||||
/** @deprecated Use `constants.Z_SYNC_FLUSH` */
|
||||
const Z_SYNC_FLUSH: number;
|
||||
/** @deprecated Use `constants.Z_FULL_FLUSH` */
|
||||
const Z_FULL_FLUSH: number;
|
||||
/** @deprecated Use `constants.Z_FINISH` */
|
||||
const Z_FINISH: number;
|
||||
/** @deprecated Use `constants.Z_BLOCK` */
|
||||
const Z_BLOCK: number;
|
||||
// Return codes for the compression/decompression functions.
|
||||
// Negative values are errors, positive values are used for special but normal events.
|
||||
/** @deprecated Use `constants.Z_OK` */
|
||||
const Z_OK: number;
|
||||
/** @deprecated Use `constants.Z_STREAM_END` */
|
||||
const Z_STREAM_END: number;
|
||||
/** @deprecated Use `constants.Z_NEED_DICT` */
|
||||
const Z_NEED_DICT: number;
|
||||
/** @deprecated Use `constants.Z_ERRNO` */
|
||||
const Z_ERRNO: number;
|
||||
/** @deprecated Use `constants.Z_STREAM_ERROR` */
|
||||
const Z_STREAM_ERROR: number;
|
||||
/** @deprecated Use `constants.Z_DATA_ERROR` */
|
||||
const Z_DATA_ERROR: number;
|
||||
/** @deprecated Use `constants.Z_MEM_ERROR` */
|
||||
const Z_MEM_ERROR: number;
|
||||
/** @deprecated Use `constants.Z_BUF_ERROR` */
|
||||
const Z_BUF_ERROR: number;
|
||||
/** @deprecated Use `constants.Z_VERSION_ERROR` */
|
||||
const Z_VERSION_ERROR: number;
|
||||
// Compression levels.
|
||||
/** @deprecated Use `constants.Z_NO_COMPRESSION` */
|
||||
const Z_NO_COMPRESSION: number;
|
||||
/** @deprecated Use `constants.Z_BEST_SPEED` */
|
||||
const Z_BEST_SPEED: number;
|
||||
/** @deprecated Use `constants.Z_BEST_COMPRESSION` */
|
||||
const Z_BEST_COMPRESSION: number;
|
||||
/** @deprecated Use `constants.Z_DEFAULT_COMPRESSION` */
|
||||
const Z_DEFAULT_COMPRESSION: number;
|
||||
// Compression strategy.
|
||||
/** @deprecated Use `constants.Z_FILTERED` */
|
||||
const Z_FILTERED: number;
|
||||
/** @deprecated Use `constants.Z_HUFFMAN_ONLY` */
|
||||
const Z_HUFFMAN_ONLY: number;
|
||||
/** @deprecated Use `constants.Z_RLE` */
|
||||
const Z_RLE: number;
|
||||
/** @deprecated Use `constants.Z_FIXED` */
|
||||
const Z_FIXED: number;
|
||||
/** @deprecated Use `constants.Z_DEFAULT_STRATEGY` */
|
||||
const Z_DEFAULT_STRATEGY: number;
|
||||
/** @deprecated */
|
||||
const Z_BINARY: number;
|
||||
/** @deprecated */
|
||||
const Z_TEXT: number;
|
||||
/** @deprecated */
|
||||
const Z_ASCII: number;
|
||||
/** @deprecated */
|
||||
const Z_UNKNOWN: number;
|
||||
/** @deprecated */
|
||||
const Z_DEFLATED: number;
|
||||
}
|
||||
declare module "node:zlib" {
|
||||
export * from "zlib";
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
# Installation
|
||||
> `npm install --save @types/responselike`
|
||||
|
||||
# Summary
|
||||
This package contains type definitions for responselike (https://github.com/lukechilds/responselike#readme).
|
||||
|
||||
# Details
|
||||
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/responselike.
|
||||
## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/responselike/index.d.ts)
|
||||
````ts
|
||||
/// <reference types="node" />
|
||||
|
||||
import { IncomingMessage } from "http";
|
||||
import { Stream } from "stream";
|
||||
|
||||
export = ResponseLike;
|
||||
|
||||
/**
|
||||
* Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage).
|
||||
*/
|
||||
declare class ResponseLike extends Stream.Readable {
|
||||
statusCode: number;
|
||||
headers: { [header: string]: string | string[] | undefined };
|
||||
body: Buffer;
|
||||
url: string;
|
||||
|
||||
/**
|
||||
* @param statusCode HTTP response status code.
|
||||
* @param headers HTTP headers object. Keys will be automatically lowercased.
|
||||
* @param body A Buffer containing the response body. The Buffer contents will be streamable but is also exposed directly as `response.body`.
|
||||
* @param url Request URL string.
|
||||
*/
|
||||
constructor(
|
||||
statusCode: number,
|
||||
headers: { [header: string]: string | string[] | undefined },
|
||||
body: Buffer,
|
||||
url: string,
|
||||
);
|
||||
}
|
||||
|
||||
````
|
||||
|
||||
### Additional Details
|
||||
* Last updated: Tue, 07 Nov 2023 15:11:36 GMT
|
||||
* Dependencies: [@types/node](https://npmjs.com/package/@types/node)
|
||||
|
||||
# Credits
|
||||
These definitions were written by [BendingBender](https://github.com/BendingBender).
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/// <reference types="node" />
|
||||
|
||||
import { IncomingMessage } from "http";
|
||||
import { Stream } from "stream";
|
||||
|
||||
export = ResponseLike;
|
||||
|
||||
/**
|
||||
* Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage).
|
||||
*/
|
||||
declare class ResponseLike extends Stream.Readable {
|
||||
statusCode: number;
|
||||
headers: { [header: string]: string | string[] | undefined };
|
||||
body: Buffer;
|
||||
url: string;
|
||||
|
||||
/**
|
||||
* @param statusCode HTTP response status code.
|
||||
* @param headers HTTP headers object. Keys will be automatically lowercased.
|
||||
* @param body A Buffer containing the response body. The Buffer contents will be streamable but is also exposed directly as `response.body`.
|
||||
* @param url Request URL string.
|
||||
*/
|
||||
constructor(
|
||||
statusCode: number,
|
||||
headers: { [header: string]: string | string[] | undefined },
|
||||
body: Buffer,
|
||||
url: string,
|
||||
);
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@types/responselike",
|
||||
"version": "1.0.3",
|
||||
"description": "TypeScript definitions for responselike",
|
||||
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/responselike",
|
||||
"license": "MIT",
|
||||
"contributors": [
|
||||
{
|
||||
"name": "BendingBender",
|
||||
"githubUsername": "BendingBender",
|
||||
"url": "https://github.com/BendingBender"
|
||||
}
|
||||
],
|
||||
"main": "",
|
||||
"types": "index.d.ts",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
|
||||
"directory": "types/responselike"
|
||||
},
|
||||
"scripts": {},
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
},
|
||||
"typesPublisherContentHash": "ea1d581578b0ef6027b7cd6aa25990bb9ee8723d002d0617acf0aa4d3324aa49",
|
||||
"typeScriptVersion": "4.5"
|
||||
}
|
||||
+533
@@ -0,0 +1,533 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.8.15](https://github.com/xmldom/xmldom/compare/0.8.14...0.8.15)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Security: parsing a deeply or repeatedly namespaced document no longer consumes quadratic memory; the in-scope namespace map is inherited through the prototype chain instead of being copied for every prefix-declaring element (O(N) instead of O(N²)), preventing a denial-of-service reachable from `DOMParser.parseFromString` with default options. Serialized output is byte-identical. [`GHSA-965w-775f-mr7g`](https://github.com/xmldom/xmldom/security/advisories/GHSA-965w-775f-mr7g)
|
||||
- Security: attribute de-duplication during parsing is now O(M) instead of O(M²); the `NamedNodeMap` parse-time dedup path uses a null-prototype membership index, so a well-formed document with a hostile number of duplicate attributes can no longer wedge the parse. Attribute order and duplicate resolution (last value wins, first position kept) are byte-identical, preserving the XML [no-duplicate-attributes well-formedness constraint](https://www.w3.org/TR/xml/#uniqattspec). [`GHSA-8344-3jmq-59r6`](https://github.com/xmldom/xmldom/security/advisories/GHSA-8344-3jmq-59r6)
|
||||
- Security: trimming trailing whitespace from an XML end tag ([`ETag`](https://www.w3.org/TR/xml/#NT-ETag)) is now anchored so it runs in linear time instead of backtracking quadratically on a long whitespace run, preventing a ReDoS reachable from `DOMParser.parseFromString`. Trimmed output is byte-identical. [`GHSA-x4fp-j954-r2f4`](https://github.com/xmldom/xmldom/security/advisories/GHSA-x4fp-j954-r2f4)
|
||||
- Security: malformed-input recovery is now linear instead of quadratic — the malformed tag-name scan terminates at an embedded `<`, and `Node.prototype.normalize()` merges adjacent text nodes in O(K) instead of O(K²) (also reachable programmatically), per [`normalize()`](https://dom.spec.whatwg.org/#dom-node-normalize) in the WHATWG DOM spec. DOM output is unchanged; only the reported error text differs. [`GHSA-93r5-fhx6-vmg9`](https://github.com/xmldom/xmldom/security/advisories/GHSA-93r5-fhx6-vmg9)
|
||||
- Security: `XMLSerializer.serializeToString()` under `{ requireWellFormed: true }` now rejects a DocType `name` that is not a valid XML [`Name`](https://www.w3.org/TR/xml/#NT-Name), throwing `InvalidStateError` — matching the sibling `publicId`/`systemId`/`internalSubset` checks and preventing XML injection via `DocumentType.name`. [`GHSA-27p8-2357-5qqv`](https://github.com/xmldom/xmldom/security/advisories/GHSA-27p8-2357-5qqv)
|
||||
- Security: `XMLSerializer.serializeToString()` under `{ requireWellFormed: true }` now validates a processing-instruction target as an XML [`NCName`](https://www.w3.org/TR/xml-names/#NT-NCName) and rejects a case-insensitive `xml`, throwing `InvalidStateError` — a check `0.8.x` did not previously perform, preventing PI-target injection via `>`, `?`, or whitespace. [`GHSA-c7q8-3ch8-vqpv`](https://github.com/xmldom/xmldom/security/advisories/GHSA-c7q8-3ch8-vqpv)
|
||||
- Security: `Document.createEntityReference()` now rejects an invalid XML [`Name`](https://www.w3.org/TR/xml/#NT-Name) at creation, and `XMLSerializer.serializeToString()` under `{ requireWellFormed: true }` validates an `EntityReference` `nodeName` as an XML `Name`, throwing `InvalidStateError` — preventing XML injection via an entity-reference name. [`GHSA-6gmq-8vp8-gcm6`](https://github.com/xmldom/xmldom/security/advisories/GHSA-6gmq-8vp8-gcm6)
|
||||
- Security: the parser now reports a not-well-formed end tag whose valid name is followed by trailing content as a recoverable `error` instead of accepting it silently, per the XML [`ETag`](https://www.w3.org/TR/xml/#NT-ETag) production; parsing recovers to the byte-identical DOM. Consumers that want strict rejection can escalate the reported `error` to fatal via the parser's `errorHandler`. [`GHSA-6h8r-xr42-gp59`](https://github.com/xmldom/xmldom/security/advisories/GHSA-6h8r-xr42-gp59)
|
||||
|
||||
Thank you,
|
||||
[@ericchiang](https://github.com/ericchiang),
|
||||
[@bhaswanthc](https://github.com/bhaswanthc),
|
||||
[@arpitjain099](https://github.com/arpitjain099),
|
||||
[@Paranoidgrinch](https://github.com/Paranoidgrinch),
|
||||
for your contributions
|
||||
|
||||
## [0.8.14](https://github.com/xmldom/xmldom/compare/0.8.13...0.8.14)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Security: `XMLSerializer.serializeToString()` now also rejects invalid element and attribute names when `{ requireWellFormed: true }` is passed, throwing `InvalidStateError` for a name that is not a valid XML [`QName`](https://www.w3.org/TR/xml-names/#NT-QName) (this covers the namespace prefix, which surfaces in the element qualified name or in a synthesized `xmlns:` declaration). This prevents XML injection via `createElement()` / `setAttribute()`, extending the existing `requireWellFormed` checks to the serialized name set. [`GHSA-w2rr-34g9-rvrj`](https://github.com/xmldom/xmldom/security/advisories/GHSA-w2rr-34g9-rvrj) [`GHSA-4w3w-2rp5-g8jm`](https://github.com/xmldom/xmldom/security/advisories/GHSA-4w3w-2rp5-g8jm)
|
||||
|
||||
Thank you,
|
||||
[@bhaswanthc](https://github.com/bhaswanthc),
|
||||
[@jmestwa-coder](https://github.com/jmestwa-coder),
|
||||
for your contributions
|
||||
|
||||
## [0.8.13](https://github.com/xmldom/xmldom/compare/0.8.12...0.8.13)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Security: `XMLSerializer.serializeToString()` (and `Node.toString()`, `NodeList.toString()`) now accept a `requireWellFormed` option (fourth argument, after `isHtml` and `nodeFilter`). When `{ requireWellFormed: true }` is passed, the serializer throws `InvalidStateError` for injection-prone node content, preventing XML injection via attacker-controlled node data. [`GHSA-j759-j44w-7fr8`](https://github.com/xmldom/xmldom/security/advisories/GHSA-j759-j44w-7fr8) [`GHSA-x6wf-f3px-wcqx`](https://github.com/xmldom/xmldom/security/advisories/GHSA-x6wf-f3px-wcqx) [`GHSA-f6ww-3ggp-fr8h`](https://github.com/xmldom/xmldom/security/advisories/GHSA-f6ww-3ggp-fr8h)
|
||||
- Comment: throws when `data` contains `-->`
|
||||
- ProcessingInstruction: throws when `data` contains `?>`
|
||||
- DocumentType: throws when `publicId` fails `PubidLiteral`, `systemId` fails `SystemLiteral`, or `internalSubset` contains `]>`
|
||||
- Security: DOM traversal operations (`XMLSerializer.serializeToString()`, `Node.prototype.normalize()`, `Node.prototype.cloneNode(true)`, `Document.prototype.importNode(node, true)`, `node.textContent` getter, `getElementsByTagName()` / `getElementsByTagNameNS()` / `getElementsByClassName()` / `getElementById()`) are now iterative. Previously, deeply nested DOM trees would exhaust the JavaScript call stack and throw an unrecoverable `RangeError`. [`GHSA-2v35-w6hq-6mfw`](https://github.com/xmldom/xmldom/security/advisories/GHSA-2v35-w6hq-6mfw)
|
||||
|
||||
Thank you,
|
||||
[@Jvr2022](https://github.com/Jvr2022),
|
||||
[@praveen-kv](https://github.com/praveen-kv),
|
||||
[@TharVid](https://github.com/TharVid),
|
||||
[@decsecre583](https://github.com/decsecre583),
|
||||
[@tlsbollei](https://github.com/tlsbollei),
|
||||
[@KarimTantawey](https://github.com/KarimTantawey),
|
||||
for your contributions
|
||||
|
||||
## [0.8.12](https://github.com/xmldom/xmldom/compare/0.8.11...0.8.12)
|
||||
|
||||
### Fixed
|
||||
|
||||
- preserve trailing whitespace in ProcessingInstruction data [`#962`](https://github.com/xmldom/xmldom/pull/962) / [`#42`](https://github.com/xmldom/xmldom/issues/42)
|
||||
- Security: `createCDATASection` now throws `InvalidCharacterError` when `data` contains `"]]>"`, as required by the [WHATWG DOM spec](https://dom.spec.whatwg.org/#dom-document-createcdatasection). [`GHSA-wh4c-j3r5-mjhp`](https://github.com/xmldom/xmldom/security/advisories/GHSA-wh4c-j3r5-mjhp)
|
||||
- Security: `XMLSerializer` now splits CDATASection nodes whose data contains `"]]>"` into adjacent CDATA sections at serialization time, preventing XML injection via mutation methods (`appendData`, `replaceData`, `.data =`, `.textContent =`). [`GHSA-wh4c-j3r5-mjhp`](https://github.com/xmldom/xmldom/security/advisories/GHSA-wh4c-j3r5-mjhp)
|
||||
|
||||
Code that passes a string containing `"]]>"` to `createCDATASection` and relied on the previously unsafe behavior will now receive `InvalidCharacterError`. Use a mutation method such as `appendData` if you intentionally need `"]]>"` in a CDATASection node's data.
|
||||
|
||||
Thank you,
|
||||
[@thesmartshadow](https://github.com/thesmartshadow),
|
||||
[@stevenobiajulu](https://github.com/stevenobiajulu),
|
||||
for your contributions
|
||||
|
||||
## [0.8.11](https://github.com/xmldom/xmldom/compare/0.8.10...0.8.11)
|
||||
|
||||
### Fixed
|
||||
|
||||
- update `ownerDocument` when moving nodes between documents [`#933`](https://github.com/xmldom/xmldom/pull/933) / [`#932`](https://github.com/xmldom/xmldom/issues/932)
|
||||
|
||||
Thank you, [@shunkica](https://github.com/shunkica), for your contributions
|
||||
|
||||
|
||||
## [0.8.10](https://github.com/xmldom/xmldom/compare/0.8.9...0.8.10)
|
||||
|
||||
### Fixed
|
||||
|
||||
- dom: prevent iteration over deleted items [`#514`](https://github.com/xmldom/xmldom/pull/514)/ [`#499`](https://github.com/xmldom/xmldom/issues/499)
|
||||
|
||||
Thank you, [@qtow](https://github.com/qtow), for your contributions
|
||||
|
||||
|
||||
## [0.8.9](https://github.com/xmldom/xmldom/compare/0.8.8...0.8.9)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Set nodeName property in ProcessingInstruction [`#509`](https://github.com/xmldom/xmldom/pull/509) / [`#505`](https://github.com/xmldom/xmldom/issues/505)
|
||||
|
||||
Thank you, [@cjbarth](https://github.com/cjbarth), for your contributions
|
||||
|
||||
|
||||
## [0.8.8](https://github.com/xmldom/xmldom/compare/0.8.7...0.8.8)
|
||||
|
||||
### Fixed
|
||||
|
||||
- extend list of HTML entities [`#489`](https://github.com/xmldom/xmldom/pull/489)
|
||||
|
||||
Thank you, [@zorkow](https://github.com/zorkow), for your contributions
|
||||
|
||||
## [0.8.7](https://github.com/xmldom/xmldom/compare/0.8.6...0.8.7)
|
||||
|
||||
### Fixed
|
||||
|
||||
- properly parse closing where the last attribute has no value [`#485`](https://github.com/xmldom/xmldom/pull/485) / [`#486`](https://github.com/xmldom/xmldom/issues/486)
|
||||
|
||||
Thank you, [@bulandent](https://github.com/bulandent), for your contributions
|
||||
|
||||
|
||||
## [0.7.10](https://github.com/xmldom/xmldom/compare/0.7.9...0.7.10)
|
||||
|
||||
### Fixed
|
||||
|
||||
- properly parse closing where the last attribute has no value [`#485`](https://github.com/xmldom/xmldom/pull/485) / [`#486`](https://github.com/xmldom/xmldom/issues/486)
|
||||
|
||||
Thank you, [@bulandent](https://github.com/bulandent), for your contributions
|
||||
|
||||
|
||||
## [0.8.6](https://github.com/xmldom/xmldom/compare/0.8.5...0.8.6)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Properly check nodes before replacement [`#457`](https://github.com/xmldom/xmldom/pull/457) / [`#455`](https://github.com/xmldom/xmldom/issues/455) / [`#456`](https://github.com/xmldom/xmldom/issues/456)
|
||||
|
||||
Thank you, [@edemaine](https://github.com/edemaine), [@pedro-l9](https://github.com/pedro-l9), for your contributions
|
||||
|
||||
|
||||
## [0.8.5](https://github.com/xmldom/xmldom/compare/0.8.4...0.8.5)
|
||||
|
||||
### Fixed
|
||||
|
||||
- fix: Restore ES5 compatibility [`#452`](https://github.com/xmldom/xmldom/pull/452) / [`#453`](https://github.com/xmldom/xmldom/issues/453)
|
||||
|
||||
Thank you, [@fengxinming](https://github.com/fengxinming), for your contributions
|
||||
|
||||
|
||||
## [0.8.4](https://github.com/xmldom/xmldom/compare/0.8.3...0.8.4)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Security: Prevent inserting DOM nodes when they are not well-formed [`CVE-2022-39353`](https://github.com/xmldom/xmldom/security/advisories/GHSA-crh6-fp67-6883)
|
||||
In case such a DOM would be created, the part that is not well-formed will be transformed into text nodes, in which xml specific characters like `<` and `>` are encoded accordingly.
|
||||
In the upcoming version 0.9.0 those text nodes will no longer be added and an error will be thrown instead.
|
||||
This change can break your code, if you relied on this behavior, e.g. multiple root elements in the past. We consider it more important to align with the specs that we want to be aligned with, considering the potential security issues that might derive from people not being aware of the difference in behavior.
|
||||
Related Spec: <https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity>
|
||||
|
||||
Thank you, [@frumioj](https://github.com/frumioj), [@cjbarth](https://github.com/cjbarth), [@markgollnick](https://github.com/markgollnick) for your contributions
|
||||
|
||||
|
||||
## [0.8.3](https://github.com/xmldom/xmldom/compare/0.8.3...0.8.2)
|
||||
|
||||
### Fixed
|
||||
- Avoid iterating over prototype properties [`#437`](https://github.com/xmldom/xmldom/pull/437) / [`#436`](https://github.com/xmldom/xmldom/issues/436)
|
||||
|
||||
Thank you, [@Supraja9726](https://github.com/Supraja9726) for your contributions
|
||||
|
||||
|
||||
## [0.8.2](https://github.com/xmldom/xmldom/compare/0.8.1...0.8.2)
|
||||
|
||||
### Fixed
|
||||
- fix(dom): Serialize `>` as specified (#395) [`#58`](https://github.com/xmldom/xmldom/issues/58)
|
||||
|
||||
### Other
|
||||
- docs: Add `nodeType` values to public interface description [`#396`](https://github.com/xmldom/xmldom/pull/396)
|
||||
- test: Add executable examples for node and typescript [`#317`](https://github.com/xmldom/xmldom/pull/317)
|
||||
- fix(dom): Serialize `>` as specified [`#395`](https://github.com/xmldom/xmldom/pull/395)
|
||||
- chore: Add minimal `Object.assign` ponyfill [`#379`](https://github.com/xmldom/xmldom/pull/379)
|
||||
- docs: Refine release documentation [`#378`](https://github.com/xmldom/xmldom/pull/378)
|
||||
- chore: update various dev dependencies
|
||||
|
||||
Thank you [@niklasl](https://github.com/niklasl), [@cburatto](https://github.com/cburatto), [@SheetJSDev](https://github.com/SheetJSDev), [@pyrsmk](https://github.com/pyrsmk) for your contributions
|
||||
|
||||
## [0.8.1](https://github.com/xmldom/xmldom/compare/0.8.0...0.8.1)
|
||||
|
||||
### Fixes
|
||||
- Only use own properties in entityMap [`#374`](https://github.com/xmldom/xmldom/pull/374)
|
||||
|
||||
### Docs
|
||||
- Add security policy [`#365`](https://github.com/xmldom/xmldom/pull/365)
|
||||
- changelog: Correct contributor name and link [`#366`](https://github.com/xmldom/xmldom/pull/366)
|
||||
- Describe release/publish steps [`#358`](https://github.com/xmldom/xmldom/pull/358), [`#376`](https://github.com/xmldom/xmldom/pull/376)
|
||||
- Add snyk package health badge [`#360`](https://github.com/xmldom/xmldom/pull/360)
|
||||
|
||||
|
||||
## [0.8.0](https://github.com/xmldom/xmldom/compare/0.7.5...0.8.0)
|
||||
|
||||
### Fixed
|
||||
- Normalize all line endings according to XML specs [1.0](https://w3.org/TR/xml/#sec-line-ends) and [1.1](https://www.w3.org/TR/xml11/#sec-line-ends) \
|
||||
BREAKING CHANGE: Certain combination of line break characters are normalized to a single `\n` before parsing takes place and will no longer be preserved.
|
||||
- [`#303`](https://github.com/xmldom/xmldom/issues/303) / [`#307`](https://github.com/xmldom/xmldom/pull/307)
|
||||
- [`#49`](https://github.com/xmldom/xmldom/issues/49), [`#97`](https://github.com/xmldom/xmldom/issues/97), [`#324`](https://github.com/xmldom/xmldom/issues/324) / [`#314`](https://github.com/xmldom/xmldom/pull/314)
|
||||
- XMLSerializer: Preserve whitespace character references [`#284`](https://github.com/xmldom/xmldom/issues/284) / [`#310`](https://github.com/xmldom/xmldom/pull/310) \
|
||||
BREAKING CHANGE: If you relied on the not spec compliant preservation of literal `\t`, `\n` or `\r` in **attribute values**.
|
||||
To preserve those you will have to create XML that instead contains the correct numerical (or hexadecimal) equivalent (e.g. `	`, `
`, `
`).
|
||||
- Drop deprecated exports `DOMImplementation` and `XMLSerializer` from `lib/dom-parser.js` [#53](https://github.com/xmldom/xmldom/issues/53) / [`#309`](https://github.com/xmldom/xmldom/pull/309)
|
||||
BREAKING CHANGE: Use the one provided by the main package export.
|
||||
- dom: Remove all links as part of `removeChild` [`#343`](https://github.com/xmldom/xmldom/issues/343) / [`#355`](https://github.com/xmldom/xmldom/pull/355)
|
||||
|
||||
### Chore
|
||||
- ci: Restore latest tested node version to 16.x [`#325`](https://github.com/xmldom/xmldom/pull/325)
|
||||
- ci: Split test and lint steps into jobs [`#111`](https://github.com/xmldom/xmldom/issues/111) / [`#304`](https://github.com/xmldom/xmldom/pull/304)
|
||||
- Pinned and updated devDependencies
|
||||
|
||||
Thank you [@marrus-sh](https://github.com/marrus-sh), [@victorandree](https://github.com/victorandree), [@mdierolf](https://github.com/mdierolf), [@tsabbay](https://github.com/tsabbay), [@fatihpense](https://github.com/fatihpense) for your contributions
|
||||
|
||||
## 0.7.5
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/0.7.4...0.7.5)
|
||||
|
||||
### Fixes:
|
||||
|
||||
- Preserve default namespace when serializing [`#319`](https://github.com/xmldom/xmldom/issues/319) / [`#321`](https://github.com/xmldom/xmldom/pull/321)
|
||||
Thank you, [@lupestro](https://github.com/lupestro)
|
||||
|
||||
## 0.7.4
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/0.7.3...0.7.4)
|
||||
|
||||
### Fixes:
|
||||
|
||||
- Restore ability to parse `__prototype__` attributes [`#315`](https://github.com/xmldom/xmldom/pull/315)
|
||||
Thank you, [@dsimpsonOMF](https://github.com/dsimpsonOMF)
|
||||
|
||||
## 0.7.3
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/0.7.2...0.7.3)
|
||||
|
||||
### Fixes:
|
||||
|
||||
- Add doctype when parsing from string [`#277`](https://github.com/xmldom/xmldom/issues/277) / [`#301`](https://github.com/xmldom/xmldom/pull/301)
|
||||
- Correct typo in error message [`#294`](https://github.com/xmldom/xmldom/pull/294)
|
||||
Thank you, [@rrthomas](https://github.com/rrthomas)
|
||||
|
||||
### Refactor:
|
||||
|
||||
- Improve exports & require statements, new main package entry [`#233`](https://github.com/xmldom/xmldom/pull/233)
|
||||
|
||||
### Docs:
|
||||
|
||||
- Fix Stryker badge [`#298`](https://github.com/xmldom/xmldom/pull/298)
|
||||
- Fix link to help-wanted issues [`#299`](https://github.com/xmldom/xmldom/pull/299)
|
||||
|
||||
### Chore:
|
||||
|
||||
- Execute stryker:dry-run on branches [`#302`](https://github.com/xmldom/xmldom/pull/302)
|
||||
- Fix stryker config [`#300`](https://github.com/xmldom/xmldom/pull/300)
|
||||
- Split test and lint scripts [`#297`](https://github.com/xmldom/xmldom/pull/297)
|
||||
- Switch to stryker dashboard owned by org [`#292`](https://github.com/xmldom/xmldom/pull/292)
|
||||
|
||||
## 0.7.2
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/0.7.1...0.7.2)
|
||||
|
||||
### Fixes:
|
||||
|
||||
- Types: Add index.d.ts to packaged files [`#288`](https://github.com/xmldom/xmldom/pull/288)
|
||||
Thank you, [@forty](https://github.com/forty)
|
||||
|
||||
## 0.7.1
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/0.7.0...0.7.1)
|
||||
|
||||
### Fixes:
|
||||
|
||||
- Types: Copy types from DefinitelyTyped [`#283`](https://github.com/xmldom/xmldom/pull/283)
|
||||
Thank you, [@kachkaev](https://github.com/kachkaev)
|
||||
|
||||
### Chore:
|
||||
- package.json: remove author, maintainers, etc. [`#279`](https://github.com/xmldom/xmldom/pull/279)
|
||||
|
||||
## 0.7.0
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/0.6.0...0.7.0)
|
||||
|
||||
Due to [`#271`](https://github.com/xmldom/xmldom/issue/271) this version was published as
|
||||
- unscoped `xmldom` package to github (git tags [`0.7.0`](https://github.com/xmldom/xmldom/tree/0.7.0) and [`0.7.0+unscoped`](https://github.com/xmldom/xmldom/tree/0.7.0%2Bunscoped))
|
||||
- scoped `@xmldom/xmldom` package to npm (git tag `0.7.0+scoped`)
|
||||
For more details look at [`#278`](https://github.com/xmldom/xmldom/pull/278#issuecomment-902172483)
|
||||
|
||||
### Fixes:
|
||||
|
||||
- Security: Misinterpretation of malicious XML input [`CVE-2021-32796`](https://github.com/xmldom/xmldom/security/advisories/GHSA-5fg8-2547-mr8q)
|
||||
- Implement `Document.getElementsByClassName` as specified [`#213`](https://github.com/xmldom/xmldom/pull/213), thank you, [@ChALkeR](https://github.com/ChALkeR)
|
||||
- Inherit namespace prefix from parent when required [`#268`](https://github.com/xmldom/xmldom/pull/268)
|
||||
- Handle whitespace in closing tags [`#267`](https://github.com/xmldom/xmldom/pull/267)
|
||||
- Update `DOMImplementation` according to recent specs [`#210`](https://github.com/xmldom/xmldom/pull/210)
|
||||
BREAKING CHANGE: Only if you "passed features to be marked as available as a constructor arguments" and expected it to "magically work".
|
||||
- No longer serializes any namespaces with an empty URI [`#244`](https://github.com/xmldom/xmldom/pull/244)
|
||||
(related to [`#168`](https://github.com/xmldom/xmldom/pull/168) released in 0.6.0)
|
||||
BREAKING CHANGE: Only if you rely on ["unsetting" a namespace prefix](https://github.com/xmldom/xmldom/pull/168#issuecomment-886984994) by setting it to an empty string
|
||||
- Set `localName` as part of `Document.createElement` [`#229`](https://github.com/xmldom/xmldom/pull/229), thank you, [@rrthomas](https://github.com/rrthomas)
|
||||
|
||||
### CI
|
||||
|
||||
- We are now additionally running tests against node v16
|
||||
- Stryker tests on the master branch now run against node v14
|
||||
|
||||
### Docs
|
||||
|
||||
- Describe relations with and between specs: [`#211`](https://github.com/xmldom/xmldom/pull/211), [`#247`](https://github.com/xmldom/xmldom/pull/247)
|
||||
|
||||
## 0.6.0
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/0.5.0...0.6.0)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Stop serializing empty namespace values like `xmlns:ds=""` [`#168`](https://github.com/xmldom/xmldom/pull/168)
|
||||
BREAKING CHANGE: If your code expected empty namespaces attributes to be serialized.
|
||||
Thank you, [@pdecat](https://github.com/pdecat) and [@FranckDepoortere](https://github.com/FranckDepoortere)
|
||||
- Escape `<` to `<` when serializing attribute values [`#198`](https://github.com/xmldom/xmldom/issues/198) / [`#199`](https://github.com/xmldom/xmldom/pull/199)
|
||||
|
||||
## 0.5.0
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/0.4.0...0.5.0)
|
||||
|
||||
### Fixes
|
||||
- Avoid misinterpretation of malicious XML input - [`GHSA-h6q6-9hqw-rwfv`](https://github.com/xmldom/xmldom/security/advisories/GHSA-h6q6-9hqw-rwfv) (CVE-2021-21366)
|
||||
- Improve error reporting; throw on duplicate attribute\
|
||||
BREAKING CHANGE: It is currently not clear how to consistently deal with duplicate attributes, so it's also safer for our users to fail when detecting them.
|
||||
It's possible to configure the `DOMParser.errorHandler` before parsing, to handle those errors differently.
|
||||
|
||||
To accomplish this and also be able to verify it in tests I needed to
|
||||
- create a new `Error` type `ParseError` and export it
|
||||
- Throw `ParseError` from `errorHandler.fatalError` and prevent those from being caught in `XMLReader`.
|
||||
- export `DOMHandler` constructor as `__DOMHandler`
|
||||
- Preserve quotes in DOCTYPE declaration
|
||||
Since the only purpose of parsing the DOCTYPE is to be able to restore it when serializing, we decided that it would be best to leave the parsed `publicId` and `systemId` as is, including any quotes.
|
||||
BREAKING CHANGE: If somebody relies on the actual unquoted values of those ids, they will need to take care of either single or double quotes and the right escaping.
|
||||
(Without this change this would not have been possible because the SAX parser already dropped the information about the quotes that have been used in the source.)
|
||||
|
||||
https://www.w3.org/TR/2006/REC-xml11-20060816/#dtd
|
||||
https://www.w3.org/TR/2006/REC-xml11-20060816/#IDAX1KS (External Entity Declaration)
|
||||
|
||||
- Fix breaking preprocessors' directives when parsing attributes [`#171`](https://github.com/xmldom/xmldom/pull/171)
|
||||
- fix(dom): Escape `]]>` when serializing CharData [`#181`](https://github.com/xmldom/xmldom/pull/181)
|
||||
- Switch to (only) MIT license (drop problematic LGPL license option) [`#178`](https://github.com/xmldom/xmldom/pull/178)
|
||||
- Export DOMException; remove custom assertions; etc. [`#174`](https://github.com/xmldom/xmldom/pull/174)
|
||||
|
||||
### Docs
|
||||
- Update MDN links in `readme.md` [`#188`](https://github.com/xmldom/xmldom/pull/188)
|
||||
|
||||
## 0.4.0
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/0.3.0...0.4.0)
|
||||
|
||||
### Fixes
|
||||
- **BREAKING** Restore ` ` behavior from v0.1.27 [`#67`](https://github.com/xmldom/xmldom/pull/67)
|
||||
- **BREAKING** Typecheck source param before parsing [`#113`](https://github.com/xmldom/xmldom/pull/113)
|
||||
- Include documents in package files list [`#156`](https://github.com/xmldom/xmldom/pull/156)
|
||||
- Preserve doctype with sysid [`#144`](https://github.com/xmldom/xmldom/pull/144)
|
||||
- Remove ES6 syntax from getElementsByClassName [`#91`](https://github.com/xmldom/xmldom/pull/91)
|
||||
- Revert "Add lowercase of åäö in entityMap" due to duplicate entries [`#84`](https://github.com/xmldom/xmldom/pull/84)
|
||||
- fix: Convert all line separators to LF [`#66`](https://github.com/xmldom/xmldom/pull/66)
|
||||
|
||||
### Docs
|
||||
- Update CHANGELOG.md through version 0.3.0 [`#63`](https://github.com/xmldom/xmldom/pull/63)
|
||||
- Update badges [`#78`](https://github.com/xmldom/xmldom/pull/78)
|
||||
- Add .editorconfig file [`#104`](https://github.com/xmldom/xmldom/pull/104)
|
||||
- Add note about import [`#79`](https://github.com/xmldom/xmldom/pull/79)
|
||||
- Modernize & improve the example in readme.md [`#81`](https://github.com/xmldom/xmldom/pull/81)
|
||||
|
||||
### CI
|
||||
- Add Stryker Mutator [`#70`](https://github.com/xmldom/xmldom/pull/70)
|
||||
- Add Stryker action to update dashboard [`#77`](https://github.com/xmldom/xmldom/pull/77)
|
||||
- Add Node GitHub action workflow [`#64`](https://github.com/xmldom/xmldom/pull/64)
|
||||
- add & enable eslint [`#106`](https://github.com/xmldom/xmldom/pull/106)
|
||||
- Use eslint-plugin-es5 to enforce ES5 syntax [`#107`](https://github.com/xmldom/xmldom/pull/107)
|
||||
- Recover `vows` tests, drop `proof` tests [`#59`](https://github.com/xmldom/xmldom/pull/59)
|
||||
- Add jest tessuite and first tests [`#114`](https://github.com/xmldom/xmldom/pull/114)
|
||||
- Add jest testsuite with `xmltest` cases [`#112`](https://github.com/xmldom/xmldom/pull/112)
|
||||
- Configure Renovate [`#108`](https://github.com/xmldom/xmldom/pull/108)
|
||||
- Test European HTML entities [`#86`](https://github.com/xmldom/xmldom/pull/86)
|
||||
- Updated devDependencies
|
||||
|
||||
### Other
|
||||
- Remove files that are not of any use [`#131`](https://github.com/xmldom/xmldom/pull/131), [`#65`](https://github.com/xmldom/xmldom/pull/65), [`#33`](https://github.com/xmldom/xmldom/pull/33)
|
||||
|
||||
## 0.3.0
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/0.2.1...0.3.0)
|
||||
|
||||
- **BREAKING** Node >=10.x is now required.
|
||||
- **BREAKING** Remove `component.json` (deprecated package manager https://github.com/componentjs/guide)
|
||||
- **BREAKING** Move existing sources into `lib` subdirectory.
|
||||
- **POSSIBLY BREAKING** Introduce `files` entry in `package.json` and remove use of `.npmignore`.
|
||||
- [Add `Document.getElementsByClassName`](https://github.com/xmldom/xmldom/issues/24).
|
||||
- [Add `Node` to the list of exports](https://github.com/xmldom/xmldom/pull/27)
|
||||
- [Add lowercase of åäö in `entityMap`](https://github.com/xmldom/xmldom/pull/23).
|
||||
- Move CHANGELOG to markdown file.
|
||||
- Move LICENSE to markdown file.
|
||||
|
||||
## 0.2.1
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/0.2.0...0.2.1)
|
||||
|
||||
- Correct `homepage`, `repository` and `bugs` URLs in `package.json`.
|
||||
|
||||
## 0.2.0
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/v0.1.27...0.2.0)
|
||||
|
||||
- Includes all **BREAKING** changes introduced in [`xmldom-alpha@v0.1.28`](#0128) by the original authors.
|
||||
- **POSSIBLY BREAKING** [remove the `Object.create` check from the `_extends` method of `dom.js` that added a `__proto__` property](https://github.com/xmldom/xmldom/commit/0be2ae910a8a22c9ec2cac042e04de4c04317d2a#diff-7d1c5d97786fdf9af5446a241d0b6d56L19-L22) ().
|
||||
- **POSSIBLY BREAKING** [remove code that added a `__proto__` property](https://github.com/xmldom/xmldom/commit/366159a76a181ce9a0d83f5dc48205686cfaf9cc)
|
||||
- formatting/corrections in `package.json`
|
||||
|
||||
## 0.1.31
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/v0.1.27...v0.1.31)
|
||||
|
||||
The patch versions (`v0.1.29` - `v0.1.31`) that have been released on the [v0.1.x branch](https://github.com/xmldom/xmldom/tree/0.1.x), to reflect the changed maintainers, **are branched off from [`v0.1.27`](#0127) so they don't include the breaking changes introduced in [`xmldom-alpha@v0.1.28`](#0128)**:
|
||||
|
||||
## Maintainer changes
|
||||
|
||||
After the last commit to the original repository <https://github.com/jindw/xmldom> on the 9th of May 2017, the first commit to <https://github.com/xmldom/xmldom> is from the 19th of December 2019. [The fork has been announced in the original repository on the 2nd of March 2020.](https://github.com/jindw/xmldom/issues/259)
|
||||
|
||||
The versions listed below have been published to one or both of the following packages:
|
||||
- <https://www.npmjs.com/package/xmldom-alpha>
|
||||
- <https://www.npmjs.com/package/xmldom>
|
||||
|
||||
It is currently not planned to continue publishing the `xmldom-alpha` package.
|
||||
|
||||
The new maintainers did not invest time to understand changes that led to the last `xmldom` version [`0.1.27`](#0127) published by the original maintainer, but consider it the basis for their work.
|
||||
A timeline of all the changes that happened from that version until `0.3.0` is available in <https://github.com/xmldom/xmldom/issues/62>. Any related questions should be asked there.
|
||||
|
||||
## 0.1.28
|
||||
|
||||
[Commits](https://github.com/xmldom/xmldom/compare/v0.1.27...xmldom-alpha@v0.1.28)
|
||||
|
||||
Published by @jindw on the 9th of May 2017 as
|
||||
- `xmldom-alpha@0.1.28`
|
||||
|
||||
- **BREAKING** includes [regression regarding ` ` (issue #57)](https://github.com/xmldom/xmldom/issues/57)
|
||||
- [Fix `license` field in `package.json`](https://github.com/jindw/xmldom/pull/178)
|
||||
- [Conditional converting of HTML entities](https://github.com/jindw/xmldom/pull/80)
|
||||
- Fix `dom.js` serialization issue for missing document element ([example that failed on `toString()` before this change](https://github.com/xmldom/xmldom/blob/a58dcf7a265522e80ce520fe3be0cddb1b976f6f/test/parse/unclosedcomment.js#L10-L11))
|
||||
- Add new module `entities.js`
|
||||
|
||||
## 0.1.27
|
||||
|
||||
Published by @jindw on the 28th of Nov 2016 as
|
||||
- `xmldom@0.1.27`
|
||||
- `xmldom-alpha@0.1.27`
|
||||
|
||||
- Various bug fixes.
|
||||
|
||||
## 0.1.26
|
||||
|
||||
Published on the 18th of Nov 2016
|
||||
as `xmldom@0.1.26`
|
||||
|
||||
- Details unknown
|
||||
|
||||
## 0.1.25
|
||||
|
||||
Published on the 18th of Nov 2016 as
|
||||
- `xmldom@0.1.25`
|
||||
|
||||
- Details unknown
|
||||
|
||||
## 0.1.24
|
||||
|
||||
Published on the 27th of November 2016 as
|
||||
- `xmldom@0.1.24`
|
||||
- `xmldom-alpha@0.1.24`
|
||||
|
||||
- Added node filter.
|
||||
|
||||
## 0.1.23
|
||||
|
||||
Published on the 5th of May 2016 as
|
||||
- `xmldom-alpha@0.1.23`
|
||||
|
||||
- Add namespace support for nest node serialize.
|
||||
- Various other bug fixes.
|
||||
|
||||
## 0.1.22
|
||||
|
||||
- Merge XMLNS serialization.
|
||||
- Remove \r from source string.
|
||||
- Print namespaces for child elements.
|
||||
- Switch references to nodeType to use named constants.
|
||||
- Add nodelist toString support.
|
||||
|
||||
## 0.1.21
|
||||
|
||||
- Fix serialize bug.
|
||||
|
||||
## 0.1.20
|
||||
|
||||
- Optimize invalid XML support.
|
||||
- Add toString sorter for attributes output.
|
||||
- Add html self closed node button.
|
||||
- Add `*` NS support for getElementsByTagNameNS.
|
||||
- Convert attribute's value to string in setAttributeNS.
|
||||
- Add support for HTML entities for HTML docs only.
|
||||
- Fix TypeError when Document is created with DocumentType.
|
||||
|
||||
## 0.1.19
|
||||
|
||||
- Fix [infinite loop on unclosed comment (jindw/xmldom#68)](https://github.com/jindw/xmldom/issues/68)
|
||||
- Add error report for unclosed tag.
|
||||
- Various other fixes.
|
||||
|
||||
## 0.1.18
|
||||
|
||||
- Add default `ns` support.
|
||||
- parseFromString now renders entirely plain text documents as textNode.
|
||||
- Enable option to ignore white space on parsing.
|
||||
|
||||
## 0.1.17
|
||||
|
||||
**Details missing for this and potential earlier version**
|
||||
|
||||
## 0.1.16
|
||||
|
||||
- Correctly handle multibyte Unicode greater than two byts. #57. #56.
|
||||
- Initial unit testing and test coverage. #53. #46. #19.
|
||||
- Create Bower `component.json` #52.
|
||||
|
||||
## 0.1.8
|
||||
|
||||
- Add: some test case from node-o3-xml(excludes xpath support)
|
||||
- Fix: remove existed attribute before setting (bug introduced in v0.1.5)
|
||||
- Fix: index direct access for childNodes and any NodeList collection(not w3c standard)
|
||||
- Fix: remove last child bug
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
Copyright 2019 - present Christopher J. Brody and other contributors, as listed in: https://github.com/xmldom/xmldom/graphs/contributors
|
||||
Copyright 2012 - 2017 @jindw <jindw@xidea.org> and other contributors, as listed in: https://github.com/jindw/xmldom/graphs/contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
# Security Policy
|
||||
|
||||
The most up-to-date version of this document can be found at <https://github.com/xmldom/xmldom/security/policy>.
|
||||
|
||||
## Supported Versions
|
||||
|
||||
This repository contains the code for the libraries `xmldom` and `@xmldom/xmldom` on npm.
|
||||
|
||||
As long as we didn't publish v1, we aim to maintain the last two minor versions with security fixes. If it is possible we provide security fixes as path versions.
|
||||
If you think there is a good reason to also patch an earlier version let us know in a github issue or the release discussion once the fix has been provided.
|
||||
The maintainers will consider it and if we agree and have/find the required resources, a patch for that version will be provided.
|
||||
|
||||
Please notice that [we are no longer able to publish the (unscoped) `xmldom` package](https://github.com/xmldom/xmldom/issues/271),
|
||||
and that all existing versions of `xmldom` are affected by at least one security vulnerability and should be considered deprecated.
|
||||
You can still report issues regarding `xmldom` as described below.
|
||||
|
||||
If you need help with migrating from `xmldom` to `@xmldom/xmldom`, file a github issue or PR in the affected repository and mention @karfau.
|
||||
|
||||
## Reporting vulnerabilities
|
||||
|
||||
Please email reports about any security related issues you find to `security@xmldom.org`, which will forward it to the list of maintainers.
|
||||
The maintainers will try to respond within 7 calendar days. (If nobody peplies after 7 days, please us send a reminder!)
|
||||
As part of you communication please make sure to always hit "Reply all", so all maintainers are kept in the loop.
|
||||
|
||||
In addition, please include the following information along with your report:
|
||||
|
||||
- Your name and affiliation (if any).
|
||||
- A description of the technical details of the vulnerabilities. It is very important to let us know how we can reproduce your findings.
|
||||
- An explanation who can exploit this vulnerability, and what they gain when doing so -- write an attack scenario. This will help us evaluate your report quickly, especially if the issue is complex.
|
||||
- Whether this vulnerability public or known to third parties. If it is, please provide details.
|
||||
|
||||
If you believe that an existing (public) issue is security-related, please send an email to `security@xmldom.org`.
|
||||
The email should include the issue URL and a short description of why it should be handled according to this security policy.
|
||||
|
||||
Once an issue is reported, the maintainers use the following disclosure process:
|
||||
|
||||
- When a report is received, we confirm the issue, determine its severity and the affected versions.
|
||||
- If we know of specific third-party services or software based on xmldom that require mitigation before publication, those projects will be notified.
|
||||
- A [github security advisory](https://docs.github.com/en/code-security/security-advisories/about-github-security-advisories) is [created](https://docs.github.com/en/code-security/security-advisories/creating-a-security-advisory) (but not published) which details the problem and steps for mitigation.
|
||||
- If the reporter provides a github account and agrees to it, we (add that github account as a collaborator on the advisuory)[https://docs.github.com/en/code-security/security-advisories/adding-a-collaborator-to-a-security-advisory].
|
||||
- The vulnerability is fixed in a [private fork](https://docs.github.com/en/code-security/security-advisories/collaborating-in-a-temporary-private-fork-to-resolve-a-security-vulnerability) and potential workarounds are identified.
|
||||
- The maintainers audit the existing code to find any potential similar problems.
|
||||
- The release for the current minor version and the [security advisory are published](https://docs.github.com/en/code-security/security-advisories/publishing-a-security-advisory).
|
||||
- The release(s) for previous minor version(s) are published.
|
||||
|
||||
We credit reporters for identifying security issues, if they confirm that they want to.
|
||||
|
||||
## Known vulnerabilities
|
||||
|
||||
See https://github.com/xmldom/xmldom/security/advisories?state=published
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
/// <reference lib="dom" />
|
||||
|
||||
declare module "@xmldom/xmldom" {
|
||||
var DOMParser: DOMParserStatic;
|
||||
var XMLSerializer: XMLSerializerStatic;
|
||||
var DOMImplementation: DOMImplementationStatic;
|
||||
|
||||
interface DOMImplementationStatic {
|
||||
new(): DOMImplementation;
|
||||
}
|
||||
|
||||
interface DOMParserStatic {
|
||||
new (): DOMParser;
|
||||
new (options: Options): DOMParser;
|
||||
}
|
||||
|
||||
interface XMLSerializerStatic {
|
||||
new (): XMLSerializer;
|
||||
}
|
||||
|
||||
interface DOMParser {
|
||||
parseFromString(xmlsource: string, mimeType?: string): Document;
|
||||
}
|
||||
|
||||
/** Options accepted by `XMLSerializer.prototype.serializeToString`. */
|
||||
interface XMLSerializerOptions {
|
||||
/**
|
||||
* When `true`, the serializer throws a DOMException with code `INVALID_STATE_ERR` if:
|
||||
* - A CDATASection node's data contains `"]]>"`.
|
||||
* - A Comment node's data contains `"-->"` (the injection sequence that terminates a
|
||||
* comment). Comments whose data contains `"--"` but not `"-->"` are accepted on this
|
||||
* branch — the 0.8.x parser does not validate bare `"--"` in comment content.
|
||||
* - A ProcessingInstruction's target is not a valid XML `NCName` (a `Name` with no colon)
|
||||
* or is an ASCII case-insensitive match for `"xml"`, or its data contains `"?>"`
|
||||
* (W3C DOM Parsing §3.2.1.7).
|
||||
* - An EntityReference's `nodeName` is not a valid XML `Name`.
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
requireWellFormed?: boolean;
|
||||
}
|
||||
|
||||
interface XMLSerializer {
|
||||
/**
|
||||
* Returns the result of serializing `node` to XML.
|
||||
*
|
||||
* When `options.requireWellFormed` is `true`, the serializer throws for content that would
|
||||
* produce ill-formed XML.
|
||||
*
|
||||
* __This implementation differs from the specification:__
|
||||
* - CDATASection nodes whose data contains `]]>` are serialized by splitting the section
|
||||
* at each `]]>` occurrence (following W3C DOM Level 3 Core `split-cdata-sections`
|
||||
* default behaviour) unless `requireWellFormed` is `true`.
|
||||
* - when `requireWellFormed` is `true`, `DOMException` with code `INVALID_STATE_ERR`
|
||||
* is only thrown to prevent injection vectors, not for all the spec mandated checks.
|
||||
*
|
||||
* @throws {DOMException}
|
||||
* With code `INVALID_STATE_ERR` when `requireWellFormed` is `true` and:
|
||||
* - an Element's qualified name (including any namespace prefix) is not a valid XML QName,
|
||||
* - an attribute's qualified name (including a synthesized `xmlns:` namespace declaration)
|
||||
* is not a valid XML QName,
|
||||
* - a CDATASection node's data contains `"]]>"`,
|
||||
* - a Comment node's data contains `"-->"` (bare `"--"` does not throw on this branch),
|
||||
* - a ProcessingInstruction's target is not a valid XML `NCName` (a `Name` with no colon) or
|
||||
* is an ASCII case-insensitive match for `"xml"`, or its data contains `"?>"`,
|
||||
* - a DocumentType's `name` is not a valid XML `Name` (XML 1.0 production [5]),
|
||||
* - a DocumentType's `publicId` is non-empty and does not match the XML `PubidLiteral`
|
||||
* production,
|
||||
* - a DocumentType's `systemId` is non-empty and does not match the XML `SystemLiteral`
|
||||
* production,
|
||||
* - a DocumentType's `internalSubset` contains `"]>"`, or
|
||||
* - an EntityReference's `nodeName` is not a valid XML `Name` (XML 1.0 production [5]).
|
||||
* Note: xmldom does not enforce `readonly` on DocumentType fields — direct property
|
||||
* writes succeed and are covered by the serializer-level checks above.
|
||||
* @see https://html.spec.whatwg.org/#dom-xmlserializer-serializetostring
|
||||
* @see https://w3c.github.io/DOM-Parsing/#xml-serialization
|
||||
* @see https://github.com/w3c/DOM-Parsing/issues/84
|
||||
*/
|
||||
serializeToString(node: Node, isHtml?: boolean, nodeFilter?: (node: Node) => Node | null | undefined, options?: XMLSerializerOptions): string;
|
||||
}
|
||||
|
||||
interface Options {
|
||||
locator?: any;
|
||||
errorHandler?: ErrorHandlerFunction | ErrorHandlerObject | undefined;
|
||||
}
|
||||
|
||||
interface ErrorHandlerFunction {
|
||||
(level: string, msg: any): any;
|
||||
}
|
||||
|
||||
interface ErrorHandlerObject {
|
||||
warning?: ((msg: any) => any) | undefined;
|
||||
error?: ((msg: any) => any) | undefined;
|
||||
fatalError?: ((msg: any) => any) | undefined;
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
extends:
|
||||
- 'plugin:es5/no-es2015'
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Ponyfill for `Array.prototype.find` which is only available in ES6 runtimes.
|
||||
*
|
||||
* Works with anything that has a `length` property and index access properties, including NodeList.
|
||||
*
|
||||
* @template {unknown} T
|
||||
* @param {Array<T> | ({length:number, [number]: T})} list
|
||||
* @param {function (item: T, index: number, list:Array<T> | ({length:number, [number]: T})):boolean} predicate
|
||||
* @param {Partial<Pick<ArrayConstructor['prototype'], 'find'>>?} ac `Array.prototype` by default,
|
||||
* allows injecting a custom implementation in tests
|
||||
* @returns {T | undefined}
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
|
||||
* @see https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.find
|
||||
*/
|
||||
function find(list, predicate, ac) {
|
||||
if (ac === undefined) {
|
||||
ac = Array.prototype;
|
||||
}
|
||||
if (list && typeof ac.find === 'function') {
|
||||
return ac.find.call(list, predicate);
|
||||
}
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
if (Object.prototype.hasOwnProperty.call(list, i)) {
|
||||
var item = list[i];
|
||||
if (predicate.call(undefined, item, i, list)) {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "Shallow freezes" an object to render it immutable.
|
||||
* Uses `Object.freeze` if available,
|
||||
* otherwise the immutability is only in the type.
|
||||
*
|
||||
* Is used to create "enum like" objects.
|
||||
*
|
||||
* @template T
|
||||
* @param {T} object the object to freeze
|
||||
* @param {Pick<ObjectConstructor, 'freeze'> = Object} oc `Object` by default,
|
||||
* allows to inject custom object constructor for tests
|
||||
* @returns {Readonly<T>}
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
|
||||
*/
|
||||
function freeze(object, oc) {
|
||||
if (oc === undefined) {
|
||||
oc = Object
|
||||
}
|
||||
return oc && typeof oc.freeze === 'function' ? oc.freeze(object) : object
|
||||
}
|
||||
|
||||
/**
|
||||
* Since we can not rely on `Object.assign` we provide a simplified version
|
||||
* that is sufficient for our needs.
|
||||
*
|
||||
* @param {Object} target
|
||||
* @param {Object | null | undefined} source
|
||||
*
|
||||
* @returns {Object} target
|
||||
* @throws TypeError if target is not an object
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
|
||||
* @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign
|
||||
*/
|
||||
function assign(target, source) {
|
||||
if (target === null || typeof target !== 'object') {
|
||||
throw new TypeError('target is not an object')
|
||||
}
|
||||
for (var key in source) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
target[key] = source[key]
|
||||
}
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
/**
|
||||
* All mime types that are allowed as input to `DOMParser.parseFromString`
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 MDN
|
||||
* @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype WHATWG HTML Spec
|
||||
* @see DOMParser.prototype.parseFromString
|
||||
*/
|
||||
var MIME_TYPE = freeze({
|
||||
/**
|
||||
* `text/html`, the only mime type that triggers treating an XML document as HTML.
|
||||
*
|
||||
* @see DOMParser.SupportedType.isHTML
|
||||
* @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
|
||||
* @see https://en.wikipedia.org/wiki/HTML Wikipedia
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
|
||||
* @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring WHATWG HTML Spec
|
||||
*/
|
||||
HTML: 'text/html',
|
||||
|
||||
/**
|
||||
* Helper method to check a mime type if it indicates an HTML document
|
||||
*
|
||||
* @param {string} [value]
|
||||
* @returns {boolean}
|
||||
*
|
||||
* @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
|
||||
* @see https://en.wikipedia.org/wiki/HTML Wikipedia
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
|
||||
* @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */
|
||||
isHTML: function (value) {
|
||||
return value === MIME_TYPE.HTML
|
||||
},
|
||||
|
||||
/**
|
||||
* `application/xml`, the standard mime type for XML documents.
|
||||
*
|
||||
* @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType registration
|
||||
* @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303
|
||||
* @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
|
||||
*/
|
||||
XML_APPLICATION: 'application/xml',
|
||||
|
||||
/**
|
||||
* `text/html`, an alias for `application/xml`.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303
|
||||
* @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration
|
||||
* @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
|
||||
*/
|
||||
XML_TEXT: 'text/xml',
|
||||
|
||||
/**
|
||||
* `application/xhtml+xml`, indicates an XML document that has the default HTML namespace,
|
||||
* but is parsed as an XML document.
|
||||
*
|
||||
* @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType registration
|
||||
* @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec
|
||||
* @see https://en.wikipedia.org/wiki/XHTML Wikipedia
|
||||
*/
|
||||
XML_XHTML_APPLICATION: 'application/xhtml+xml',
|
||||
|
||||
/**
|
||||
* `image/svg+xml`,
|
||||
*
|
||||
* @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration
|
||||
* @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1
|
||||
* @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia
|
||||
*/
|
||||
XML_SVG_IMAGE: 'image/svg+xml',
|
||||
})
|
||||
|
||||
/**
|
||||
* Namespaces that are used in this code base.
|
||||
*
|
||||
* @see http://www.w3.org/TR/REC-xml-names
|
||||
*/
|
||||
var NAMESPACE = freeze({
|
||||
/**
|
||||
* The XHTML namespace.
|
||||
*
|
||||
* @see http://www.w3.org/1999/xhtml
|
||||
*/
|
||||
HTML: 'http://www.w3.org/1999/xhtml',
|
||||
|
||||
/**
|
||||
* Checks if `uri` equals `NAMESPACE.HTML`.
|
||||
*
|
||||
* @param {string} [uri]
|
||||
*
|
||||
* @see NAMESPACE.HTML
|
||||
*/
|
||||
isHTML: function (uri) {
|
||||
return uri === NAMESPACE.HTML
|
||||
},
|
||||
|
||||
/**
|
||||
* The SVG namespace.
|
||||
*
|
||||
* @see http://www.w3.org/2000/svg
|
||||
*/
|
||||
SVG: 'http://www.w3.org/2000/svg',
|
||||
|
||||
/**
|
||||
* The `xml:` namespace.
|
||||
*
|
||||
* @see http://www.w3.org/XML/1998/namespace
|
||||
*/
|
||||
XML: 'http://www.w3.org/XML/1998/namespace',
|
||||
|
||||
/**
|
||||
* The `xmlns:` namespace
|
||||
*
|
||||
* @see https://www.w3.org/2000/xmlns/
|
||||
*/
|
||||
XMLNS: 'http://www.w3.org/2000/xmlns/',
|
||||
})
|
||||
|
||||
//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
|
||||
//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
|
||||
//[5] Name ::= NameStartChar (NameChar)*
|
||||
var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
|
||||
var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
|
||||
var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
|
||||
//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
|
||||
|
||||
exports.assign = assign;
|
||||
exports.find = find;
|
||||
exports.freeze = freeze;
|
||||
exports.MIME_TYPE = MIME_TYPE;
|
||||
exports.NAMESPACE = NAMESPACE;
|
||||
exports.nameStartChar = nameStartChar;
|
||||
exports.nameChar = nameChar;
|
||||
exports.tagNamePattern = tagNamePattern;
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
var conventions = require("./conventions");
|
||||
var dom = require('./dom')
|
||||
var entities = require('./entities');
|
||||
var sax = require('./sax');
|
||||
|
||||
var DOMImplementation = dom.DOMImplementation;
|
||||
|
||||
var NAMESPACE = conventions.NAMESPACE;
|
||||
|
||||
var ParseError = sax.ParseError;
|
||||
var XMLReader = sax.XMLReader;
|
||||
|
||||
/**
|
||||
* Normalizes line ending according to https://www.w3.org/TR/xml11/#sec-line-ends:
|
||||
*
|
||||
* > XML parsed entities are often stored in computer files which,
|
||||
* > for editing convenience, are organized into lines.
|
||||
* > These lines are typically separated by some combination
|
||||
* > of the characters CARRIAGE RETURN (#xD) and LINE FEED (#xA).
|
||||
* >
|
||||
* > To simplify the tasks of applications, the XML processor must behave
|
||||
* > as if it normalized all line breaks in external parsed entities (including the document entity)
|
||||
* > on input, before parsing, by translating all of the following to a single #xA character:
|
||||
* >
|
||||
* > 1. the two-character sequence #xD #xA
|
||||
* > 2. the two-character sequence #xD #x85
|
||||
* > 3. the single character #x85
|
||||
* > 4. the single character #x2028
|
||||
* > 5. any #xD character that is not immediately followed by #xA or #x85.
|
||||
*
|
||||
* @param {string} input
|
||||
* @returns {string}
|
||||
*/
|
||||
function normalizeLineEndings(input) {
|
||||
return input
|
||||
.replace(/\r[\n\u0085]/g, '\n')
|
||||
.replace(/[\r\u0085\u2028]/g, '\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef Locator
|
||||
* @property {number} [columnNumber]
|
||||
* @property {number} [lineNumber]
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef DOMParserOptions
|
||||
* @property {DOMHandler} [domBuilder]
|
||||
* @property {Function} [errorHandler]
|
||||
* @property {(string) => string} [normalizeLineEndings] used to replace line endings before parsing
|
||||
* defaults to `normalizeLineEndings`
|
||||
* @property {Locator} [locator]
|
||||
* @property {Record<string, string>} [xmlns]
|
||||
*
|
||||
* @see normalizeLineEndings
|
||||
*/
|
||||
|
||||
/**
|
||||
* The DOMParser interface provides the ability to parse XML or HTML source code
|
||||
* from a string into a DOM `Document`.
|
||||
*
|
||||
* _xmldom is different from the spec in that it allows an `options` parameter,
|
||||
* to override the default behavior._
|
||||
*
|
||||
* @param {DOMParserOptions} [options]
|
||||
* @constructor
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
|
||||
* @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization
|
||||
*/
|
||||
function DOMParser(options){
|
||||
this.options = options ||{locator:{}};
|
||||
}
|
||||
|
||||
DOMParser.prototype.parseFromString = function(source,mimeType){
|
||||
var options = this.options;
|
||||
var sax = new XMLReader();
|
||||
var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
|
||||
var errorHandler = options.errorHandler;
|
||||
var locator = options.locator;
|
||||
var defaultNSMap = options.xmlns||{};
|
||||
var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1;
|
||||
var entityMap = isHTML ? entities.HTML_ENTITIES : entities.XML_ENTITIES;
|
||||
if(locator){
|
||||
domBuilder.setDocumentLocator(locator)
|
||||
}
|
||||
|
||||
sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
|
||||
sax.domBuilder = options.domBuilder || domBuilder;
|
||||
if(isHTML){
|
||||
defaultNSMap[''] = NAMESPACE.HTML;
|
||||
}
|
||||
defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML;
|
||||
var normalize = options.normalizeLineEndings || normalizeLineEndings;
|
||||
if (source && typeof source === 'string') {
|
||||
sax.parse(
|
||||
normalize(source),
|
||||
defaultNSMap,
|
||||
entityMap
|
||||
)
|
||||
} else {
|
||||
sax.errorHandler.error('invalid doc source')
|
||||
}
|
||||
return domBuilder.doc;
|
||||
}
|
||||
function buildErrorHandler(errorImpl,domBuilder,locator){
|
||||
if(!errorImpl){
|
||||
if(domBuilder instanceof DOMHandler){
|
||||
return domBuilder;
|
||||
}
|
||||
errorImpl = domBuilder ;
|
||||
}
|
||||
var errorHandler = {}
|
||||
var isCallback = errorImpl instanceof Function;
|
||||
locator = locator||{}
|
||||
function build(key){
|
||||
var fn = errorImpl[key];
|
||||
if(!fn && isCallback){
|
||||
fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
|
||||
}
|
||||
errorHandler[key] = fn && function(msg){
|
||||
fn('[xmldom '+key+']\t'+msg+_locator(locator));
|
||||
}||function(){};
|
||||
}
|
||||
build('warning');
|
||||
build('error');
|
||||
build('fatalError');
|
||||
return errorHandler;
|
||||
}
|
||||
|
||||
//console.log('#\n\n\n\n\n\n\n####')
|
||||
/**
|
||||
* +ContentHandler+ErrorHandler
|
||||
* +LexicalHandler+EntityResolver2
|
||||
* -DeclHandler-DTDHandler
|
||||
*
|
||||
* DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
|
||||
* DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
|
||||
* @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
|
||||
*/
|
||||
function DOMHandler() {
|
||||
this.cdata = false;
|
||||
}
|
||||
function position(locator,node){
|
||||
node.lineNumber = locator.lineNumber;
|
||||
node.columnNumber = locator.columnNumber;
|
||||
}
|
||||
/**
|
||||
* @see org.xml.sax.ContentHandler#startDocument
|
||||
* @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
|
||||
*/
|
||||
DOMHandler.prototype = {
|
||||
startDocument : function() {
|
||||
this.doc = new DOMImplementation().createDocument(null, null, null);
|
||||
if (this.locator) {
|
||||
this.doc.documentURI = this.locator.systemId;
|
||||
}
|
||||
},
|
||||
startElement:function(namespaceURI, localName, qName, attrs) {
|
||||
var doc = this.doc;
|
||||
var el = doc.createElementNS(namespaceURI, qName||localName);
|
||||
var len = attrs.length;
|
||||
appendElement(this, el);
|
||||
this.currentElement = el;
|
||||
|
||||
this.locator && position(this.locator,el)
|
||||
for (var i = 0 ; i < len; i++) {
|
||||
var namespaceURI = attrs.getURI(i);
|
||||
var value = attrs.getValue(i);
|
||||
var qName = attrs.getQName(i);
|
||||
var attr = doc.createAttributeNS(namespaceURI, qName);
|
||||
this.locator &&position(attrs.getLocator(i),attr);
|
||||
attr.value = attr.nodeValue = value;
|
||||
el.setAttributeNode(attr)
|
||||
}
|
||||
},
|
||||
endElement:function(namespaceURI, localName, qName) {
|
||||
var current = this.currentElement
|
||||
var tagName = current.tagName;
|
||||
this.currentElement = current.parentNode;
|
||||
},
|
||||
startPrefixMapping:function(prefix, uri) {
|
||||
},
|
||||
endPrefixMapping:function(prefix) {
|
||||
},
|
||||
processingInstruction:function(target, data) {
|
||||
var ins = this.doc.createProcessingInstruction(target, data);
|
||||
this.locator && position(this.locator,ins)
|
||||
appendElement(this, ins);
|
||||
},
|
||||
ignorableWhitespace:function(ch, start, length) {
|
||||
},
|
||||
characters:function(chars, start, length) {
|
||||
chars = _toString.apply(this,arguments)
|
||||
//console.log(chars)
|
||||
if(chars){
|
||||
if (this.cdata) {
|
||||
var charNode = this.doc.createCDATASection(chars);
|
||||
} else {
|
||||
var charNode = this.doc.createTextNode(chars);
|
||||
}
|
||||
if(this.currentElement){
|
||||
this.currentElement.appendChild(charNode);
|
||||
}else if(/^\s*$/.test(chars)){
|
||||
this.doc.appendChild(charNode);
|
||||
//process xml
|
||||
}
|
||||
this.locator && position(this.locator,charNode)
|
||||
}
|
||||
},
|
||||
skippedEntity:function(name) {
|
||||
},
|
||||
endDocument:function() {
|
||||
this.doc.normalize();
|
||||
},
|
||||
setDocumentLocator:function (locator) {
|
||||
if(this.locator = locator){// && !('lineNumber' in locator)){
|
||||
locator.lineNumber = 0;
|
||||
}
|
||||
},
|
||||
//LexicalHandler
|
||||
comment:function(chars, start, length) {
|
||||
chars = _toString.apply(this,arguments)
|
||||
var comm = this.doc.createComment(chars);
|
||||
this.locator && position(this.locator,comm)
|
||||
appendElement(this, comm);
|
||||
},
|
||||
|
||||
startCDATA:function() {
|
||||
//used in characters() methods
|
||||
this.cdata = true;
|
||||
},
|
||||
endCDATA:function() {
|
||||
this.cdata = false;
|
||||
},
|
||||
|
||||
startDTD:function(name, publicId, systemId) {
|
||||
var impl = this.doc.implementation;
|
||||
if (impl && impl.createDocumentType) {
|
||||
var dt = impl.createDocumentType(name, publicId, systemId);
|
||||
this.locator && position(this.locator,dt)
|
||||
appendElement(this, dt);
|
||||
this.doc.doctype = dt;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @see org.xml.sax.ErrorHandler
|
||||
* @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
|
||||
*/
|
||||
warning:function(error) {
|
||||
console.warn('[xmldom warning]\t'+error,_locator(this.locator));
|
||||
},
|
||||
error:function(error) {
|
||||
console.error('[xmldom error]\t'+error,_locator(this.locator));
|
||||
},
|
||||
fatalError:function(error) {
|
||||
throw new ParseError(error, this.locator);
|
||||
}
|
||||
}
|
||||
function _locator(l){
|
||||
if(l){
|
||||
return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
|
||||
}
|
||||
}
|
||||
function _toString(chars,start,length){
|
||||
if(typeof chars == 'string'){
|
||||
return chars.substr(start,length)
|
||||
}else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
|
||||
if(chars.length >= start+length || start){
|
||||
return new java.lang.String(chars,start,length)+'';
|
||||
}
|
||||
return chars;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
|
||||
* used method of org.xml.sax.ext.LexicalHandler:
|
||||
* #comment(chars, start, length)
|
||||
* #startCDATA()
|
||||
* #endCDATA()
|
||||
* #startDTD(name, publicId, systemId)
|
||||
*
|
||||
*
|
||||
* IGNORED method of org.xml.sax.ext.LexicalHandler:
|
||||
* #endDTD()
|
||||
* #startEntity(name)
|
||||
* #endEntity(name)
|
||||
*
|
||||
*
|
||||
* @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
|
||||
* IGNORED method of org.xml.sax.ext.DeclHandler
|
||||
* #attributeDecl(eName, aName, type, mode, value)
|
||||
* #elementDecl(name, model)
|
||||
* #externalEntityDecl(name, publicId, systemId)
|
||||
* #internalEntityDecl(name, value)
|
||||
* @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
|
||||
* IGNORED method of org.xml.sax.EntityResolver2
|
||||
* #resolveEntity(String name,String publicId,String baseURI,String systemId)
|
||||
* #resolveEntity(publicId, systemId)
|
||||
* #getExternalSubset(name, baseURI)
|
||||
* @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
|
||||
* IGNORED method of org.xml.sax.DTDHandler
|
||||
* #notationDecl(name, publicId, systemId) {};
|
||||
* #unparsedEntityDecl(name, publicId, systemId, notationName) {};
|
||||
*/
|
||||
"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
|
||||
DOMHandler.prototype[key] = function(){return null}
|
||||
})
|
||||
|
||||
/* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
|
||||
function appendElement (hander,node) {
|
||||
if (!hander.currentElement) {
|
||||
hander.doc.appendChild(node);
|
||||
} else {
|
||||
hander.currentElement.appendChild(node);
|
||||
}
|
||||
}//appendChild and setAttributeNS are preformance key
|
||||
|
||||
exports.__DOMHandler = DOMHandler;
|
||||
exports.normalizeLineEndings = normalizeLineEndings;
|
||||
exports.DOMParser = DOMParser;
|
||||
+2266
File diff suppressed because it is too large
Load Diff
+2166
File diff suppressed because it is too large
Load Diff
+4
@@ -0,0 +1,4 @@
|
||||
var dom = require('./dom')
|
||||
exports.DOMImplementation = dom.DOMImplementation
|
||||
exports.XMLSerializer = dom.XMLSerializer
|
||||
exports.DOMParser = require('./dom-parser').DOMParser
|
||||
+683
@@ -0,0 +1,683 @@
|
||||
var NAMESPACE = require("./conventions").NAMESPACE;
|
||||
var tagNamePattern = require("./conventions").tagNamePattern;
|
||||
|
||||
//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
|
||||
|
||||
//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
|
||||
//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
|
||||
var S_TAG = 0;//tag name offerring
|
||||
var S_ATTR = 1;//attr name offerring
|
||||
var S_ATTR_SPACE=2;//attr name end and space offer
|
||||
var S_EQ = 3;//=space?
|
||||
var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
|
||||
var S_ATTR_END = 5;//attr value end and no space(quot end)
|
||||
var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
|
||||
var S_TAG_CLOSE = 7;//closed el<el />
|
||||
|
||||
/**
|
||||
* Creates an error that will not be caught by XMLReader aka the SAX parser.
|
||||
*
|
||||
* @param {string} message
|
||||
* @param {any?} locator Optional, can provide details about the location in the source
|
||||
* @constructor
|
||||
*/
|
||||
function ParseError(message, locator) {
|
||||
this.message = message
|
||||
this.locator = locator
|
||||
if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
|
||||
}
|
||||
ParseError.prototype = new Error();
|
||||
ParseError.prototype.name = ParseError.name
|
||||
|
||||
function XMLReader(){
|
||||
|
||||
}
|
||||
|
||||
XMLReader.prototype = {
|
||||
parse:function(source,defaultNSMap,entityMap){
|
||||
var domBuilder = this.domBuilder;
|
||||
domBuilder.startDocument();
|
||||
_copy(defaultNSMap ,defaultNSMap = {})
|
||||
parse(source,defaultNSMap,entityMap,
|
||||
domBuilder,this.errorHandler);
|
||||
domBuilder.endDocument();
|
||||
}
|
||||
}
|
||||
function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
|
||||
function fixedFromCharCode(code) {
|
||||
// String.prototype.fromCharCode does not supports
|
||||
// > 2 bytes unicode chars directly
|
||||
if (code > 0xffff) {
|
||||
code -= 0x10000;
|
||||
var surrogate1 = 0xd800 + (code >> 10)
|
||||
, surrogate2 = 0xdc00 + (code & 0x3ff);
|
||||
|
||||
return String.fromCharCode(surrogate1, surrogate2);
|
||||
} else {
|
||||
return String.fromCharCode(code);
|
||||
}
|
||||
}
|
||||
function entityReplacer(a){
|
||||
var k = a.slice(1,-1);
|
||||
if (Object.hasOwnProperty.call(entityMap, k)) {
|
||||
return entityMap[k];
|
||||
}else if(k.charAt(0) === '#'){
|
||||
return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
|
||||
}else{
|
||||
errorHandler.error('entity not found:'+a);
|
||||
return a;
|
||||
}
|
||||
}
|
||||
function appendText(end){//has some bugs
|
||||
if(end>start){
|
||||
var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
|
||||
locator&&position(start);
|
||||
domBuilder.characters(xt,0,end-start);
|
||||
start = end
|
||||
}
|
||||
}
|
||||
function position(p,m){
|
||||
while(p>=lineEnd && (m = linePattern.exec(source))){
|
||||
lineStart = m.index;
|
||||
lineEnd = lineStart + m[0].length;
|
||||
locator.lineNumber++;
|
||||
//console.log('line++:',locator,startPos,endPos)
|
||||
}
|
||||
locator.columnNumber = p-lineStart+1;
|
||||
}
|
||||
var lineStart = 0;
|
||||
var lineEnd = 0;
|
||||
var linePattern = /.*(?:\r\n?|\n)|.*$/g
|
||||
var locator = domBuilder.locator;
|
||||
|
||||
var parseStack = [{currentNSMap:defaultNSMapCopy}]
|
||||
var closeMap = {};
|
||||
var start = 0;
|
||||
while(true){
|
||||
try{
|
||||
var tagStart = source.indexOf('<',start);
|
||||
if(tagStart<0){
|
||||
if(!source.substr(start).match(/^\s*$/)){
|
||||
var doc = domBuilder.doc;
|
||||
var text = doc.createTextNode(source.substr(start));
|
||||
doc.appendChild(text);
|
||||
domBuilder.currentElement = text;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(tagStart>start){
|
||||
appendText(tagStart);
|
||||
}
|
||||
switch(source.charAt(tagStart+1)){
|
||||
case '/':
|
||||
var end = source.indexOf('>',tagStart+3);
|
||||
// Anchored trailing-whitespace trim. The former `/[ \t\n\r]+$/g` backtracked
|
||||
// quadratically on a name shaped `whitespace-run + non-whitespace char`
|
||||
// (an end tag `</ … x>`): from every start position it extended `[ws]+`
|
||||
// to the end and then failed the `$` anchor. This anchored form matches the
|
||||
// whole string once and captures everything up to the last non-whitespace
|
||||
// character, so it trims in linear time with byte-identical output.
|
||||
var tagName = source.substring(tagStart + 2, end).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/, '$1');
|
||||
var config = parseStack.pop();
|
||||
if(end<0){
|
||||
|
||||
tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
|
||||
errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
|
||||
end = tagStart+1+tagName.length;
|
||||
}else if(tagName.match(/\s</)){
|
||||
tagName = tagName.replace(/[\s<].*/,'');
|
||||
errorHandler.error("end tag name: "+tagName+' maybe not complete');
|
||||
end = tagStart+1+tagName.length;
|
||||
}else if(/[ \t\n\r]/.test(tagName) && tagNamePattern.test(tagName.split(/[ \t\n\r]/)[0])){
|
||||
// The XML `ETag` production is `'</' Name S? '>'`: only optional whitespace may follow
|
||||
// the `Name`. A valid `Name` followed by whitespace and non-whitespace residue (e.g.
|
||||
// `</a\nbogus>` or `</a bogus>`) is not well-formed, but historically it was silently
|
||||
// accepted (the malformed end tag ignored, the residue dropped, the element left on the
|
||||
// stack). Report it as a recoverable `error` (which a custom errorHandler may escalate to
|
||||
// fatal) while keeping the existing recovery so the parsed DOM stays byte-identical.
|
||||
errorHandler.error('end tag name is followed by whitespace and trailing content: "'+tagName+'"');
|
||||
}
|
||||
var localNSMap = config.localNSMap;
|
||||
var endMatch = config.tagName == tagName;
|
||||
var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
|
||||
if(endIgnoreCaseMach){
|
||||
domBuilder.endElement(config.uri,config.localName,tagName);
|
||||
if(localNSMap){
|
||||
for (var prefix in localNSMap) {
|
||||
if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) {
|
||||
domBuilder.endPrefixMapping(prefix);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!endMatch){
|
||||
errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName ); // No known test case
|
||||
}
|
||||
}else{
|
||||
parseStack.push(config)
|
||||
}
|
||||
|
||||
end++;
|
||||
break;
|
||||
// end elment
|
||||
case '?':// <?...?>
|
||||
locator&&position(tagStart);
|
||||
end = parseInstruction(source,tagStart,domBuilder);
|
||||
break;
|
||||
case '!':// <!doctype,<![CDATA,<!--
|
||||
locator&&position(tagStart);
|
||||
end = parseDCC(source,tagStart,domBuilder,errorHandler);
|
||||
break;
|
||||
default:
|
||||
locator&&position(tagStart);
|
||||
var el = new ElementAttributes();
|
||||
var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
|
||||
//elStartEnd
|
||||
var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
|
||||
var len = el.length;
|
||||
|
||||
|
||||
if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
|
||||
el.closed = true;
|
||||
if(!entityMap.nbsp){
|
||||
errorHandler.warning('unclosed xml attribute');
|
||||
}
|
||||
}
|
||||
if(locator && len){
|
||||
var locator2 = copyLocator(locator,{});
|
||||
//try{//attribute position fixed
|
||||
for(var i = 0;i<len;i++){
|
||||
var a = el[i];
|
||||
position(a.offset);
|
||||
a.locator = copyLocator(locator,{});
|
||||
}
|
||||
domBuilder.locator = locator2
|
||||
if(appendElement(el,domBuilder,currentNSMap)){
|
||||
parseStack.push(el)
|
||||
}
|
||||
domBuilder.locator = locator;
|
||||
}else{
|
||||
if(appendElement(el,domBuilder,currentNSMap)){
|
||||
parseStack.push(el)
|
||||
}
|
||||
}
|
||||
|
||||
if (NAMESPACE.isHTML(el.uri) && !el.closed) {
|
||||
end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
|
||||
} else {
|
||||
end++;
|
||||
}
|
||||
}
|
||||
}catch(e){
|
||||
if (e instanceof ParseError) {
|
||||
throw e;
|
||||
}
|
||||
errorHandler.error('element parse error: '+e)
|
||||
end = -1;
|
||||
}
|
||||
if(end>start){
|
||||
start = end;
|
||||
}else{
|
||||
//TODO: 这里有可能sax回退,有位置错误风险
|
||||
appendText(Math.max(tagStart,start)+1);
|
||||
}
|
||||
}
|
||||
}
|
||||
function copyLocator(f,t){
|
||||
t.lineNumber = f.lineNumber;
|
||||
t.columnNumber = f.columnNumber;
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
|
||||
* @return end of the elementStartPart(end of elementEndPart for selfClosed el)
|
||||
*/
|
||||
function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
|
||||
|
||||
/**
|
||||
* @param {string} qname
|
||||
* @param {string} value
|
||||
* @param {number} startIndex
|
||||
*/
|
||||
function addAttribute(qname, value, startIndex) {
|
||||
if (el.attributeNames.hasOwnProperty(qname)) {
|
||||
errorHandler.fatalError('Attribute ' + qname + ' redefined')
|
||||
}
|
||||
el.addValue(
|
||||
qname,
|
||||
// @see https://www.w3.org/TR/xml/#AVNormalize
|
||||
// since the xmldom sax parser does not "interpret" DTD the following is not implemented:
|
||||
// - recursive replacement of (DTD) entity references
|
||||
// - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA
|
||||
value.replace(/[\t\n\r]/g, ' ').replace(/&#?\w+;/g, entityReplacer),
|
||||
startIndex
|
||||
)
|
||||
}
|
||||
var attrName;
|
||||
var value;
|
||||
var p = ++start;
|
||||
var s = S_TAG;//status
|
||||
while(true){
|
||||
var c = source.charAt(p);
|
||||
if (s === S_TAG && c === '<') {
|
||||
// A `<` can never occur inside a tag name. Without this guard the scan runs
|
||||
// on to the next `>` (or EOF) before the tag name is rejected, so a document
|
||||
// with many `<` inside a malformed tag makes each one-character recovery step
|
||||
// re-scan to the distant `>` — O(n^2). Stopping at the `<` keeps each recovery
|
||||
// step bounded. The candidate scanned so far is reported raw, consistent with
|
||||
// the sibling invalid-tag-name throw below.
|
||||
throw new Error('unexpected < in tag name: ' + source.slice(start, p));
|
||||
}
|
||||
switch(c){
|
||||
case '=':
|
||||
if(s === S_ATTR){//attrName
|
||||
attrName = source.slice(start,p);
|
||||
s = S_EQ;
|
||||
}else if(s === S_ATTR_SPACE){
|
||||
s = S_EQ;
|
||||
}else{
|
||||
//fatalError: equal must after attrName or space after attrName
|
||||
throw new Error('attribute equal must after attrName'); // No known test case
|
||||
}
|
||||
break;
|
||||
case '\'':
|
||||
case '"':
|
||||
if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
|
||||
){//equal
|
||||
if(s === S_ATTR){
|
||||
errorHandler.warning('attribute value must after "="')
|
||||
attrName = source.slice(start,p)
|
||||
}
|
||||
start = p+1;
|
||||
p = source.indexOf(c,start)
|
||||
if(p>0){
|
||||
value = source.slice(start, p);
|
||||
addAttribute(attrName, value, start-1);
|
||||
s = S_ATTR_END;
|
||||
}else{
|
||||
//fatalError: no end quot match
|
||||
throw new Error('attribute value no end \''+c+'\' match');
|
||||
}
|
||||
}else if(s == S_ATTR_NOQUOT_VALUE){
|
||||
value = source.slice(start, p);
|
||||
addAttribute(attrName, value, start);
|
||||
errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
|
||||
start = p+1;
|
||||
s = S_ATTR_END
|
||||
}else{
|
||||
//fatalError: no equal before
|
||||
throw new Error('attribute value must after "="'); // No known test case
|
||||
}
|
||||
break;
|
||||
case '/':
|
||||
switch(s){
|
||||
case S_TAG:
|
||||
el.setTagName(source.slice(start,p));
|
||||
case S_ATTR_END:
|
||||
case S_TAG_SPACE:
|
||||
case S_TAG_CLOSE:
|
||||
s =S_TAG_CLOSE;
|
||||
el.closed = true;
|
||||
case S_ATTR_NOQUOT_VALUE:
|
||||
case S_ATTR:
|
||||
break;
|
||||
case S_ATTR_SPACE:
|
||||
el.closed = true;
|
||||
break;
|
||||
//case S_EQ:
|
||||
default:
|
||||
throw new Error("attribute invalid close char('/')") // No known test case
|
||||
}
|
||||
break;
|
||||
case ''://end document
|
||||
errorHandler.error('unexpected end of input');
|
||||
if(s == S_TAG){
|
||||
el.setTagName(source.slice(start,p));
|
||||
}
|
||||
return p;
|
||||
case '>':
|
||||
switch(s){
|
||||
case S_TAG:
|
||||
el.setTagName(source.slice(start,p));
|
||||
case S_ATTR_END:
|
||||
case S_TAG_SPACE:
|
||||
case S_TAG_CLOSE:
|
||||
break;//normal
|
||||
case S_ATTR_NOQUOT_VALUE://Compatible state
|
||||
case S_ATTR:
|
||||
value = source.slice(start,p);
|
||||
if(value.slice(-1) === '/'){
|
||||
el.closed = true;
|
||||
value = value.slice(0,-1)
|
||||
}
|
||||
case S_ATTR_SPACE:
|
||||
if(s === S_ATTR_SPACE){
|
||||
value = attrName;
|
||||
}
|
||||
if(s == S_ATTR_NOQUOT_VALUE){
|
||||
errorHandler.warning('attribute "'+value+'" missed quot(")!');
|
||||
addAttribute(attrName, value, start)
|
||||
}else{
|
||||
if(!NAMESPACE.isHTML(currentNSMap['']) || !value.match(/^(?:disabled|checked|selected)$/i)){
|
||||
errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
|
||||
}
|
||||
addAttribute(value, value, start)
|
||||
}
|
||||
break;
|
||||
case S_EQ:
|
||||
throw new Error('attribute value missed!!');
|
||||
}
|
||||
// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
|
||||
return p;
|
||||
/*xml space '\x20' | #x9 | #xD | #xA; */
|
||||
case '\u0080':
|
||||
c = ' ';
|
||||
default:
|
||||
if(c<= ' '){//space
|
||||
switch(s){
|
||||
case S_TAG:
|
||||
el.setTagName(source.slice(start,p));//tagName
|
||||
s = S_TAG_SPACE;
|
||||
break;
|
||||
case S_ATTR:
|
||||
attrName = source.slice(start,p)
|
||||
s = S_ATTR_SPACE;
|
||||
break;
|
||||
case S_ATTR_NOQUOT_VALUE:
|
||||
var value = source.slice(start, p);
|
||||
errorHandler.warning('attribute "'+value+'" missed quot(")!!');
|
||||
addAttribute(attrName, value, start)
|
||||
case S_ATTR_END:
|
||||
s = S_TAG_SPACE;
|
||||
break;
|
||||
//case S_TAG_SPACE:
|
||||
//case S_EQ:
|
||||
//case S_ATTR_SPACE:
|
||||
// void();break;
|
||||
//case S_TAG_CLOSE:
|
||||
//ignore warning
|
||||
}
|
||||
}else{//not space
|
||||
//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
|
||||
//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
|
||||
switch(s){
|
||||
//case S_TAG:void();break;
|
||||
//case S_ATTR:void();break;
|
||||
//case S_ATTR_NOQUOT_VALUE:void();break;
|
||||
case S_ATTR_SPACE:
|
||||
var tagName = el.tagName;
|
||||
if (!NAMESPACE.isHTML(currentNSMap['']) || !attrName.match(/^(?:disabled|checked|selected)$/i)) {
|
||||
errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
|
||||
}
|
||||
addAttribute(attrName, attrName, start);
|
||||
start = p;
|
||||
s = S_ATTR;
|
||||
break;
|
||||
case S_ATTR_END:
|
||||
errorHandler.warning('attribute space is required"'+attrName+'"!!')
|
||||
case S_TAG_SPACE:
|
||||
s = S_ATTR;
|
||||
start = p;
|
||||
break;
|
||||
case S_EQ:
|
||||
s = S_ATTR_NOQUOT_VALUE;
|
||||
start = p;
|
||||
break;
|
||||
case S_TAG_CLOSE:
|
||||
throw new Error("elements closed character '/' and '>' must be connected to");
|
||||
}
|
||||
}
|
||||
}//end outer switch
|
||||
//console.log('p++',p)
|
||||
p++;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @return true if has new namespace define
|
||||
*/
|
||||
function appendElement(el,domBuilder,currentNSMap){
|
||||
var tagName = el.tagName;
|
||||
var localNSMap = null;
|
||||
//var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
|
||||
var i = el.length;
|
||||
while(i--){
|
||||
var a = el[i];
|
||||
var qName = a.qName;
|
||||
var value = a.value;
|
||||
var nsp = qName.indexOf(':');
|
||||
if(nsp>0){
|
||||
var prefix = a.prefix = qName.slice(0,nsp);
|
||||
var localName = qName.slice(nsp+1);
|
||||
var nsPrefix = prefix === 'xmlns' && localName
|
||||
}else{
|
||||
localName = qName;
|
||||
prefix = null
|
||||
nsPrefix = qName === 'xmlns' && ''
|
||||
}
|
||||
//can not set prefix,because prefix !== ''
|
||||
a.localName = localName ;
|
||||
//prefix == null for no ns prefix attribute
|
||||
if(nsPrefix !== false){//hack!!
|
||||
if(localNSMap == null){
|
||||
localNSMap = {}
|
||||
// Derive the child scope's namespace map by prototype-chain inheritance
|
||||
// instead of a flat copy: lookups inherit ancestor prefixes transparently,
|
||||
// so a document nesting N scopes retains O(N) map entries rather than
|
||||
// sum(1..N) = O(N^2). localNSMap stays a flat own-only record of the
|
||||
// prefixes declared at THIS element, so own-property enumeration
|
||||
// (endPrefixMapping below) still reports only local declarations.
|
||||
currentNSMap = Object.create(currentNSMap)
|
||||
}
|
||||
currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
|
||||
a.uri = NAMESPACE.XMLNS
|
||||
domBuilder.startPrefixMapping(nsPrefix, value)
|
||||
}
|
||||
}
|
||||
var i = el.length;
|
||||
while(i--){
|
||||
a = el[i];
|
||||
var prefix = a.prefix;
|
||||
if(prefix){//no prefix attribute has no namespace
|
||||
if(prefix === 'xml'){
|
||||
a.uri = NAMESPACE.XML;
|
||||
}if(prefix !== 'xmlns'){
|
||||
a.uri = currentNSMap[prefix || '']
|
||||
|
||||
//{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
|
||||
}
|
||||
}
|
||||
}
|
||||
var nsp = tagName.indexOf(':');
|
||||
if(nsp>0){
|
||||
prefix = el.prefix = tagName.slice(0,nsp);
|
||||
localName = el.localName = tagName.slice(nsp+1);
|
||||
}else{
|
||||
prefix = null;//important!!
|
||||
localName = el.localName = tagName;
|
||||
}
|
||||
//no prefix element has default namespace
|
||||
var ns = el.uri = currentNSMap[prefix || ''];
|
||||
domBuilder.startElement(ns,localName,tagName,el);
|
||||
//endPrefixMapping and startPrefixMapping have not any help for dom builder
|
||||
//localNSMap = null
|
||||
if(el.closed){
|
||||
domBuilder.endElement(ns,localName,tagName);
|
||||
if(localNSMap){
|
||||
for (prefix in localNSMap) {
|
||||
if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) {
|
||||
domBuilder.endPrefixMapping(prefix);
|
||||
}
|
||||
}
|
||||
}
|
||||
}else{
|
||||
el.currentNSMap = currentNSMap;
|
||||
el.localNSMap = localNSMap;
|
||||
//parseStack.push(el);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
|
||||
if(/^(?:script|textarea)$/i.test(tagName)){
|
||||
var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
|
||||
var text = source.substring(elStartEnd+1,elEndStart);
|
||||
if(/[&<]/.test(text)){
|
||||
if(/^script$/i.test(tagName)){
|
||||
//if(!/\]\]>/.test(text)){
|
||||
//lexHandler.startCDATA();
|
||||
domBuilder.characters(text,0,text.length);
|
||||
//lexHandler.endCDATA();
|
||||
return elEndStart;
|
||||
//}
|
||||
}//}else{//text area
|
||||
text = text.replace(/&#?\w+;/g,entityReplacer);
|
||||
domBuilder.characters(text,0,text.length);
|
||||
return elEndStart;
|
||||
//}
|
||||
|
||||
}
|
||||
}
|
||||
return elStartEnd+1;
|
||||
}
|
||||
function fixSelfClosed(source,elStartEnd,tagName,closeMap){
|
||||
//if(tagName in closeMap){
|
||||
var pos = closeMap[tagName];
|
||||
if(pos == null){
|
||||
//console.log(tagName)
|
||||
pos = source.lastIndexOf('</'+tagName+'>')
|
||||
if(pos<elStartEnd){//忘记闭合
|
||||
pos = source.lastIndexOf('</'+tagName)
|
||||
}
|
||||
closeMap[tagName] =pos
|
||||
}
|
||||
return pos<elStartEnd;
|
||||
//}
|
||||
}
|
||||
|
||||
function _copy (source, target) {
|
||||
for (var n in source) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, n)) {
|
||||
target[n] = source[n];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
|
||||
var next= source.charAt(start+2)
|
||||
switch(next){
|
||||
case '-':
|
||||
if(source.charAt(start + 3) === '-'){
|
||||
var end = source.indexOf('-->',start+4);
|
||||
//append comment source.substring(4,end)//<!--
|
||||
if(end>start){
|
||||
domBuilder.comment(source,start+4,end-start-4);
|
||||
return end+3;
|
||||
}else{
|
||||
errorHandler.error("Unclosed comment");
|
||||
return -1;
|
||||
}
|
||||
}else{
|
||||
//error
|
||||
return -1;
|
||||
}
|
||||
default:
|
||||
if(source.substr(start+3,6) == 'CDATA['){
|
||||
var end = source.indexOf(']]>',start+9);
|
||||
domBuilder.startCDATA();
|
||||
domBuilder.characters(source,start+9,end-start-9);
|
||||
domBuilder.endCDATA()
|
||||
return end+3;
|
||||
}
|
||||
//<!DOCTYPE
|
||||
//startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
|
||||
var matchs = split(source,start);
|
||||
var len = matchs.length;
|
||||
if(len>1 && /!doctype/i.test(matchs[0][0])){
|
||||
var name = matchs[1][0];
|
||||
var pubid = false;
|
||||
var sysid = false;
|
||||
if(len>3){
|
||||
if(/^public$/i.test(matchs[2][0])){
|
||||
pubid = matchs[3][0];
|
||||
sysid = len>4 && matchs[4][0];
|
||||
}else if(/^system$/i.test(matchs[2][0])){
|
||||
sysid = matchs[3][0];
|
||||
}
|
||||
}
|
||||
var lastMatch = matchs[len-1]
|
||||
domBuilder.startDTD(name, pubid, sysid);
|
||||
domBuilder.endDTD();
|
||||
|
||||
return lastMatch.index+lastMatch[0].length
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
function parseInstruction(source,start,domBuilder){
|
||||
var end = source.indexOf('?>',start);
|
||||
if(end){
|
||||
var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)$/);
|
||||
if(match){
|
||||
var len = match[0].length;
|
||||
domBuilder.processingInstruction(match[1], match[2]) ;
|
||||
return end+2;
|
||||
}else{//error
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function ElementAttributes(){
|
||||
this.attributeNames = {}
|
||||
}
|
||||
ElementAttributes.prototype = {
|
||||
setTagName:function(tagName){
|
||||
if(!tagNamePattern.test(tagName)){
|
||||
throw new Error('invalid tagName:'+tagName)
|
||||
}
|
||||
this.tagName = tagName
|
||||
},
|
||||
addValue:function(qName, value, offset) {
|
||||
if(!tagNamePattern.test(qName)){
|
||||
throw new Error('invalid attribute:'+qName)
|
||||
}
|
||||
this.attributeNames[qName] = this.length;
|
||||
this[this.length++] = {qName:qName,value:value,offset:offset}
|
||||
},
|
||||
length:0,
|
||||
getLocalName:function(i){return this[i].localName},
|
||||
getLocator:function(i){return this[i].locator},
|
||||
getQName:function(i){return this[i].qName},
|
||||
getURI:function(i){return this[i].uri},
|
||||
getValue:function(i){return this[i].value}
|
||||
// ,getIndex:function(uri, localName)){
|
||||
// if(localName){
|
||||
//
|
||||
// }else{
|
||||
// var qName = uri
|
||||
// }
|
||||
// },
|
||||
// getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
|
||||
// getType:function(uri,localName){}
|
||||
// getType:function(i){},
|
||||
}
|
||||
|
||||
|
||||
|
||||
function split(source,start){
|
||||
var match;
|
||||
var buf = [];
|
||||
var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
|
||||
reg.lastIndex = start;
|
||||
reg.exec(source);//skip <
|
||||
while(match = reg.exec(source)){
|
||||
buf.push(match);
|
||||
if(match[1])return buf;
|
||||
}
|
||||
}
|
||||
|
||||
exports.XMLReader = XMLReader;
|
||||
exports.ParseError = ParseError;
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"name": "@xmldom/xmldom",
|
||||
"version": "0.8.15",
|
||||
"description": "A pure JavaScript W3C standard-based (XML DOM Level 2 Core) DOMParser and XMLSerializer module.",
|
||||
"keywords": [
|
||||
"w3c",
|
||||
"dom",
|
||||
"xml",
|
||||
"parser",
|
||||
"javascript",
|
||||
"DOMParser",
|
||||
"XMLSerializer",
|
||||
"ponyfill"
|
||||
],
|
||||
"homepage": "https://github.com/xmldom/xmldom",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/xmldom/xmldom.git"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"types": "index.d.ts",
|
||||
"files": [
|
||||
"CHANGELOG.md",
|
||||
"LICENSE",
|
||||
"readme.md",
|
||||
"SECURITY.md",
|
||||
"index.d.ts",
|
||||
"lib"
|
||||
],
|
||||
"config": {
|
||||
"test_stack_size": 256
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint lib test",
|
||||
"format": "prettier --write test",
|
||||
"format:check": "prettier --check test",
|
||||
"changelog": "auto-changelog --unreleased-only",
|
||||
"start": "nodemon --watch package.json --watch lib --watch test --exec 'npm --silent run test && npm --silent run lint'",
|
||||
"stryker": "stryker run",
|
||||
"stryker:dry-run": "stryker run -m '' --reporters progress",
|
||||
"test": "node --stack-size=$npm_package_config_test_stack_size ./node_modules/.bin/jest",
|
||||
"testrelease": "npm test && eslint lib",
|
||||
"version": "./changelog-has-version.sh",
|
||||
"release": "np --no-yarn --test-script testrelease --branch release-0.8.x patch"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@stryker-mutator/core": "5.6.1",
|
||||
"auto-changelog": "2.4.0",
|
||||
"eslint": "8.25.0",
|
||||
"eslint-config-prettier": "8.5.0",
|
||||
"eslint-plugin-es5": "1.5.0",
|
||||
"eslint-plugin-prettier": "4.2.1",
|
||||
"get-stream": "6.0.1",
|
||||
"jest": "27.5.1",
|
||||
"nodemon": "2.0.20",
|
||||
"np": "9.2.0",
|
||||
"prettier": "2.7.1",
|
||||
"xmltest": "1.5.0",
|
||||
"yauzl": "2.10.0"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/xmldom/xmldom/issues"
|
||||
},
|
||||
"license": "MIT",
|
||||
"auto-changelog": {
|
||||
"prepend": true,
|
||||
"remote": "upstream",
|
||||
"tagPrefix": "",
|
||||
"template": "./auto-changelog.hbs"
|
||||
}
|
||||
}
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
# @xmldom/xmldom
|
||||
|
||||
***Since version 0.7.0 this package is published to npm as [`@xmldom/xmldom`](https://www.npmjs.com/package/@xmldom/xmldom) and no longer as [`xmldom`](https://www.npmjs.com/package/xmldom), because [we are no longer able to publish `xmldom`](https://github.com/xmldom/xmldom/issues/271).***
|
||||
*For better readability in the docs we will continue to talk about this library as "xmldom".*
|
||||
|
||||
[](https://github.com/xmldom/xmldom/blob/master/LICENSE)
|
||||
[](https://www.npmjs.com/package/@xmldom/xmldom)
|
||||
[](https://snyk.io/advisor/npm-package/@xmldom/xmldom)
|
||||
[](https://github.com/xmldom/xmldom/issues?q=is%3Aissue+is%3Aopen+label%3Abug)
|
||||
[](https://github.com/xmldom/xmldom/issues?q=is%3Aissue+is%3Aopen+label%3Ahelp-wanted)
|
||||
[](https://dashboard.stryker-mutator.io/reports/github.com/xmldom/xmldom/master)
|
||||
|
||||
|
||||
xmldom is a javascript [ponyfill](https://ponyfill.com/) to provide the following APIs [that are present in modern browsers](https://caniuse.com/xml-serializer) to other runtimes:
|
||||
- convert an XML string into a DOM tree
|
||||
```
|
||||
new DOMParser().parseFromString(xml, mimeType) => Document
|
||||
```
|
||||
- create, access and modify a DOM tree
|
||||
```
|
||||
new DOMImplementation().createDocument(...) => Document
|
||||
```
|
||||
- serialize a DOM tree back into an XML string
|
||||
```
|
||||
new XMLSerializer().serializeToString(node) => string
|
||||
```
|
||||
|
||||
The target runtimes `xmldom` supports are currently Node >= v10 (ES5) and Rhino ([not tested as part of CI](https://github.com/xmldom/xmldom/discussions/214)).
|
||||
|
||||
When deciding how to fix bugs or implement features, `xmldom` tries to stay as close as possible to the various [related specifications/standards](#specs).
|
||||
As indicated by the version starting with `0.`, this implementation is not feature complete and some implemented features differ from what the specifications describe.
|
||||
**Issues and PRs for such differences are always welcome, even when they only provide a failing test case.**
|
||||
|
||||
This project was forked from it's [original source](https://github.com/jindw/xmldom) in 2019, more details about that transition can be found in the [CHANGELOG](CHANGELOG.md#maintainer-changes).
|
||||
|
||||
## Usage
|
||||
|
||||
### Install:
|
||||
|
||||
> npm install @xmldom/xmldom
|
||||
|
||||
### Example:
|
||||
|
||||
[In NodeJS](examples/nodejs/src/index.js)
|
||||
```javascript
|
||||
const { DOMParser, XMLSerializer } = require('@xmldom/xmldom')
|
||||
|
||||
const source = `<xml xmlns="a">
|
||||
<child>test</child>
|
||||
<child/>
|
||||
</xml>`
|
||||
|
||||
const doc = new DOMParser().parseFromString(source, 'text/xml')
|
||||
|
||||
const serialized = new XMLSerializer().serializeToString(doc)
|
||||
```
|
||||
|
||||
Note: in Typescript ~and ES6~(see #316) you can use the `import` approach, as follows:
|
||||
|
||||
```typescript
|
||||
import { DOMParser } from '@xmldom/xmldom'
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
* [DOMParser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser):
|
||||
|
||||
```javascript
|
||||
parseFromString(xmlsource,mimeType)
|
||||
```
|
||||
* **options extension** _by xmldom_ (not DOM standard!!)
|
||||
|
||||
```javascript
|
||||
//added the options argument
|
||||
new DOMParser(options)
|
||||
|
||||
//errorHandler is supported
|
||||
new DOMParser({
|
||||
/**
|
||||
* locator is always need for error position info
|
||||
*/
|
||||
locator:{},
|
||||
/**
|
||||
* you can override the errorHandler for xml parser
|
||||
* @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
|
||||
*/
|
||||
errorHandler:{warning:function(w){console.warn(w)},error:callback,fatalError:callback}
|
||||
//only callback model
|
||||
//errorHandler:function(level,msg){console.log(level,msg)}
|
||||
})
|
||||
|
||||
```
|
||||
|
||||
* [XMLSerializer](https://developer.mozilla.org/en-US/docs/Web/API/XMLSerializer)
|
||||
|
||||
```javascript
|
||||
serializeToString(node)
|
||||
```
|
||||
### DOM level2 method and attribute:
|
||||
|
||||
* [Node](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247)
|
||||
|
||||
readonly class properties (aka `NodeType`),
|
||||
these can be accessed from any `Node` instance `node`:
|
||||
`if (node.nodeType === node.ELEMENT_NODE) {...`
|
||||
|
||||
1. `ELEMENT_NODE` (`1`)
|
||||
2. `ATTRIBUTE_NODE` (`2`)
|
||||
3. `TEXT_NODE` (`3`)
|
||||
4. `CDATA_SECTION_NODE` (`4`)
|
||||
5. `ENTITY_REFERENCE_NODE` (`5`)
|
||||
6. `ENTITY_NODE` (`6`)
|
||||
7. `PROCESSING_INSTRUCTION_NODE` (`7`)
|
||||
8. `COMMENT_NODE` (`8`)
|
||||
9. `DOCUMENT_NODE` (`9`)
|
||||
10. `DOCUMENT_TYPE_NODE` (`10`)
|
||||
11. `DOCUMENT_FRAGMENT_NODE` (`11`)
|
||||
12. `NOTATION_NODE` (`12`)
|
||||
|
||||
attribute:
|
||||
- `nodeValue` | `prefix`
|
||||
|
||||
readonly attribute:
|
||||
- `nodeName` | `nodeType` | `parentNode` | `childNodes` | `firstChild` | `lastChild` | `previousSibling` | `nextSibling` | `attributes` | `ownerDocument` | `namespaceURI` | `localName`
|
||||
|
||||
method:
|
||||
* `insertBefore(newChild, refChild)`
|
||||
* `replaceChild(newChild, oldChild)`
|
||||
* `removeChild(oldChild)`
|
||||
* `appendChild(newChild)`
|
||||
* `hasChildNodes()`
|
||||
* `cloneNode(deep)`
|
||||
* `normalize()`
|
||||
* `isSupported(feature, version)`
|
||||
* `hasAttributes()`
|
||||
* [DOMException](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html)
|
||||
|
||||
extends the Error type thrown as part of DOM API.
|
||||
|
||||
readonly class properties:
|
||||
- `INDEX_SIZE_ERR` (`1`)
|
||||
- `DOMSTRING_SIZE_ERR` (`2`)
|
||||
- `HIERARCHY_REQUEST_ERR` (`3`)
|
||||
- `WRONG_DOCUMENT_ERR` (`4`)
|
||||
- `INVALID_CHARACTER_ERR` (`5`)
|
||||
- `NO_DATA_ALLOWED_ERR` (`6`)
|
||||
- `NO_MODIFICATION_ALLOWED_ERR` (`7`)
|
||||
- `NOT_FOUND_ERR` (`8`)
|
||||
- `NOT_SUPPORTED_ERR` (`9`)
|
||||
- `INUSE_ATTRIBUTE_ERR` (`10`)
|
||||
- `INVALID_STATE_ERR` (`11`)
|
||||
- `SYNTAX_ERR` (`12`)
|
||||
- `INVALID_MODIFICATION_ERR` (`13`)
|
||||
- `NAMESPACE_ERR` (`14`)
|
||||
- `INVALID_ACCESS_ERR` (`15`)
|
||||
|
||||
attributes:
|
||||
- `code` with a value matching one of the above constants.
|
||||
|
||||
* [DOMImplementation](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-102161490)
|
||||
|
||||
method:
|
||||
- `hasFeature(feature, version)`
|
||||
- `createDocumentType(qualifiedName, publicId, systemId)`
|
||||
- `createDocument(namespaceURI, qualifiedName, doctype)`
|
||||
|
||||
* [Document](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#i-Document) : Node
|
||||
|
||||
readonly attribute:
|
||||
- `doctype` | `implementation` | `documentElement`
|
||||
|
||||
method:
|
||||
- `createElement(tagName)`
|
||||
- `createDocumentFragment()`
|
||||
- `createTextNode(data)`
|
||||
- `createComment(data)`
|
||||
- `createCDATASection(data)`
|
||||
- `createProcessingInstruction(target, data)`
|
||||
- `createAttribute(name)`
|
||||
- `createEntityReference(name)`
|
||||
- `getElementsByTagName(tagname)`
|
||||
- `importNode(importedNode, deep)`
|
||||
- `createElementNS(namespaceURI, qualifiedName)`
|
||||
- `createAttributeNS(namespaceURI, qualifiedName)`
|
||||
- `getElementsByTagNameNS(namespaceURI, localName)`
|
||||
- `getElementById(elementId)`
|
||||
|
||||
* [DocumentFragment](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-B63ED1A3) : Node
|
||||
* [Element](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-745549614) : Node
|
||||
|
||||
readonly attribute:
|
||||
- `tagName`
|
||||
|
||||
method:
|
||||
- `getAttribute(name)`
|
||||
- `setAttribute(name, value)`
|
||||
- `removeAttribute(name)`
|
||||
- `getAttributeNode(name)`
|
||||
- `setAttributeNode(newAttr)`
|
||||
- `removeAttributeNode(oldAttr)`
|
||||
- `getElementsByTagName(name)`
|
||||
- `getAttributeNS(namespaceURI, localName)`
|
||||
- `setAttributeNS(namespaceURI, qualifiedName, value)`
|
||||
- `removeAttributeNS(namespaceURI, localName)`
|
||||
- `getAttributeNodeNS(namespaceURI, localName)`
|
||||
- `setAttributeNodeNS(newAttr)`
|
||||
- `getElementsByTagNameNS(namespaceURI, localName)`
|
||||
- `hasAttribute(name)`
|
||||
- `hasAttributeNS(namespaceURI, localName)`
|
||||
|
||||
* [Attr](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-637646024) : Node
|
||||
|
||||
attribute:
|
||||
- `value`
|
||||
|
||||
readonly attribute:
|
||||
- `name` | `specified` | `ownerElement`
|
||||
|
||||
* [NodeList](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177)
|
||||
|
||||
readonly attribute:
|
||||
- `length`
|
||||
|
||||
method:
|
||||
- `item(index)`
|
||||
|
||||
* [NamedNodeMap](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1780488922)
|
||||
|
||||
readonly attribute:
|
||||
- `length`
|
||||
|
||||
method:
|
||||
- `getNamedItem(name)`
|
||||
- `setNamedItem(arg)`
|
||||
- `removeNamedItem(name)`
|
||||
- `item(index)`
|
||||
- `getNamedItemNS(namespaceURI, localName)`
|
||||
- `setNamedItemNS(arg)`
|
||||
- `removeNamedItemNS(namespaceURI, localName)`
|
||||
|
||||
* [CharacterData](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-FF21A306) : Node
|
||||
|
||||
method:
|
||||
- `substringData(offset, count)`
|
||||
- `appendData(arg)`
|
||||
- `insertData(offset, arg)`
|
||||
- `deleteData(offset, count)`
|
||||
- `replaceData(offset, count, arg)`
|
||||
|
||||
* [Text](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1312295772) : CharacterData
|
||||
|
||||
method:
|
||||
- `splitText(offset)`
|
||||
|
||||
* [CDATASection](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-667469212)
|
||||
* [Comment](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1728279322) : CharacterData
|
||||
|
||||
* [DocumentType](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-412266927)
|
||||
|
||||
readonly attribute:
|
||||
- `name` | `entities` | `notations` | `publicId` | `systemId` | `internalSubset`
|
||||
|
||||
* Notation : Node
|
||||
|
||||
readonly attribute:
|
||||
- `publicId` | `systemId`
|
||||
|
||||
* Entity : Node
|
||||
|
||||
readonly attribute:
|
||||
- `publicId` | `systemId` | `notationName`
|
||||
|
||||
* EntityReference : Node
|
||||
* ProcessingInstruction : Node
|
||||
|
||||
attribute:
|
||||
- `data`
|
||||
readonly attribute:
|
||||
- `target`
|
||||
|
||||
### DOM level 3 support:
|
||||
|
||||
* [Node](http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-textContent)
|
||||
|
||||
attribute:
|
||||
- `textContent`
|
||||
|
||||
method:
|
||||
- `isDefaultNamespace(namespaceURI)`
|
||||
- `lookupNamespaceURI(prefix)`
|
||||
|
||||
### DOM extension by xmldom
|
||||
|
||||
* [Node] Source position extension;
|
||||
|
||||
attribute:
|
||||
- `lineNumber` //number starting from `1`
|
||||
- `columnNumber` //number starting from `1`
|
||||
|
||||
## Specs
|
||||
|
||||
The implementation is based on several specifications:
|
||||
|
||||
<!-- Should open in new tab and the links in the SVG should be clickable there! -->
|
||||
<a href="https://raw.githubusercontent.com/xmldom/xmldom/master/docs/specs.svg" target="_blank" rel="noopener noreferrer nofollow" ></a>
|
||||
|
||||
### DOM Parsing and Serialization
|
||||
|
||||
From the [W3C DOM Parsing and Serialization (WD 2016)](https://www.w3.org/TR/2016/WD-DOM-Parsing-20160517/) `xmldom` provides an implementation for the interfaces:
|
||||
- `DOMParser`
|
||||
- `XMLSerializer`
|
||||
|
||||
Note that there are some known deviations between this implementation and the W3 specifications.
|
||||
|
||||
Note: [The latest version of this spec](https://w3c.github.io/DOM-Parsing/) has the status "Editors Draft", since it is under active development. One major change is that [the definition of the `DOMParser` interface has been moved to the HTML spec](https://w3c.github.io/DOM-Parsing/#the-domparser-interface)
|
||||
|
||||
|
||||
### DOM
|
||||
|
||||
The original author claims that xmldom implements [DOM Level 2] in a "fully compatible" way and some parts of [DOM Level 3], but there are not enough tests to prove this. Both Specifications are now superseded by the [DOM Level 4 aka Living standard] wich has a much broader scope than xmldom.
|
||||
|
||||
xmldom implements the following interfaces (most constructors are currently not exposed):
|
||||
- `Attr`
|
||||
- `CDATASection`
|
||||
- `CharacterData`
|
||||
- `Comment`
|
||||
- `Document`
|
||||
- `DocumentFragment`
|
||||
- `DocumentType`
|
||||
- `DOMException` (constructor exposed)
|
||||
- `DOMImplementation` (constructor exposed)
|
||||
- `Element`
|
||||
- `Entity`
|
||||
- `EntityReference`
|
||||
- `LiveNodeList`
|
||||
- `NamedNodeMap`
|
||||
- `Node` (constructor exposed)
|
||||
- `NodeList`
|
||||
- `Notation`
|
||||
- `ProcessingInstruction`
|
||||
- `Text`
|
||||
|
||||
more details are available in the (incomplete) [API Reference](#api-reference) section.
|
||||
|
||||
### HTML
|
||||
|
||||
xmldom does not have any goal of supporting the full spec, but it has some capability to parse, report and serialize things differently when "detecting HTML" (by checking the default namespace).
|
||||
There is an upcoming change to better align the implementation with the latest specs, related to <https://github.com/xmldom/xmldom/issues/203>.
|
||||
|
||||
### SAX, XML, XMLNS
|
||||
|
||||
xmldom has an own SAX parser implementation to do the actual parsing, which implements some interfaces in alignment with the Java interfaces SAX defines:
|
||||
- `XMLReader`
|
||||
- `DOMHandler`
|
||||
|
||||
There is an idea/proposal to make it possible to replace it with something else in <https://github.com/xmldom/xmldom/issues/55>
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
This software is dual-licensed under the ISC and MIT licenses.
|
||||
You may use this software under EITHER of the following licenses.
|
||||
|
||||
----------
|
||||
|
||||
The ISC License
|
||||
|
||||
Copyright (c) Isaac Z. Schlueter and Contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
|
||||
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
----------
|
||||
|
||||
Copyright Isaac Z. Schlueter and Contributors
|
||||
All rights reserved.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
# abbrev-js
|
||||
|
||||
Just like [ruby's Abbrev](http://apidock.com/ruby/Abbrev).
|
||||
|
||||
Usage:
|
||||
|
||||
var abbrev = require("abbrev");
|
||||
abbrev("foo", "fool", "folding", "flop");
|
||||
|
||||
// returns:
|
||||
{ fl: 'flop'
|
||||
, flo: 'flop'
|
||||
, flop: 'flop'
|
||||
, fol: 'folding'
|
||||
, fold: 'folding'
|
||||
, foldi: 'folding'
|
||||
, foldin: 'folding'
|
||||
, folding: 'folding'
|
||||
, foo: 'foo'
|
||||
, fool: 'fool'
|
||||
}
|
||||
|
||||
This is handy for command-line scripts, or other cases where you want to be able to accept shorthands.
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
module.exports = abbrev
|
||||
|
||||
function abbrev (...args) {
|
||||
let list = args
|
||||
if (args.length === 1 && (Array.isArray(args[0]) || typeof args[0] === 'string')) {
|
||||
list = [].concat(args[0])
|
||||
}
|
||||
|
||||
for (let i = 0, l = list.length; i < l; i++) {
|
||||
list[i] = typeof list[i] === 'string' ? list[i] : String(list[i])
|
||||
}
|
||||
|
||||
// sort them lexicographically, so that they're next to their nearest kin
|
||||
list = list.sort(lexSort)
|
||||
|
||||
// walk through each, seeing how much it has in common with the next and previous
|
||||
const abbrevs = {}
|
||||
let prev = ''
|
||||
for (let ii = 0, ll = list.length; ii < ll; ii++) {
|
||||
const current = list[ii]
|
||||
const next = list[ii + 1] || ''
|
||||
let nextMatches = true
|
||||
let prevMatches = true
|
||||
if (current === next) {
|
||||
continue
|
||||
}
|
||||
let j = 0
|
||||
const cl = current.length
|
||||
for (; j < cl; j++) {
|
||||
const curChar = current.charAt(j)
|
||||
nextMatches = nextMatches && curChar === next.charAt(j)
|
||||
prevMatches = prevMatches && curChar === prev.charAt(j)
|
||||
if (!nextMatches && !prevMatches) {
|
||||
j++
|
||||
break
|
||||
}
|
||||
}
|
||||
prev = current
|
||||
if (j === cl) {
|
||||
abbrevs[current] = current
|
||||
continue
|
||||
}
|
||||
for (let a = current.slice(0, j); j <= cl; j++) {
|
||||
abbrevs[a] = current
|
||||
a += current.charAt(j)
|
||||
}
|
||||
}
|
||||
return abbrevs
|
||||
}
|
||||
|
||||
function lexSort (a, b) {
|
||||
return a === b ? 0 : a > b ? 1 : -1
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "abbrev",
|
||||
"version": "4.0.0",
|
||||
"description": "Like ruby's abbrev module, but in js",
|
||||
"author": "GitHub Inc.",
|
||||
"main": "lib/index.js",
|
||||
"scripts": {
|
||||
"test": "node --test",
|
||||
"lint": "npm run eslint",
|
||||
"postlint": "template-oss-check",
|
||||
"template-oss-apply": "template-oss-apply --force",
|
||||
"lintfix": "npm run eslint -- --fix",
|
||||
"snap": "node --test --test-update-snapshots",
|
||||
"posttest": "npm run lint",
|
||||
"eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
|
||||
"test:cover": "node --test --experimental-test-coverage --test-timeout=3000 --test-coverage-lines=100 --test-coverage-functions=100 --test-coverage-branches=100"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/npm/abbrev-js.git"
|
||||
},
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"@npmcli/eslint-config": "^5.0.0",
|
||||
"@npmcli/template-oss": "4.26.1"
|
||||
},
|
||||
"files": [
|
||||
"bin/",
|
||||
"lib/"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.17.0 || >=22.9.0"
|
||||
},
|
||||
"templateOSS": {
|
||||
"//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
|
||||
"version": "4.26.1",
|
||||
"publish": true,
|
||||
"testRunner": "node:test",
|
||||
"latestCiVersion": 24
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/// <reference types="node" />
|
||||
/// <reference types="node" />
|
||||
/// <reference types="node" />
|
||||
/// <reference types="node" />
|
||||
/// <reference types="node" />
|
||||
import * as http from 'http';
|
||||
import * as https from 'https';
|
||||
import type { Readable } from 'stream';
|
||||
export type ThenableRequest = http.ClientRequest & {
|
||||
then: Promise<http.IncomingMessage>['then'];
|
||||
};
|
||||
export declare function toBuffer(stream: Readable): Promise<Buffer>;
|
||||
export declare function json(stream: Readable): Promise<any>;
|
||||
export declare function req(url: string | URL, opts?: https.RequestOptions): ThenableRequest;
|
||||
//# sourceMappingURL=helpers.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";;;;;AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAEvC,MAAM,MAAM,eAAe,GAAG,IAAI,CAAC,aAAa,GAAG;IAClD,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC;CAC5C,CAAC;AAEF,wBAAsB,QAAQ,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,CAQhE;AAGD,wBAAsB,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,CAUzD;AAED,wBAAgB,GAAG,CAClB,GAAG,EAAE,MAAM,GAAG,GAAG,EACjB,IAAI,GAAE,KAAK,CAAC,cAAmB,GAC7B,eAAe,CAcjB"}
|
||||
Reference in New Issue
Block a user