Website Structure

This commit is contained in:
supalerk-ar66 2026-01-13 10:46:40 +07:00
parent 62812f2090
commit 71f0676a62
22365 changed files with 4265753 additions and 791 deletions

View file

@ -0,0 +1,7 @@
import type nodeAsyncHooks from "node:async_hooks";
export declare const createHook: typeof nodeAsyncHooks.createHook;
export declare const executionAsyncId: typeof nodeAsyncHooks.executionAsyncId;
export declare const executionAsyncResource: typeof nodeAsyncHooks.executionAsyncResource;
export declare const triggerAsyncId: typeof nodeAsyncHooks.triggerAsyncId;
// @ts-expect-error @types/node is missing this one - this is a bug in typings
export declare const asyncWrapProviders: typeof nodeAsyncHooks.asyncWrapProviders;

View file

@ -0,0 +1,115 @@
const kInit = /* @__PURE__ */ Symbol("init");
const kBefore = /* @__PURE__ */ Symbol("before");
const kAfter = /* @__PURE__ */ Symbol("after");
const kDestroy = /* @__PURE__ */ Symbol("destroy");
const kPromiseResolve = /* @__PURE__ */ Symbol("promiseResolve");
class _AsyncHook {
__unenv__ = true;
_enabled = false;
_callbacks = {};
constructor(callbacks = {}) {
this._callbacks = callbacks;
}
enable() {
this._enabled = true;
return this;
}
disable() {
this._enabled = false;
return this;
}
get [kInit]() {
return this._callbacks.init;
}
get [kBefore]() {
return this._callbacks.before;
}
get [kAfter]() {
return this._callbacks.after;
}
get [kDestroy]() {
return this._callbacks.destroy;
}
get [kPromiseResolve]() {
return this._callbacks.promiseResolve;
}
}
export const createHook = function createHook(callbacks) {
const asyncHook = new _AsyncHook(callbacks);
return asyncHook;
};
export const executionAsyncId = function executionAsyncId() {
return 0;
};
export const executionAsyncResource = function() {
return Object.create(null);
};
export const triggerAsyncId = function() {
return 0;
};
// @ts-expect-error @types/node is missing this one - this is a bug in typings
export const asyncWrapProviders = Object.assign(Object.create(null), {
NONE: 0,
DIRHANDLE: 1,
DNSCHANNEL: 2,
ELDHISTOGRAM: 3,
FILEHANDLE: 4,
FILEHANDLECLOSEREQ: 5,
BLOBREADER: 6,
FSEVENTWRAP: 7,
FSREQCALLBACK: 8,
FSREQPROMISE: 9,
GETADDRINFOREQWRAP: 10,
GETNAMEINFOREQWRAP: 11,
HEAPSNAPSHOT: 12,
HTTP2SESSION: 13,
HTTP2STREAM: 14,
HTTP2PING: 15,
HTTP2SETTINGS: 16,
HTTPINCOMINGMESSAGE: 17,
HTTPCLIENTREQUEST: 18,
JSSTREAM: 19,
JSUDPWRAP: 20,
MESSAGEPORT: 21,
PIPECONNECTWRAP: 22,
PIPESERVERWRAP: 23,
PIPEWRAP: 24,
PROCESSWRAP: 25,
PROMISE: 26,
QUERYWRAP: 27,
QUIC_ENDPOINT: 28,
QUIC_LOGSTREAM: 29,
QUIC_PACKET: 30,
QUIC_SESSION: 31,
QUIC_STREAM: 32,
QUIC_UDP: 33,
SHUTDOWNWRAP: 34,
SIGNALWRAP: 35,
STATWATCHER: 36,
STREAMPIPE: 37,
TCPCONNECTWRAP: 38,
TCPSERVERWRAP: 39,
TCPWRAP: 40,
TTYWRAP: 41,
UDPSENDWRAP: 42,
UDPWRAP: 43,
SIGINTWATCHDOG: 44,
WORKER: 45,
WORKERHEAPSNAPSHOT: 46,
WRITEWRAP: 47,
ZLIB: 48,
CHECKPRIMEREQUEST: 49,
PBKDF2REQUEST: 50,
KEYPAIRGENREQUEST: 51,
KEYGENREQUEST: 52,
KEYEXPORTREQUEST: 53,
CIPHERREQUEST: 54,
DERIVEBITSREQUEST: 55,
HASHREQUEST: 56,
RANDOMBYTESREQUEST: 57,
RANDOMPRIMEREQUEST: 58,
SCRYPTREQUEST: 59,
SIGNREQUEST: 60,
TLSWRAP: 61,
VERIFYREQUEST: 62
});

View file

@ -0,0 +1,2 @@
import type nodeAsyncHooks from "node:async_hooks";
export declare const AsyncLocalStorage: typeof nodeAsyncHooks.AsyncLocalStorage;

View file

@ -0,0 +1,36 @@
// https://nodejs.org/api/async_context.html#class-asynclocalstorage
class _AsyncLocalStorage {
__unenv__ = true;
_currentStore;
_enterStore;
_enabled = true;
getStore() {
return this._currentStore ?? this._enterStore;
}
disable() {
this._enabled = false;
}
enable() {
this._enabled = true;
}
enterWith(store) {
this._enterStore = store;
}
run(store, callback, ...args) {
this._currentStore = store;
const res = callback(...args);
this._currentStore = undefined;
return res;
}
exit(callback, ...args) {
const _previousStore = this._currentStore;
this._currentStore = undefined;
const res = callback(...args);
this._currentStore = _previousStore;
return res;
}
static snapshot() {
throw new Error("[unenv] `AsyncLocalStorage.snapshot` is not implemented!");
}
}
export const AsyncLocalStorage = globalThis.AsyncLocalStorage || _AsyncLocalStorage;

View file

@ -0,0 +1,2 @@
import type nodeAsyncHooks from "node:async_hooks";
export declare const AsyncResource: typeof nodeAsyncHooks.AsyncResource;

View file

@ -0,0 +1,37 @@
import { executionAsyncId } from "./async-hook.mjs";
// https://nodejs.org/api/async_context.html#class-asyncresource
let _asyncIdCounter = 100;
class _AsyncResource {
__unenv__ = true;
type;
_asyncId;
_triggerAsyncId;
constructor(type, triggerAsyncId = executionAsyncId()) {
this.type = type;
this._asyncId = -1 * _asyncIdCounter++;
this._triggerAsyncId = typeof triggerAsyncId === "number" ? triggerAsyncId : triggerAsyncId?.triggerAsyncId;
}
static bind(fn, type, thisArg) {
const resource = new AsyncResource(type ?? "anonymous");
return resource.bind(fn);
}
bind(fn, thisArg) {
const binded = (...args) => this.runInAsyncScope(fn, thisArg, ...args);
binded.asyncResource = this;
return binded;
}
runInAsyncScope(fn, thisArg, ...args) {
const result = fn.apply(thisArg, args);
return result;
}
emitDestroy() {
return this;
}
asyncId() {
return this._asyncId;
}
triggerAsyncId() {
return this._triggerAsyncId;
}
}
export const AsyncResource = globalThis.AsyncResource || _AsyncResource;

View file

@ -0,0 +1,4 @@
// base64 is 4/3 + up to two characters of the original data
export declare function byteLength(b64);
export declare function toByteArray(b64);
export declare function fromByteArray(uint8);

View file

@ -0,0 +1,97 @@
// @ts-nocheck
// Source: https://github.com/beatgammit/base64-js/blob/88957c9943c7e2a0f03cdf73e71d579e433627d3/index.js
const lookup = [];
const revLookup = [];
const Arr = typeof Uint8Array === "undefined" ? Array : Uint8Array;
const code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (let i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i];
revLookup[code.charCodeAt(i)] = i;
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup["-".charCodeAt(0)] = 62;
revLookup["_".charCodeAt(0)] = 63;
function getLens(b64) {
const len = b64.length;
if (len % 4 > 0) {
throw new Error("Invalid string. Length must be a multiple of 4");
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
let validLen = b64.indexOf("=");
if (validLen === -1) {
validLen = len;
}
const placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
return [validLen, placeHoldersLen];
}
// base64 is 4/3 + up to two characters of the original data
export function byteLength(b64) {
const lens = getLens(b64);
const validLen = lens[0];
const placeHoldersLen = lens[1];
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function _byteLength(b64, validLen, placeHoldersLen) {
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
export function toByteArray(b64) {
let tmp;
const lens = getLens(b64);
const validLen = lens[0];
const placeHoldersLen = lens[1];
const arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
let curByte = 0;
// if there are placeholders, only get up to the last complete 4 chars
const len = placeHoldersLen > 0 ? validLen - 4 : validLen;
let i;
for (i = 0; i < len; i += 4) {
tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
arr[curByte++] = tmp >> 16 & 255;
arr[curByte++] = tmp >> 8 & 255;
arr[curByte++] = tmp & 255;
}
if (placeHoldersLen === 2) {
tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
arr[curByte++] = tmp & 255;
}
if (placeHoldersLen === 1) {
tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
arr[curByte++] = tmp >> 8 & 255;
arr[curByte++] = tmp & 255;
}
return arr;
}
function tripletToBase64(num) {
return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
}
function encodeChunk(uint8, start, end) {
let tmp;
const output = [];
for (let i = start; i < end; i += 3) {
tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255);
output.push(tripletToBase64(tmp));
}
return output.join("");
}
export function fromByteArray(uint8) {
let tmp;
const len = uint8.length;
const extraBytes = len % 3;
const parts = [];
const maxChunkLength = 16383;
// go through the array every three bytes, we'll deal with trailing stuff later
for (let i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1];
parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==");
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1];
parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=");
}
return parts.join("");
}

View file

@ -0,0 +1,13 @@
export declare const INSPECT_MAX_BYTES = 50;
export declare const kMaxLength: unknown;
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
export declare function Buffer(arg, encodingOrOffset, length);
export declare function SlowBuffer(length);

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,14 @@
import type nodeBuffer from "node:buffer";
export declare class File extends Blob implements nodeBuffer.File {
readonly __unenv__: true;
size: number;
type: any;
name: string;
lastModified: number;
constructor(...args: any[]);
arrayBuffer(): Promise<ArrayBuffer>;
slice(): any;
text(): any;
stream(): any;
bytes(): Promise<Uint8Array<ArrayBuffer>>;
}

View file

@ -0,0 +1,26 @@
export class File extends Blob {
__unenv__ = true;
size = 0;
type = "";
name = "";
lastModified = 0;
constructor(...args) {
super(...args);
throw new Error("[unenv] buffer.File is not implemented");
}
arrayBuffer() {
throw new Error("Not implemented");
}
slice() {
throw new Error("Not implemented");
}
text() {
throw new Error("Not implemented");
}
stream() {
throw new Error("Not implemented");
}
bytes() {
throw new Error("Not implemented");
}
}

View file

@ -0,0 +1,4 @@
// Source: https://github.com/feross/ieee754/blob/8a0041f3d5e41b7cfcf0e0158fcf84b071709bda/index.js
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
export declare function read(buffer: Uint8Array, offset: number, isLE: boolean, mLen: number, nBytes: number);
export declare function write(buffer: Uint8Array, value: number, offset: number, isLE: boolean, mLen: number, nBytes: number);

View file

@ -0,0 +1,89 @@
// Source: https://github.com/feross/ieee754/blob/8a0041f3d5e41b7cfcf0e0158fcf84b071709bda/index.js
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
export function read(buffer, offset, isLE, mLen, nBytes) {
let e, m;
const eLen = nBytes * 8 - mLen - 1;
const eMax = (1 << eLen) - 1;
const eBias = eMax >> 1;
let nBits = -7;
let i = isLE ? nBytes - 1 : 0;
const d = isLE ? -1 : 1;
let s = buffer[offset + i];
i += d;
e = s & (1 << -nBits) - 1;
s >>= -nBits;
nBits += eLen;
while (nBits > 0) {
e = e * 256 + buffer[offset + i];
i += d;
nBits -= 8;
}
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
while (nBits > 0) {
m = m * 256 + buffer[offset + i];
i += d;
nBits -= 8;
}
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? Number.NaN : (s ? -1 : 1) * Number.POSITIVE_INFINITY;
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
}
export function write(buffer, value, offset, isLE, mLen, nBytes) {
let e, m, c;
let eLen = nBytes * 8 - mLen - 1;
const eMax = (1 << eLen) - 1;
const eBias = eMax >> 1;
const rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
let i = isLE ? 0 : nBytes - 1;
const d = isLE ? 1 : -1;
const s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
value = Math.abs(value);
if (Number.isNaN(value) || value === Number.POSITIVE_INFINITY) {
m = Number.isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log2(value));
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
value += e + eBias >= 1 ? rt / c : rt * Math.pow(2, 1 - eBias);
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
while (mLen >= 8) {
buffer[offset + i] = m & 255;
i += d;
m /= 256;
mLen -= 8;
}
e = e << mLen | m;
eLen += mLen;
while (eLen > 0) {
buffer[offset + i] = e & 255;
i += d;
e /= 256;
eLen -= 8;
}
buffer[offset + i - d] |= s * 128;
}

View file

@ -0,0 +1,58 @@
// npx -y node@22.14 -e 'const{constants}=require("crypto");console.log(Object.entries(constants).map(([k,v]) => `export const ${k} = ${JSON.stringify(v)}`).join("\n"))'
export declare const SSL_OP_ALL = 2147485776;
export declare const SSL_OP_ALLOW_NO_DHE_KEX = 1024;
export declare const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION = 262144;
export declare const SSL_OP_CIPHER_SERVER_PREFERENCE = 4194304;
export declare const SSL_OP_CISCO_ANYCONNECT = 32768;
export declare const SSL_OP_COOKIE_EXCHANGE = 8192;
export declare const SSL_OP_CRYPTOPRO_TLSEXT_BUG = 2147483648;
export declare const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS = 2048;
export declare const SSL_OP_LEGACY_SERVER_CONNECT = 4;
export declare const SSL_OP_NO_COMPRESSION = 131072;
export declare const SSL_OP_NO_ENCRYPT_THEN_MAC = 524288;
export declare const SSL_OP_NO_QUERY_MTU = 4096;
export declare const SSL_OP_NO_RENEGOTIATION = 1073741824;
export declare const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = 65536;
export declare const SSL_OP_NO_SSLv2 = 0;
export declare const SSL_OP_NO_SSLv3 = 33554432;
export declare const SSL_OP_NO_TICKET = 16384;
export declare const SSL_OP_NO_TLSv1 = 67108864;
export declare const SSL_OP_NO_TLSv1_1 = 268435456;
export declare const SSL_OP_NO_TLSv1_2 = 134217728;
export declare const SSL_OP_NO_TLSv1_3 = 536870912;
export declare const SSL_OP_PRIORITIZE_CHACHA = 2097152;
export declare const SSL_OP_TLS_ROLLBACK_BUG = 8388608;
export declare const ENGINE_METHOD_RSA = 1;
export declare const ENGINE_METHOD_DSA = 2;
export declare const ENGINE_METHOD_DH = 4;
export declare const ENGINE_METHOD_RAND = 8;
export declare const ENGINE_METHOD_EC = 2048;
export declare const ENGINE_METHOD_CIPHERS = 64;
export declare const ENGINE_METHOD_DIGESTS = 128;
export declare const ENGINE_METHOD_PKEY_METHS = 512;
export declare const ENGINE_METHOD_PKEY_ASN1_METHS = 1024;
export declare const ENGINE_METHOD_ALL = 65535;
export declare const ENGINE_METHOD_NONE = 0;
export declare const DH_CHECK_P_NOT_SAFE_PRIME = 2;
export declare const DH_CHECK_P_NOT_PRIME = 1;
export declare const DH_UNABLE_TO_CHECK_GENERATOR = 4;
export declare const DH_NOT_SUITABLE_GENERATOR = 8;
export declare const RSA_PKCS1_PADDING = 1;
export declare const RSA_NO_PADDING = 3;
export declare const RSA_PKCS1_OAEP_PADDING = 4;
export declare const RSA_X931_PADDING = 5;
export declare const RSA_PKCS1_PSS_PADDING = 6;
export declare const RSA_PSS_SALTLEN_DIGEST = -1;
export declare const RSA_PSS_SALTLEN_MAX_SIGN = -2;
export declare const RSA_PSS_SALTLEN_AUTO = -2;
export declare const POINT_CONVERSION_COMPRESSED = 2;
export declare const POINT_CONVERSION_UNCOMPRESSED = 4;
export declare const POINT_CONVERSION_HYBRID = 6;
// Versions explicitly set to 0 to avoid version misdetections
export declare const defaultCoreCipherList = "";
export declare const defaultCipherList = "";
export declare const OPENSSL_VERSION_NUMBER = 0;
export declare const TLS1_VERSION = 0;
export declare const TLS1_1_VERSION = 0;
export declare const TLS1_2_VERSION = 0;
export declare const TLS1_3_VERSION = 0;

View file

@ -0,0 +1,58 @@
// npx -y node@22.14 -e 'const{constants}=require("crypto");console.log(Object.entries(constants).map(([k,v]) => `export const ${k} = ${JSON.stringify(v)}`).join("\n"))'
export const SSL_OP_ALL = 2147485776;
export const SSL_OP_ALLOW_NO_DHE_KEX = 1024;
export const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION = 262144;
export const SSL_OP_CIPHER_SERVER_PREFERENCE = 4194304;
export const SSL_OP_CISCO_ANYCONNECT = 32768;
export const SSL_OP_COOKIE_EXCHANGE = 8192;
export const SSL_OP_CRYPTOPRO_TLSEXT_BUG = 2147483648;
export const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS = 2048;
export const SSL_OP_LEGACY_SERVER_CONNECT = 4;
export const SSL_OP_NO_COMPRESSION = 131072;
export const SSL_OP_NO_ENCRYPT_THEN_MAC = 524288;
export const SSL_OP_NO_QUERY_MTU = 4096;
export const SSL_OP_NO_RENEGOTIATION = 1073741824;
export const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = 65536;
export const SSL_OP_NO_SSLv2 = 0;
export const SSL_OP_NO_SSLv3 = 33554432;
export const SSL_OP_NO_TICKET = 16384;
export const SSL_OP_NO_TLSv1 = 67108864;
export const SSL_OP_NO_TLSv1_1 = 268435456;
export const SSL_OP_NO_TLSv1_2 = 134217728;
export const SSL_OP_NO_TLSv1_3 = 536870912;
export const SSL_OP_PRIORITIZE_CHACHA = 2097152;
export const SSL_OP_TLS_ROLLBACK_BUG = 8388608;
export const ENGINE_METHOD_RSA = 1;
export const ENGINE_METHOD_DSA = 2;
export const ENGINE_METHOD_DH = 4;
export const ENGINE_METHOD_RAND = 8;
export const ENGINE_METHOD_EC = 2048;
export const ENGINE_METHOD_CIPHERS = 64;
export const ENGINE_METHOD_DIGESTS = 128;
export const ENGINE_METHOD_PKEY_METHS = 512;
export const ENGINE_METHOD_PKEY_ASN1_METHS = 1024;
export const ENGINE_METHOD_ALL = 65535;
export const ENGINE_METHOD_NONE = 0;
export const DH_CHECK_P_NOT_SAFE_PRIME = 2;
export const DH_CHECK_P_NOT_PRIME = 1;
export const DH_UNABLE_TO_CHECK_GENERATOR = 4;
export const DH_NOT_SUITABLE_GENERATOR = 8;
export const RSA_PKCS1_PADDING = 1;
export const RSA_NO_PADDING = 3;
export const RSA_PKCS1_OAEP_PADDING = 4;
export const RSA_X931_PADDING = 5;
export const RSA_PKCS1_PSS_PADDING = 6;
export const RSA_PSS_SALTLEN_DIGEST = -1;
export const RSA_PSS_SALTLEN_MAX_SIGN = -2;
export const RSA_PSS_SALTLEN_AUTO = -2;
export const POINT_CONVERSION_COMPRESSED = 2;
export const POINT_CONVERSION_UNCOMPRESSED = 4;
export const POINT_CONVERSION_HYBRID = 6;
// Versions explicitly set to 0 to avoid version misdetections
export const defaultCoreCipherList = "";
export const defaultCipherList = "";
export const OPENSSL_VERSION_NUMBER = 0;
export const TLS1_VERSION = 0;
export const TLS1_1_VERSION = 0;
export const TLS1_2_VERSION = 0;
export const TLS1_3_VERSION = 0;

View file

@ -0,0 +1,78 @@
import type nodeCrypto from "node:crypto";
// ---- implemented Utils ----
export declare const webcrypto: unknown;
export declare const randomBytes: typeof nodeCrypto.randomBytes;
export declare const rng: unknown;
export declare const prng: unknown;
// ---- Constants ----
export declare const fips: typeof nodeCrypto.fips;
// ---- Unimplemented utils ----
export declare const checkPrime: unknown;
export declare const checkPrimeSync: unknown;
/** @deprecated https://nodejs.org/docs/latest/api/deprecations.html#dep0106-cryptocreatecipher-and-cryptocreatedecipher */
export declare const createCipher: undefined;
/** @deprecated https://nodejs.org/docs/latest/api/deprecations.html#dep0106-cryptocreatecipher-and-cryptocreatedecipher */
export declare const createDecipher: undefined;
export declare const pseudoRandomBytes: unknown;
export declare const createCipheriv: unknown;
export declare const createDecipheriv: unknown;
export declare const createDiffieHellman: unknown;
export declare const createDiffieHellmanGroup: unknown;
export declare const createECDH: unknown;
export declare const createHash: unknown;
export declare const createHmac: unknown;
export declare const createPrivateKey: unknown;
export declare const createPublicKey: unknown;
export declare const createSecretKey: unknown;
export declare const createSign: unknown;
export declare const createVerify: unknown;
export declare const diffieHellman: unknown;
export declare const generatePrime: unknown;
export declare const generatePrimeSync: unknown;
export declare const getCiphers: unknown;
export declare const getCipherInfo: unknown;
export declare const getCurves: unknown;
export declare const getDiffieHellman: unknown;
export declare const getHashes: unknown;
export declare const hkdf: unknown;
export declare const hkdfSync: unknown;
export declare const pbkdf2: unknown;
export declare const pbkdf2Sync: unknown;
export declare const generateKeyPair: unknown;
export declare const generateKeyPairSync: unknown;
export declare const generateKey: unknown;
export declare const generateKeySync: unknown;
export declare const privateDecrypt: unknown;
export declare const privateEncrypt: unknown;
export declare const publicDecrypt: unknown;
export declare const publicEncrypt: unknown;
export declare const randomFill: unknown;
export declare const randomFillSync: unknown;
export declare const randomInt: unknown;
export declare const scrypt: unknown;
export declare const scryptSync: unknown;
export declare const sign: unknown;
export declare const setEngine: unknown;
export declare const timingSafeEqual: unknown;
export declare const getFips: unknown;
export declare const setFips: unknown;
export declare const verify: unknown;
export declare const secureHeapUsed: unknown;
export declare const hash: unknown;
// ---- Unimplemented Classes ----
/** @deprecated https://nodejs.org/docs/latest/api/deprecations.html#dep0106-cryptocreatecipher-and-cryptocreatedecipher */
export declare const Cipher: typeof nodeCrypto.Cipher;
/** @deprecated https://nodejs.org/docs/latest/api/deprecations.html#dep0106-cryptocreatecipher-and-cryptocreatedecipher */
export declare const Decipher: typeof nodeCrypto.Decipher;
export declare const Certificate: typeof nodeCrypto.Certificate;
export declare const Cipheriv: typeof nodeCrypto.Cipheriv;
export declare const Decipheriv: typeof nodeCrypto.Decipheriv;
export declare const DiffieHellman: typeof nodeCrypto.DiffieHellman;
export declare const DiffieHellmanGroup: typeof nodeCrypto.DiffieHellmanGroup;
export declare const ECDH: typeof nodeCrypto.ECDH;
export declare const Hash: typeof nodeCrypto.Hash;
export declare const Hmac: typeof nodeCrypto.Hmac;
export declare const KeyObject: typeof nodeCrypto.KeyObject;
export declare const Sign: typeof nodeCrypto.Sign;
export declare const Verify: typeof nodeCrypto.Verify;
export declare const X509Certificate: typeof nodeCrypto.X509Certificate;

View file

@ -0,0 +1,110 @@
import { notImplemented, notImplementedClass } from "../../../_internal/utils.mjs";
import { getRandomValues } from "./web.mjs";
// limit of Crypto.getRandomValues()
// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
const MAX_RANDOM_VALUE_BYTES = 65536;
// ---- implemented Utils ----
export const webcrypto = new Proxy(globalThis.crypto, { get(_, key) {
if (key === "CryptoKey") {
return globalThis.CryptoKey;
}
if (typeof globalThis.crypto[key] === "function") {
// @ts-ignore
return globalThis.crypto[key].bind(globalThis.crypto);
}
return globalThis.crypto[key];
} });
export const randomBytes = (size, cb) => {
const bytes = Buffer.alloc(size, 0, undefined);
for (let generated = 0; generated < size; generated += MAX_RANDOM_VALUE_BYTES) {
getRandomValues(
// Use subarray to get a view of the buffer
Uint8Array.prototype.subarray.call(bytes, generated, generated + MAX_RANDOM_VALUE_BYTES)
);
}
if (typeof cb === "function") {
cb(null, bytes);
return undefined;
}
return bytes;
};
export const rng = randomBytes;
export const prng = randomBytes;
// ---- Constants ----
export const fips = false;
// ---- Unimplemented utils ----
export const checkPrime = /* @__PURE__ */ notImplemented("crypto.checkPrime");
export const checkPrimeSync = /* @__PURE__ */ notImplemented("crypto.checkPrimeSync");
/** @deprecated https://nodejs.org/docs/latest/api/deprecations.html#dep0106-cryptocreatecipher-and-cryptocreatedecipher */
export const createCipher = undefined;
/** @deprecated https://nodejs.org/docs/latest/api/deprecations.html#dep0106-cryptocreatecipher-and-cryptocreatedecipher */
export const createDecipher = undefined;
export const pseudoRandomBytes = /* @__PURE__ */ notImplemented("crypto.pseudoRandomBytes");
export const createCipheriv = /* @__PURE__ */ notImplemented("crypto.createCipheriv");
export const createDecipheriv = /* @__PURE__ */ notImplemented("crypto.createDecipheriv");
export const createDiffieHellman = /* @__PURE__ */ notImplemented("crypto.createDiffieHellman");
export const createDiffieHellmanGroup = /* @__PURE__ */ notImplemented("crypto.createDiffieHellmanGroup");
export const createECDH = /* @__PURE__ */ notImplemented("crypto.createECDH");
export const createHash = /* @__PURE__ */ notImplemented("crypto.createHash");
export const createHmac = /* @__PURE__ */ notImplemented("crypto.createHmac");
export const createPrivateKey = /* @__PURE__ */ notImplemented("crypto.createPrivateKey");
export const createPublicKey = /* @__PURE__ */ notImplemented("crypto.createPublicKey");
export const createSecretKey = /* @__PURE__ */ notImplemented("crypto.createSecretKey");
export const createSign = /* @__PURE__ */ notImplemented("crypto.createSign");
export const createVerify = /* @__PURE__ */ notImplemented("crypto.createVerify");
export const diffieHellman = /* @__PURE__ */ notImplemented("crypto.diffieHellman");
export const generatePrime = /* @__PURE__ */ notImplemented("crypto.generatePrime");
export const generatePrimeSync = /* @__PURE__ */ notImplemented("crypto.generatePrimeSync");
export const getCiphers = /* @__PURE__ */ notImplemented("crypto.getCiphers");
export const getCipherInfo = /* @__PURE__ */ notImplemented("crypto.getCipherInfo");
export const getCurves = /* @__PURE__ */ notImplemented("crypto.getCurves");
export const getDiffieHellman = /* @__PURE__ */ notImplemented("crypto.getDiffieHellman");
export const getHashes = /* @__PURE__ */ notImplemented("crypto.getHashes");
export const hkdf = /* @__PURE__ */ notImplemented("crypto.hkdf");
export const hkdfSync = /* @__PURE__ */ notImplemented("crypto.hkdfSync");
export const pbkdf2 = /* @__PURE__ */ notImplemented("crypto.pbkdf2");
export const pbkdf2Sync = /* @__PURE__ */ notImplemented("crypto.pbkdf2Sync");
export const generateKeyPair = /* @__PURE__ */ notImplemented("crypto.generateKeyPair");
export const generateKeyPairSync = /* @__PURE__ */ notImplemented("crypto.generateKeyPairSync");
export const generateKey = /* @__PURE__ */ notImplemented("crypto.generateKey");
export const generateKeySync = /* @__PURE__ */ notImplemented("crypto.generateKeySync");
export const privateDecrypt = /* @__PURE__ */ notImplemented("crypto.privateDecrypt");
export const privateEncrypt = /* @__PURE__ */ notImplemented("crypto.privateEncrypt");
export const publicDecrypt = /* @__PURE__ */ notImplemented("crypto.publicDecrypt");
export const publicEncrypt = /* @__PURE__ */ notImplemented("crypto.publicEncrypt");
export const randomFill = /* @__PURE__ */ notImplemented("crypto.randomFill");
export const randomFillSync = /* @__PURE__ */ notImplemented("crypto.randomFillSync");
export const randomInt = /* @__PURE__ */ notImplemented("crypto.randomInt");
export const scrypt = /* @__PURE__ */ notImplemented("crypto.scrypt");
export const scryptSync = /* @__PURE__ */ notImplemented("crypto.scryptSync");
export const sign = /* @__PURE__ */ notImplemented("crypto.sign");
export const setEngine = /* @__PURE__ */ notImplemented("crypto.setEngine");
export const timingSafeEqual = /* @__PURE__ */ notImplemented("crypto.timingSafeEqual");
export const getFips = /* @__PURE__ */ notImplemented("crypto.getFips");
export const setFips = /* @__PURE__ */ notImplemented("crypto.setFips");
export const verify = /* @__PURE__ */ notImplemented("crypto.verify");
export const secureHeapUsed = /* @__PURE__ */ notImplemented("crypto.secureHeapUsed");
export const hash = /* @__PURE__ */ notImplemented("crypto.hash");
// ---- Unimplemented Classes ----
/** @deprecated https://nodejs.org/docs/latest/api/deprecations.html#dep0106-cryptocreatecipher-and-cryptocreatedecipher */
export const Cipher = undefined;
/** @deprecated https://nodejs.org/docs/latest/api/deprecations.html#dep0106-cryptocreatecipher-and-cryptocreatedecipher */
export const Decipher = undefined;
export const Certificate = /* @__PURE__ */ notImplementedClass("crypto.Certificate");
export const Cipheriv = /* @__PURE__ */ notImplementedClass(
"crypto.Cipheriv"
// @ts-expect-error not typed yet
);
export const Decipheriv = /* @__PURE__ */ notImplementedClass(
"crypto.Decipheriv"
// @ts-expect-error not typed yet
);
export const DiffieHellman = /* @__PURE__ */ notImplementedClass("crypto.DiffieHellman");
export const DiffieHellmanGroup = /* @__PURE__ */ notImplementedClass("crypto.DiffieHellmanGroup");
export const ECDH = /* @__PURE__ */ notImplementedClass("crypto.ECDH");
export const Hash = /* @__PURE__ */ notImplementedClass("crypto.Hash");
export const Hmac = /* @__PURE__ */ notImplementedClass("crypto.Hmac");
export const KeyObject = /* @__PURE__ */ notImplementedClass("crypto.KeyObject");
export const Sign = /* @__PURE__ */ notImplementedClass("crypto.Sign");
export const Verify = /* @__PURE__ */ notImplementedClass("crypto.Verify");
export const X509Certificate = /* @__PURE__ */ notImplementedClass("crypto.X509Certificate");

View file

@ -0,0 +1,5 @@
// https://nodejs.org/api/crypto.html
// https://github.com/unjs/uncrypto
export declare const subtle: SubtleCrypto;
export declare const randomUUID: Crypto["randomUUID"];
export declare const getRandomValues: Crypto["getRandomValues"];

View file

@ -0,0 +1,9 @@
// https://nodejs.org/api/crypto.html
// https://github.com/unjs/uncrypto
export const subtle = globalThis.crypto?.subtle;
export const randomUUID = () => {
return globalThis.crypto?.randomUUID();
};
export const getRandomValues = (array) => {
return globalThis.crypto?.getRandomValues(array);
};

View file

@ -0,0 +1,31 @@
import { EventEmitter } from "node:events";
import type nodeNet from "node:net";
import type nodeDgram from "node:dgram";
export declare class Socket extends EventEmitter implements nodeDgram.Socket {
readonly __unenv__: true;
bind(): this;
close(): this;
ref(): this;
unref(): this;
getRecvBufferSize(): number;
getSendBufferSize(): number;
getSendQueueSize(): number;
getSendQueueCount(): number;
setMulticastLoopback(): boolean;
setMulticastTTL(): number;
setTTL(): number;
address(): nodeNet.AddressInfo;
remoteAddress(): nodeNet.AddressInfo;
[Symbol.asyncDispose]();
addMembership();
addSourceSpecificMembership();
connect();
disconnect();
dropMembership();
dropSourceSpecificMembership();
send();
setSendBufferSize();
setBroadcast();
setRecvBufferSize();
setMulticastInterface();
}

View file

@ -0,0 +1,61 @@
import { EventEmitter } from "node:events";
export class Socket extends EventEmitter {
__unenv__ = true;
bind() {
return this;
}
close() {
return this;
}
ref() {
return this;
}
unref() {
return this;
}
getRecvBufferSize() {
return 1e5;
}
getSendBufferSize() {
return 1e4;
}
getSendQueueSize() {
return 0;
}
getSendQueueCount() {
return 0;
}
setMulticastLoopback() {
return false;
}
setMulticastTTL() {
return 1;
}
setTTL() {
return 1;
}
address() {
return {
address: "127.0.0.1",
family: "IPv4",
port: 1234
};
}
remoteAddress() {
throw new Error("ERR_SOCKET_DGRAM_NOT_CONNECTED");
}
[Symbol.asyncDispose]() {
return Promise.resolve();
}
addMembership() {}
addSourceSpecificMembership() {}
connect() {}
disconnect() {}
dropMembership() {}
dropSourceSpecificMembership() {}
send() {}
setSendBufferSize() {}
setBroadcast() {}
setRecvBufferSize() {}
setMulticastInterface() {}
}

View file

@ -0,0 +1,18 @@
import type nodeDiagnosticsChannel from "node:diagnostics_channel";
export declare const getChannels: unknown;
export declare class Channel<
StoreType,
ContextType
> implements nodeDiagnosticsChannel.Channel<StoreType, ContextType> {
readonly __unenv__: true;
name: nodeDiagnosticsChannel.Channel["name"];
get hasSubscribers();
_subscribers: nodeDiagnosticsChannel.ChannelListener[];
constructor(name: nodeDiagnosticsChannel.Channel["name"]);
subscribe(onMessage: nodeDiagnosticsChannel.ChannelListener);
unsubscribe(onMessage: nodeDiagnosticsChannel.ChannelListener);
publish(message: unknown): void;
bindStore();
unbindStore();
runStores();
}

View file

@ -0,0 +1,40 @@
import { createNotImplementedError } from "../../../_internal/utils.mjs";
const channels = {};
export const getChannels = () => channels;
export class Channel {
__unenv__ = true;
name;
get hasSubscribers() {
return this._subscribers.length > 0;
}
_subscribers;
constructor(name) {
this.name = name;
this._subscribers = [];
const channels = getChannels();
channels[name] = this;
}
subscribe(onMessage) {
this._subscribers.push(onMessage);
}
unsubscribe(onMessage) {
const index = this._subscribers.indexOf(onMessage);
if (index === -1) return false;
this._subscribers.splice(index, 1);
return true;
}
publish(message) {
for (const subscriber of this._subscribers) {
subscriber(message, this.name);
}
}
bindStore() {
throw createNotImplementedError("Channel.bindStore");
}
unbindStore() {
throw createNotImplementedError("Channel.unbindStore");
}
runStores() {
throw createNotImplementedError("Channel.runStores");
}
}

View file

@ -0,0 +1,19 @@
import type nodeDagnosticsChannel from "node:diagnostics_channel";
import { Channel } from "./channel.mjs";
export declare class TracingChannel<
StoreType = unknown,
ContextType extends object = object
> implements nodeDagnosticsChannel.TracingChannel<StoreType, ContextType> {
readonly __unenv__: true;
asyncEnd: Channel<StoreType, ContextType>;
asyncStart: Channel<StoreType, ContextType>;
end: Channel<StoreType, ContextType>;
error: Channel<StoreType, ContextType>;
start: Channel<StoreType, ContextType>;
constructor(nameOrChannels: string | nodeDagnosticsChannel.TracingChannelCollection<StoreType, ContextType>);
subscribe(handlers: nodeDagnosticsChannel.TracingChannelSubscribers<ContextType>): void;
unsubscribe(handlers: nodeDagnosticsChannel.TracingChannelSubscribers<ContextType>): void;
traceSync();
tracePromise();
traceCallback();
}

View file

@ -0,0 +1,48 @@
import { createNotImplementedError } from "../../../_internal/utils.mjs";
import { Channel } from "./channel.mjs";
export class TracingChannel {
__unenv__ = true;
asyncEnd = new Channel("asyncEnd");
asyncStart = new Channel("asyncStart");
end = new Channel("end");
error = new Channel("error");
start = new Channel("start");
constructor(nameOrChannels) {
if (typeof nameOrChannels === "string") {
this.asyncEnd = new Channel(`trace:${nameOrChannels}:asyncEnd`);
this.asyncStart = new Channel(`trace:${nameOrChannels}:asyncStart`);
this.end = new Channel(`trace:${nameOrChannels}:end`);
this.error = new Channel(`trace:${nameOrChannels}:error`);
this.start = new Channel(`trace:${nameOrChannels}:start`);
} else {
this.asyncStart = nameOrChannels.asyncStart;
this.asyncEnd = nameOrChannels.asyncEnd;
this.end = nameOrChannels.end;
this.error = nameOrChannels.error;
this.start = nameOrChannels.start;
}
}
subscribe(handlers) {
this.asyncEnd?.subscribe(handlers.asyncEnd);
this.asyncStart?.subscribe(handlers.asyncStart);
this.end?.subscribe(handlers.end);
this.error?.subscribe(handlers.error);
this.start?.subscribe(handlers.start);
}
unsubscribe(handlers) {
this.asyncEnd?.unsubscribe(handlers.asyncEnd);
this.asyncStart?.unsubscribe(handlers.asyncStart);
this.end?.unsubscribe(handlers.end);
this.error?.unsubscribe(handlers.error);
this.start?.unsubscribe(handlers.start);
}
traceSync() {
throw createNotImplementedError("TracingChannel.traceSync");
}
tracePromise() {
throw createNotImplementedError("TracingChannel.tracePromise");
}
traceCallback() {
throw createNotImplementedError("TracingChannel.traceCallback");
}
}

View file

@ -0,0 +1,28 @@
// npx -y node@22.14 -e 'const dns=require("dns");console.log(Object.entries(dns).filter(e => ["string", "number"].includes(typeof e[1])).map(([k,v]) => `export const ${k} = ${JSON.stringify(v)}`).join("\n"))'
export declare const ADDRCONFIG = 1024;
export declare const ALL = 256;
export declare const V4MAPPED = 2048;
export declare const NODATA = "ENODATA";
export declare const FORMERR = "EFORMERR";
export declare const SERVFAIL = "ESERVFAIL";
export declare const NOTFOUND = "ENOTFOUND";
export declare const NOTIMP = "ENOTIMP";
export declare const REFUSED = "EREFUSED";
export declare const BADQUERY = "EBADQUERY";
export declare const BADNAME = "EBADNAME";
export declare const BADFAMILY = "EBADFAMILY";
export declare const BADRESP = "EBADRESP";
export declare const CONNREFUSED = "ECONNREFUSED";
export declare const TIMEOUT = "ETIMEOUT";
export declare const EOF = "EOF";
export declare const FILE = "EFILE";
export declare const NOMEM = "ENOMEM";
export declare const DESTRUCTION = "EDESTRUCTION";
export declare const BADSTR = "EBADSTR";
export declare const BADFLAGS = "EBADFLAGS";
export declare const NONAME = "ENONAME";
export declare const BADHINTS = "EBADHINTS";
export declare const NOTINITIALIZED = "ENOTINITIALIZED";
export declare const LOADIPHLPAPI = "ELOADIPHLPAPI";
export declare const ADDRGETNETWORKPARAMS = "EADDRGETNETWORKPARAMS";
export declare const CANCELLED = "ECANCELLED";

View file

@ -0,0 +1,28 @@
// npx -y node@22.14 -e 'const dns=require("dns");console.log(Object.entries(dns).filter(e => ["string", "number"].includes(typeof e[1])).map(([k,v]) => `export const ${k} = ${JSON.stringify(v)}`).join("\n"))'
export const ADDRCONFIG = 1024;
export const ALL = 256;
export const V4MAPPED = 2048;
export const NODATA = "ENODATA";
export const FORMERR = "EFORMERR";
export const SERVFAIL = "ESERVFAIL";
export const NOTFOUND = "ENOTFOUND";
export const NOTIMP = "ENOTIMP";
export const REFUSED = "EREFUSED";
export const BADQUERY = "EBADQUERY";
export const BADNAME = "EBADNAME";
export const BADFAMILY = "EBADFAMILY";
export const BADRESP = "EBADRESP";
export const CONNREFUSED = "ECONNREFUSED";
export const TIMEOUT = "ETIMEOUT";
export const EOF = "EOF";
export const FILE = "EFILE";
export const NOMEM = "ENOMEM";
export const DESTRUCTION = "EDESTRUCTION";
export const BADSTR = "EBADSTR";
export const BADFLAGS = "EBADFLAGS";
export const NONAME = "ENONAME";
export const BADHINTS = "EBADHINTS";
export const NOTINITIALIZED = "ENOTINITIALIZED";
export const LOADIPHLPAPI = "ELOADIPHLPAPI";
export const ADDRGETNETWORKPARAMS = "EADDRGETNETWORKPARAMS";
export const CANCELLED = "ECANCELLED";

View file

@ -0,0 +1,13 @@
import { EventEmitter } from "node:events";
import type nodeDomain from "node:domain";
export declare class Domain extends EventEmitter implements nodeDomain.Domain {
readonly __unenv__: true;
members: unknown;
add();
enter();
exit();
remove();
bind<T>(callback: T): T;
intercept<T>(callback: T): T;
run<T>(fn: (...args: any[]) => T, ...args: any[]): T;
}

View file

@ -0,0 +1,19 @@
import { createNotImplementedError } from "../../../_internal/utils.mjs";
import { EventEmitter } from "node:events";
export class Domain extends EventEmitter {
__unenv__ = true;
members = [];
add() {}
enter() {}
exit() {}
remove() {}
bind(callback) {
throw createNotImplementedError("Domain.bind");
}
intercept(callback) {
throw createNotImplementedError("Domain.intercept");
}
run(fn, ...args) {
throw createNotImplementedError("Domain.run");
}
}

View file

@ -0,0 +1,207 @@
// Copyright Joyent, Inc. and other Node 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.
// Based on Node.js EventEmitter implementation
// https://github.com/nodejs/node/blob/26f2cbdd59957e9a33a94ee2e0fdbeb9aadb0be6/lib/events.js
import type nodeEvents from "node:events";
import { EventEmitter as NodeEventEmitter } from "node:events";
// Types
type Listener = (...args: any[]) => void;
// ----------------------------------------------------------------------------
// EventEmitter
// ----------------------------------------------------------------------------
export declare class _EventEmitter implements NodeEventEmitter {
// Internal state
_events: any;
_eventsCount: number;
_maxListeners: number | undefined;
// Symbols
static captureRejectionSymbol;
static errorMonitor;
static kMaxEventTargetListeners;
static kMaxEventTargetListenersWarned;
// Static utils
static usingDomains: boolean;
static get on();
static get once();
static get getEventListeners();
static get getMaxListeners();
static get addAbortListener();
static get EventEmitterAsyncResource();
static get EventEmitter();
static setMaxListeners(n?, ...eventTargets: (_EventEmitter | EventTarget)[]);
static listenerCount(emitter: NodeEventEmitter, type: string);
static init();
static get captureRejections();
static set captureRejections(value);
static get defaultMaxListeners();
static set defaultMaxListeners(arg);
// Constructor
constructor(opts?: any);
/**
* Increases the max listeners of the event emitter.
* @param {number} n
* @returns {EventEmitter}
*/
setMaxListeners(n: number);
/**
* Returns the current max listener value for the event emitter.
* @returns {number}
*/
getMaxListeners();
/**
* Synchronously calls each of the listeners registered
* for the event.
* @param {...any} [args]
* @returns {boolean}
*/
emit(type: string | symbol, ...args: any[]);
/**
* Adds a listener to the event emitter.
* @returns {EventEmitter}
*/
addListener(type: string | symbol, listener: Listener);
on(type: string | symbol, listener: Listener);
/**
* Adds the `listener` function to the beginning of
* the listeners array.
*/
prependListener(type: string | symbol, listener: Listener);
/**
* Adds a one-time `listener` function to the event emitter.
*/
once(type: string | symbol, listener: Listener);
/**
* Adds a one-time `listener` function to the beginning of
* the listeners array.
*/
prependOnceListener(type: string | symbol, listener: Listener);
/**
* Removes the specified `listener` from the listeners array.
* @param {string | symbol} type
* @param {Function} listener
* @returns {EventEmitter}
*/
removeListener(type: string | symbol, listener: Listener);
off(type: string | symbol, listener: Listener);
/**
* Removes all listeners from the event emitter. (Only
* removes listeners for a specific event name if specified
* as `type`).
*/
removeAllListeners(type?: string | symbol);
/**
* Returns a copy of the array of listeners for the event name
* specified as `type`.
* @param {string | symbol} type
* @returns {Function[]}
*/
listeners(type: string | symbol);
/**
* Returns a copy of the array of listeners and wrappers for
* the event name specified as `type`.
* @returns {Function[]}
*/
rawListeners(type: string | symbol);
/**
* Returns an array listing the events for which
* the emitter has registered listeners.
* @returns {any[]}
*/
eventNames();
/**
* Returns the number of listeners listening to event name
*/
listenerCount(eventName: string | symbol, listener?: Listener): number;
}
// ----------------------------------------------------------------------------
// EventEmitterAsyncResource
// ----------------------------------------------------------------------------
export declare class EventEmitterAsyncResource extends _EventEmitter {
/**
* @param {{
* name?: string,
* triggerAsyncId?: number,
* requireManualDestroy?: boolean,
* }} [options]
*/
constructor(options: any);
/**
* @param {symbol,string} event
* @param {...any} args
* @returns {boolean}
*/
emit(event: string | symbol, ...args: any[]): boolean;
/**
* @returns {void}
*/
emitDestroy();
/**
* @type {number}
*/
get asyncId();
/**
* @type {number}
*/
get triggerAsyncId();
/**
* @type {EventEmitterReferencingAsyncResource}
*/
get asyncResource();
}
// ----------------------------------------------------------------------------
// Exported utils
// ----------------------------------------------------------------------------
/**
* Returns an `AsyncIterator` that iterates `event` events.
* @param {EventEmitter} emitter
* @param {string | symbol} event
* @param {{
* signal: AbortSignal;
* close?: string[];
* highWaterMark?: number,
* lowWaterMark?: number
* }} [options]
* @returns {AsyncIterator}
*/
export declare const on: typeof nodeEvents.on;
/**
* Creates a `Promise` that is fulfilled when the emitter
* emits the given event.
* @param {EventEmitter} emitter
* @param {string} name
* @param {{ signal: AbortSignal; }} [options]
* @returns {Promise}
*/
export declare const once: typeof nodeEvents.once;
export declare const addAbortListener: typeof nodeEvents.addAbortListener;
/**
* Returns a copy of the array of listeners for the event name
* specified as `type`.
* @returns {Function[]}
*/
export declare const getEventListeners: typeof nodeEvents.getEventListeners;
/**
* Returns the max listeners set.
* @param {EventEmitter | EventTarget} emitterOrTarget
* @returns {number}
*/
export declare const getMaxListeners: typeof nodeEvents.getMaxListeners;
export {};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,8 @@
import type nodeFs from "node:fs";
export declare const Dir: typeof nodeFs.Dir;
export declare const Dirent: typeof nodeFs.Dirent;
export declare const Stats: typeof nodeFs.Stats;
export declare const ReadStream: typeof nodeFs.ReadStream;
export declare const WriteStream: typeof nodeFs.WriteStream;
export declare const FileReadStream: unknown;
export declare const FileWriteStream: unknown;

View file

@ -0,0 +1,8 @@
import { notImplementedClass } from "../../../_internal/utils.mjs";
export const Dir = /* @__PURE__ */ notImplementedClass("fs.Dir");
export const Dirent = /* @__PURE__ */ notImplementedClass("fs.Dirent");
export const Stats = /* @__PURE__ */ notImplementedClass("fs.Stats");
export const ReadStream = /* @__PURE__ */ notImplementedClass("fs.ReadStream");
export const WriteStream = /* @__PURE__ */ notImplementedClass("fs.WriteStream");
export const FileReadStream = ReadStream;
export const FileWriteStream = WriteStream;

View file

@ -0,0 +1,59 @@
// npx -y node@22.14 -e 'const{constants}=require("fs");console.log(Object.entries(constants).map(([k,v]) => `export const ${k} = ${JSON.stringify(v)}`).join("\n"))'
export declare const UV_FS_SYMLINK_DIR = 1;
export declare const UV_FS_SYMLINK_JUNCTION = 2;
export declare const O_RDONLY = 0;
export declare const O_WRONLY = 1;
export declare const O_RDWR = 2;
export declare const UV_DIRENT_UNKNOWN = 0;
export declare const UV_DIRENT_FILE = 1;
export declare const UV_DIRENT_DIR = 2;
export declare const UV_DIRENT_LINK = 3;
export declare const UV_DIRENT_FIFO = 4;
export declare const UV_DIRENT_SOCKET = 5;
export declare const UV_DIRENT_CHAR = 6;
export declare const UV_DIRENT_BLOCK = 7;
export declare const EXTENSIONLESS_FORMAT_JAVASCRIPT = 0;
export declare const EXTENSIONLESS_FORMAT_WASM = 1;
export declare const S_IFMT = 61440;
export declare const S_IFREG = 32768;
export declare const S_IFDIR = 16384;
export declare const S_IFCHR = 8192;
export declare const S_IFBLK = 24576;
export declare const S_IFIFO = 4096;
export declare const S_IFLNK = 40960;
export declare const S_IFSOCK = 49152;
export declare const O_CREAT = 64;
export declare const O_EXCL = 128;
export declare const UV_FS_O_FILEMAP = 0;
export declare const O_NOCTTY = 256;
export declare const O_TRUNC = 512;
export declare const O_APPEND = 1024;
export declare const O_DIRECTORY = 65536;
export declare const O_NOATIME = 262144;
export declare const O_NOFOLLOW = 131072;
export declare const O_SYNC = 1052672;
export declare const O_DSYNC = 4096;
export declare const O_DIRECT = 16384;
export declare const O_NONBLOCK = 2048;
export declare const S_IRWXU = 448;
export declare const S_IRUSR = 256;
export declare const S_IWUSR = 128;
export declare const S_IXUSR = 64;
export declare const S_IRWXG = 56;
export declare const S_IRGRP = 32;
export declare const S_IWGRP = 16;
export declare const S_IXGRP = 8;
export declare const S_IRWXO = 7;
export declare const S_IROTH = 4;
export declare const S_IWOTH = 2;
export declare const S_IXOTH = 1;
export declare const F_OK = 0;
export declare const R_OK = 4;
export declare const W_OK = 2;
export declare const X_OK = 1;
export declare const UV_FS_COPYFILE_EXCL = 1;
export declare const COPYFILE_EXCL = 1;
export declare const UV_FS_COPYFILE_FICLONE = 2;
export declare const COPYFILE_FICLONE = 2;
export declare const UV_FS_COPYFILE_FICLONE_FORCE = 4;
export declare const COPYFILE_FICLONE_FORCE = 4;

View file

@ -0,0 +1,59 @@
// npx -y node@22.14 -e 'const{constants}=require("fs");console.log(Object.entries(constants).map(([k,v]) => `export const ${k} = ${JSON.stringify(v)}`).join("\n"))'
export const UV_FS_SYMLINK_DIR = 1;
export const UV_FS_SYMLINK_JUNCTION = 2;
export const O_RDONLY = 0;
export const O_WRONLY = 1;
export const O_RDWR = 2;
export const UV_DIRENT_UNKNOWN = 0;
export const UV_DIRENT_FILE = 1;
export const UV_DIRENT_DIR = 2;
export const UV_DIRENT_LINK = 3;
export const UV_DIRENT_FIFO = 4;
export const UV_DIRENT_SOCKET = 5;
export const UV_DIRENT_CHAR = 6;
export const UV_DIRENT_BLOCK = 7;
export const EXTENSIONLESS_FORMAT_JAVASCRIPT = 0;
export const EXTENSIONLESS_FORMAT_WASM = 1;
export const S_IFMT = 61440;
export const S_IFREG = 32768;
export const S_IFDIR = 16384;
export const S_IFCHR = 8192;
export const S_IFBLK = 24576;
export const S_IFIFO = 4096;
export const S_IFLNK = 40960;
export const S_IFSOCK = 49152;
export const O_CREAT = 64;
export const O_EXCL = 128;
export const UV_FS_O_FILEMAP = 0;
export const O_NOCTTY = 256;
export const O_TRUNC = 512;
export const O_APPEND = 1024;
export const O_DIRECTORY = 65536;
export const O_NOATIME = 262144;
export const O_NOFOLLOW = 131072;
export const O_SYNC = 1052672;
export const O_DSYNC = 4096;
export const O_DIRECT = 16384;
export const O_NONBLOCK = 2048;
export const S_IRWXU = 448;
export const S_IRUSR = 256;
export const S_IWUSR = 128;
export const S_IXUSR = 64;
export const S_IRWXG = 56;
export const S_IRGRP = 32;
export const S_IWGRP = 16;
export const S_IXGRP = 8;
export const S_IRWXO = 7;
export const S_IROTH = 4;
export const S_IWOTH = 2;
export const S_IXOTH = 1;
export const F_OK = 0;
export const R_OK = 4;
export const W_OK = 2;
export const X_OK = 1;
export const UV_FS_COPYFILE_EXCL = 1;
export const COPYFILE_EXCL = 1;
export const UV_FS_COPYFILE_FICLONE = 2;
export const COPYFILE_FICLONE = 2;
export const UV_FS_COPYFILE_FICLONE_FORCE = 4;
export const COPYFILE_FICLONE_FORCE = 4;

View file

@ -0,0 +1,96 @@
import type nodeFs from "node:fs";
// Async
export declare const access: typeof nodeFs.access;
export declare const appendFile: typeof nodeFs.appendFile;
export declare const chown: typeof nodeFs.chown;
export declare const chmod: typeof nodeFs.chmod;
export declare const copyFile: typeof nodeFs.copyFile;
export declare const cp: typeof nodeFs.cp;
export declare const lchown: typeof nodeFs.lchown;
export declare const lchmod: typeof nodeFs.lchmod;
export declare const link: typeof nodeFs.link;
export declare const lstat: typeof nodeFs.lstat;
export declare const lutimes: typeof nodeFs.lutimes;
export declare const mkdir: typeof nodeFs.mkdir;
export declare const mkdtemp: typeof nodeFs.mkdtemp;
export declare const realpath: typeof nodeFs.realpath;
export declare const open: typeof nodeFs.open;
export declare const opendir: typeof nodeFs.opendir;
export declare const readdir: typeof nodeFs.readdir;
export declare const readFile: typeof nodeFs.readFile;
export declare const readlink: typeof nodeFs.readlink;
export declare const rename: typeof nodeFs.rename;
export declare const rm: typeof nodeFs.rm;
export declare const rmdir: typeof nodeFs.rmdir;
export declare const stat: typeof nodeFs.stat;
export declare const symlink: typeof nodeFs.symlink;
export declare const truncate: typeof nodeFs.truncate;
export declare const unlink: typeof nodeFs.unlink;
export declare const utimes: typeof nodeFs.utimes;
export declare const writeFile: typeof nodeFs.writeFile;
export declare const statfs: typeof nodeFs.statfs;
export declare const close: typeof nodeFs.close;
export declare const createReadStream: typeof nodeFs.createReadStream;
export declare const createWriteStream: typeof nodeFs.createWriteStream;
export declare const exists: typeof nodeFs.exists;
export declare const fchown: typeof nodeFs.fchown;
export declare const fchmod: typeof nodeFs.fchmod;
export declare const fdatasync: typeof nodeFs.fdatasync;
export declare const fstat: typeof nodeFs.fstat;
export declare const fsync: typeof nodeFs.fsync;
export declare const ftruncate: typeof nodeFs.ftruncate;
export declare const futimes: typeof nodeFs.futimes;
export declare const lstatSync: typeof nodeFs.lstatSync;
export declare const read: typeof nodeFs.read;
export declare const readv: typeof nodeFs.readv;
export declare const realpathSync: typeof nodeFs.realpathSync;
export declare const statSync: typeof nodeFs.statSync;
export declare const unwatchFile: typeof nodeFs.unwatchFile;
export declare const watch: typeof nodeFs.watch;
export declare const watchFile: typeof nodeFs.watchFile;
export declare const write: typeof nodeFs.write;
export declare const writev: typeof nodeFs.writev;
export declare const _toUnixTimestamp: unknown;
export declare const openAsBlob: typeof nodeFs.openAsBlob;
export declare const glob: typeof nodeFs.glob;
// Sync
export declare const appendFileSync: unknown;
export declare const accessSync: unknown;
export declare const chownSync: unknown;
export declare const chmodSync: unknown;
export declare const closeSync: unknown;
export declare const copyFileSync: unknown;
export declare const cpSync: unknown;
export declare const existsSync: typeof nodeFs.existsSync;
export declare const fchownSync: unknown;
export declare const fchmodSync: unknown;
export declare const fdatasyncSync: unknown;
export declare const fstatSync: typeof nodeFs.fstatSync;
export declare const fsyncSync: unknown;
export declare const ftruncateSync: unknown;
export declare const futimesSync: unknown;
export declare const lchownSync: unknown;
export declare const lchmodSync: unknown;
export declare const linkSync: unknown;
export declare const lutimesSync: unknown;
export declare const mkdirSync: unknown;
export declare const mkdtempSync: typeof nodeFs.mkdtempSync;
export declare const openSync: unknown;
export declare const opendirSync: unknown;
export declare const readdirSync: typeof nodeFs.readdirSync;
export declare const readSync: unknown;
export declare const readvSync: unknown;
export declare const readFileSync: typeof nodeFs.readFileSync;
export declare const readlinkSync: typeof nodeFs.readlinkSync;
export declare const renameSync: unknown;
export declare const rmSync: unknown;
export declare const rmdirSync: unknown;
export declare const symlinkSync: unknown;
export declare const truncateSync: unknown;
export declare const unlinkSync: unknown;
export declare const utimesSync: unknown;
export declare const writeFileSync: unknown;
export declare const writeSync: unknown;
export declare const writevSync: unknown;
export declare const statfsSync: typeof nodeFs.statfsSync;
export declare const globSync: unknown;

View file

@ -0,0 +1,106 @@
import { notImplemented, notImplementedAsync } from "../../../_internal/utils.mjs";
import * as fsp from "./promises.mjs";
function callbackify(fn) {
const fnc = function(...args) {
const cb = args.pop();
fn().catch((error) => cb(error)).then((val) => cb(undefined, val));
};
fnc.__promisify__ = fn;
fnc.native = fnc;
return fnc;
}
// Async
export const access = callbackify(fsp.access);
export const appendFile = callbackify(fsp.appendFile);
export const chown = callbackify(fsp.chown);
export const chmod = callbackify(fsp.chmod);
export const copyFile = callbackify(fsp.copyFile);
export const cp = callbackify(fsp.cp);
export const lchown = callbackify(fsp.lchown);
export const lchmod = callbackify(fsp.lchmod);
export const link = callbackify(fsp.link);
export const lstat = callbackify(fsp.lstat);
export const lutimes = callbackify(fsp.lutimes);
export const mkdir = callbackify(fsp.mkdir);
export const mkdtemp = callbackify(fsp.mkdtemp);
export const realpath = callbackify(fsp.realpath);
export const open = callbackify(fsp.open);
export const opendir = callbackify(fsp.opendir);
export const readdir = callbackify(fsp.readdir);
export const readFile = callbackify(fsp.readFile);
export const readlink = callbackify(fsp.readlink);
export const rename = callbackify(fsp.rename);
export const rm = callbackify(fsp.rm);
export const rmdir = callbackify(fsp.rmdir);
export const stat = callbackify(fsp.stat);
export const symlink = callbackify(fsp.symlink);
export const truncate = callbackify(fsp.truncate);
export const unlink = callbackify(fsp.unlink);
export const utimes = callbackify(fsp.utimes);
export const writeFile = callbackify(fsp.writeFile);
export const statfs = callbackify(fsp.statfs);
export const close = /* @__PURE__ */ notImplementedAsync("fs.close");
export const createReadStream = /* @__PURE__ */ notImplementedAsync("fs.createReadStream");
export const createWriteStream = /* @__PURE__ */ notImplementedAsync("fs.createWriteStream");
export const exists = /* @__PURE__ */ notImplementedAsync("fs.exists");
export const fchown = /* @__PURE__ */ notImplementedAsync("fs.fchown");
export const fchmod = /* @__PURE__ */ notImplementedAsync("fs.fchmod");
export const fdatasync = /* @__PURE__ */ notImplementedAsync("fs.fdatasync");
export const fstat = /* @__PURE__ */ notImplementedAsync("fs.fstat");
export const fsync = /* @__PURE__ */ notImplementedAsync("fs.fsync");
export const ftruncate = /* @__PURE__ */ notImplementedAsync("fs.ftruncate");
export const futimes = /* @__PURE__ */ notImplementedAsync("fs.futimes");
export const lstatSync = /* @__PURE__ */ notImplementedAsync("fs.lstatSync");
export const read = /* @__PURE__ */ notImplementedAsync("fs.read");
export const readv = /* @__PURE__ */ notImplementedAsync("fs.readv");
export const realpathSync = /* @__PURE__ */ notImplementedAsync("fs.realpathSync");
export const statSync = /* @__PURE__ */ notImplementedAsync("fs.statSync");
export const unwatchFile = /* @__PURE__ */ notImplementedAsync("fs.unwatchFile");
export const watch = /* @__PURE__ */ notImplementedAsync("fs.watch");
export const watchFile = /* @__PURE__ */ notImplementedAsync("fs.watchFile");
export const write = /* @__PURE__ */ notImplementedAsync("fs.write");
export const writev = /* @__PURE__ */ notImplementedAsync("fs.writev");
export const _toUnixTimestamp = /* @__PURE__ */ notImplementedAsync("fs._toUnixTimestamp");
export const openAsBlob = /* @__PURE__ */ notImplementedAsync("fs.openAsBlob");
export const glob = /* @__PURE__ */ notImplementedAsync("fs.glob");
// Sync
export const appendFileSync = /* @__PURE__ */ notImplemented("fs.appendFileSync");
export const accessSync = /* @__PURE__ */ notImplemented("fs.accessSync");
export const chownSync = /* @__PURE__ */ notImplemented("fs.chownSync");
export const chmodSync = /* @__PURE__ */ notImplemented("fs.chmodSync");
export const closeSync = /* @__PURE__ */ notImplemented("fs.closeSync");
export const copyFileSync = /* @__PURE__ */ notImplemented("fs.copyFileSync");
export const cpSync = /* @__PURE__ */ notImplemented("fs.cpSync");
export const existsSync = () => false;
export const fchownSync = /* @__PURE__ */ notImplemented("fs.fchownSync");
export const fchmodSync = /* @__PURE__ */ notImplemented("fs.fchmodSync");
export const fdatasyncSync = /* @__PURE__ */ notImplemented("fs.fdatasyncSync");
export const fstatSync = /* @__PURE__ */ notImplemented("fs.fstatSync");
export const fsyncSync = /* @__PURE__ */ notImplemented("fs.fsyncSync");
export const ftruncateSync = /* @__PURE__ */ notImplemented("fs.ftruncateSync");
export const futimesSync = /* @__PURE__ */ notImplemented("fs.futimesSync");
export const lchownSync = /* @__PURE__ */ notImplemented("fs.lchownSync");
export const lchmodSync = /* @__PURE__ */ notImplemented("fs.lchmodSync");
export const linkSync = /* @__PURE__ */ notImplemented("fs.linkSync");
export const lutimesSync = /* @__PURE__ */ notImplemented("fs.lutimesSync");
export const mkdirSync = /* @__PURE__ */ notImplemented("fs.mkdirSync");
export const mkdtempSync = /* @__PURE__ */ notImplemented("fs.mkdtempSync");
export const openSync = /* @__PURE__ */ notImplemented("fs.openSync");
export const opendirSync = /* @__PURE__ */ notImplemented("fs.opendirSync");
export const readdirSync = /* @__PURE__ */ notImplemented("fs.readdirSync");
export const readSync = /* @__PURE__ */ notImplemented("fs.readSync");
export const readvSync = /* @__PURE__ */ notImplemented("fs.readvSync");
export const readFileSync = /* @__PURE__ */ notImplemented("fs.readFileSync");
export const readlinkSync = /* @__PURE__ */ notImplemented("fs.readlinkSync");
export const renameSync = /* @__PURE__ */ notImplemented("fs.renameSync");
export const rmSync = /* @__PURE__ */ notImplemented("fs.rmSync");
export const rmdirSync = /* @__PURE__ */ notImplemented("fs.rmdirSync");
export const symlinkSync = /* @__PURE__ */ notImplemented("fs.symlinkSync");
export const truncateSync = /* @__PURE__ */ notImplemented("fs.truncateSync");
export const unlinkSync = /* @__PURE__ */ notImplemented("fs.unlinkSync");
export const utimesSync = /* @__PURE__ */ notImplemented("fs.utimesSync");
export const writeFileSync = /* @__PURE__ */ notImplemented("fs.writeFileSync");
export const writeSync = /* @__PURE__ */ notImplemented("fs.writeSync");
export const writevSync = /* @__PURE__ */ notImplemented("fs.writevSync");
export const statfsSync = /* @__PURE__ */ notImplemented("fs.statfsSync");
export const globSync = /* @__PURE__ */ notImplemented("fs.globSync");

View file

@ -0,0 +1,32 @@
import type nodeFsPromises from "node:fs/promises";
export declare const access: unknown;
export declare const copyFile: unknown;
export declare const cp: unknown;
export declare const open: unknown;
export declare const opendir: unknown;
export declare const rename: unknown;
export declare const truncate: unknown;
export declare const rm: unknown;
export declare const rmdir: unknown;
export declare const mkdir: typeof nodeFsPromises.mkdir;
export declare const readdir: typeof nodeFsPromises.readdir;
export declare const readlink: typeof nodeFsPromises.readlink;
export declare const symlink: unknown;
export declare const lstat: typeof nodeFsPromises.lstat;
export declare const stat: typeof nodeFsPromises.stat;
export declare const link: unknown;
export declare const unlink: unknown;
export declare const chmod: unknown;
export declare const lchmod: unknown;
export declare const lchown: unknown;
export declare const chown: unknown;
export declare const utimes: unknown;
export declare const lutimes: unknown;
export declare const realpath: typeof nodeFsPromises.realpath;
export declare const mkdtemp: typeof nodeFsPromises.mkdtemp;
export declare const writeFile: unknown;
export declare const appendFile: unknown;
export declare const readFile: typeof nodeFsPromises.readFile;
export declare const watch: typeof nodeFsPromises.watch;
export declare const statfs: typeof nodeFsPromises.statfs;
export declare const glob: unknown;

View file

@ -0,0 +1,32 @@
import { notImplemented } from "../../../_internal/utils.mjs";
export const access = /* @__PURE__ */ notImplemented("fs.access");
export const copyFile = /* @__PURE__ */ notImplemented("fs.copyFile");
export const cp = /* @__PURE__ */ notImplemented("fs.cp");
export const open = /* @__PURE__ */ notImplemented("fs.open");
export const opendir = /* @__PURE__ */ notImplemented("fs.opendir");
export const rename = /* @__PURE__ */ notImplemented("fs.rename");
export const truncate = /* @__PURE__ */ notImplemented("fs.truncate");
export const rm = /* @__PURE__ */ notImplemented("fs.rm");
export const rmdir = /* @__PURE__ */ notImplemented("fs.rmdir");
export const mkdir = /* @__PURE__ */ notImplemented("fs.mkdir");
export const readdir = /* @__PURE__ */ notImplemented("fs.readdir");
export const readlink = /* @__PURE__ */ notImplemented("fs.readlink");
export const symlink = /* @__PURE__ */ notImplemented("fs.symlink");
export const lstat = /* @__PURE__ */ notImplemented("fs.lstat");
export const stat = /* @__PURE__ */ notImplemented("fs.stat");
export const link = /* @__PURE__ */ notImplemented("fs.link");
export const unlink = /* @__PURE__ */ notImplemented("fs.unlink");
export const chmod = /* @__PURE__ */ notImplemented("fs.chmod");
export const lchmod = /* @__PURE__ */ notImplemented("fs.lchmod");
export const lchown = /* @__PURE__ */ notImplemented("fs.lchown");
export const chown = /* @__PURE__ */ notImplemented("fs.chown");
export const utimes = /* @__PURE__ */ notImplemented("fs.utimes");
export const lutimes = /* @__PURE__ */ notImplemented("fs.lutimes");
export const realpath = /* @__PURE__ */ notImplemented("fs.realpath");
export const mkdtemp = /* @__PURE__ */ notImplemented("fs.mkdtemp");
export const writeFile = /* @__PURE__ */ notImplemented("fs.writeFile");
export const appendFile = /* @__PURE__ */ notImplemented("fs.appendFile");
export const readFile = /* @__PURE__ */ notImplemented("fs.readFile");
export const watch = /* @__PURE__ */ notImplemented("fs.watch");
export const statfs = /* @__PURE__ */ notImplemented("fs.statfs");
export const glob = /* @__PURE__ */ notImplemented("fs.glob");

View file

@ -0,0 +1,14 @@
import type nodeHttp from "node:http";
import { EventEmitter } from "node:events";
export declare class Agent extends EventEmitter implements nodeHttp.Agent {
__unenv__: {};
maxFreeSockets: number;
maxSockets: number;
maxTotalSockets: number;
readonly freeSockets: {};
readonly sockets: {};
readonly requests: {};
readonly options: nodeHttp.AgentOptions;
constructor(opts?: nodeHttp.AgentOptions);
destroy(): void;
}

View file

@ -0,0 +1,16 @@
import { EventEmitter } from "node:events";
export class Agent extends EventEmitter {
__unenv__ = {};
maxFreeSockets = 256;
maxSockets = Infinity;
maxTotalSockets = Infinity;
freeSockets = {};
sockets = {};
requests = {};
options;
constructor(opts = {}) {
super();
this.options = opts;
}
destroy() {}
}

View file

@ -0,0 +1,67 @@
export declare const METHODS: unknown;
export declare const STATUS_CODES: {
100: string;
101: string;
102: string;
103: string;
200: string;
201: string;
202: string;
203: string;
204: string;
205: string;
206: string;
207: string;
208: string;
226: string;
300: string;
301: string;
302: string;
303: string;
304: string;
305: string;
307: string;
308: string;
400: string;
401: string;
402: string;
403: string;
404: string;
405: string;
406: string;
407: string;
408: string;
409: string;
410: string;
411: string;
412: string;
413: string;
414: string;
415: string;
416: string;
417: string;
418: string;
421: string;
422: string;
423: string;
424: string;
425: string;
426: string;
428: string;
429: string;
431: string;
451: string;
500: string;
501: string;
502: string;
503: string;
504: string;
505: string;
506: string;
507: string;
508: string;
509: string;
510: string;
511: string;
};
export declare const maxHeaderSize = 16384;

View file

@ -0,0 +1,103 @@
export const METHODS = [
"ACL",
"BIND",
"CHECKOUT",
"CONNECT",
"COPY",
"DELETE",
"GET",
"HEAD",
"LINK",
"LOCK",
"M-SEARCH",
"MERGE",
"MKACTIVITY",
"MKCALENDAR",
"MKCOL",
"MOVE",
"NOTIFY",
"OPTIONS",
"PATCH",
"POST",
"PRI",
"PROPFIND",
"PROPPATCH",
"PURGE",
"PUT",
"REBIND",
"REPORT",
"SEARCH",
"SOURCE",
"SUBSCRIBE",
"TRACE",
"UNBIND",
"UNLINK",
"UNLOCK",
"UNSUBSCRIBE"
];
export const STATUS_CODES = {
100: "Continue",
101: "Switching Protocols",
102: "Processing",
103: "Early Hints",
200: "OK",
201: "Created",
202: "Accepted",
203: "Non-Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
207: "Multi-Status",
208: "Already Reported",
226: "IM Used",
300: "Multiple Choices",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
307: "Temporary Redirect",
308: "Permanent Redirect",
400: "Bad Request",
401: "Unauthorized",
402: "Payment Required",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Payload Too Large",
414: "URI Too Long",
415: "Unsupported Media Type",
416: "Range Not Satisfiable",
417: "Expectation Failed",
418: "I'm a Teapot",
421: "Misdirected Request",
422: "Unprocessable Entity",
423: "Locked",
424: "Failed Dependency",
425: "Too Early",
426: "Upgrade Required",
428: "Precondition Required",
429: "Too Many Requests",
431: "Request Header Fields Too Large",
451: "Unavailable For Legal Reasons",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported",
506: "Variant Also Negotiates",
507: "Insufficient Storage",
508: "Loop Detected",
509: "Bandwidth Limit Exceeded",
510: "Not Extended",
511: "Network Authentication Required"
};
export const maxHeaderSize = 16384;

View file

@ -0,0 +1,31 @@
import type NodeHttp from "node:http";
import { Socket } from "node:net";
import { Readable } from "node:stream";
// Docs: https://nodejs.org/api/http.html#http_class_http_incomingmessage
// Implementation: https://github.com/nodejs/node/blob/master/lib/_http_incoming.js
export declare class IncomingMessage extends Readable implements NodeHttp.IncomingMessage {
__unenv__: {};
aborted: boolean;
httpVersion: string;
httpVersionMajor: number;
httpVersionMinor: number;
complete: boolean;
connection: Socket;
socket: Socket;
headers: NodeHttp.IncomingHttpHeaders;
trailers: {};
method: string;
url: string;
statusCode: number;
statusMessage: string;
closed: boolean;
errored: Error | null;
readable: boolean;
constructor(socket?: Socket);
get rawHeaders();
get rawTrailers(): unknown;
setTimeout(_msecs: number, _callback?: () => void);
get headersDistinct();
get trailersDistinct();
_read();
}

View file

@ -0,0 +1,53 @@
import { Socket } from "node:net";
import { Readable } from "node:stream";
import { rawHeaders } from "../../../_internal/utils.mjs";
// Docs: https://nodejs.org/api/http.html#http_class_http_incomingmessage
// Implementation: https://github.com/nodejs/node/blob/master/lib/_http_incoming.js
export class IncomingMessage extends Readable {
__unenv__ = {};
aborted = false;
httpVersion = "1.1";
httpVersionMajor = 1;
httpVersionMinor = 1;
complete = true;
connection;
socket;
headers = {};
trailers = {};
method = "GET";
url = "/";
statusCode = 200;
statusMessage = "";
closed = false;
errored = null;
readable = false;
constructor(socket) {
super();
this.socket = this.connection = socket || new Socket();
}
get rawHeaders() {
return rawHeaders(this.headers);
}
get rawTrailers() {
return [];
}
setTimeout(_msecs, _callback) {
return this;
}
get headersDistinct() {
return _distinct(this.headers);
}
get trailersDistinct() {
return _distinct(this.trailers);
}
_read() {}
}
function _distinct(obj) {
const d = {};
for (const [key, value] of Object.entries(obj)) {
if (key) {
d[key] = (Array.isArray(value) ? value : [value]).filter(Boolean);
}
}
return d;
}

View file

@ -0,0 +1,42 @@
import type nodeHttp from "node:http";
import type { Socket } from "node:net";
import type { Callback } from "../../../_internal/types.mjs";
import { Writable } from "node:stream";
// Docs: https://nodejs.org/api/http.html#http_class_http_serverresponse
// Implementation: https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js
export declare class ServerResponse extends Writable implements nodeHttp.ServerResponse {
readonly __unenv__: true;
statusCode: number;
statusMessage: string;
upgrading: boolean;
chunkedEncoding: boolean;
shouldKeepAlive: boolean;
useChunkedEncodingByDefault: boolean;
sendDate: boolean;
finished: boolean;
headersSent: boolean;
strictContentLength: boolean;
connection: Socket | null;
socket: Socket | null;
req: nodeHttp.IncomingMessage;
_headers: Record<string, number | string | string[] | undefined>;
constructor(req: nodeHttp.IncomingMessage);
assignSocket(socket: Socket): void;
_flush();
detachSocket(_socket: Socket): void;
writeContinue(_callback?: Callback): void;
writeHead(statusCode: number, arg1?: string | nodeHttp.OutgoingHttpHeaders | nodeHttp.OutgoingHttpHeader[], arg2?: nodeHttp.OutgoingHttpHeaders | nodeHttp.OutgoingHttpHeader[]);
writeProcessing(): void;
setTimeout(_msecs: number, _callback?: Callback): this;
appendHeader(name: string, value: string | string[]);
setHeader(name: string, value: number | string | readonly string[]): this;
setHeaders(headers: Headers | Map<string, number | string | readonly string[]>): this;
getHeader(name: string): number | string | string[] | undefined;
getHeaders(): nodeHttp.OutgoingHttpHeaders;
getHeaderNames(): string[];
hasHeader(name: string): boolean;
removeHeader(name: string): void;
addTrailers(_headers: nodeHttp.OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void;
flushHeaders(): void;
writeEarlyHints(_headers: nodeHttp.OutgoingHttpHeaders, cb: () => void): void;
}

View file

@ -0,0 +1,101 @@
import { Writable } from "node:stream";
// Docs: https://nodejs.org/api/http.html#http_class_http_serverresponse
// Implementation: https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js
export class ServerResponse extends Writable {
__unenv__ = true;
statusCode = 200;
statusMessage = "";
upgrading = false;
chunkedEncoding = false;
shouldKeepAlive = false;
useChunkedEncodingByDefault = false;
sendDate = false;
finished = false;
headersSent = false;
strictContentLength = false;
connection = null;
socket = null;
req;
_headers = {};
constructor(req) {
super();
this.req = req;
}
assignSocket(socket) {
// @ts-ignore
socket._httpMessage = this;
// socket.on('close', onServerResponseClose)
this.socket = socket;
this.connection = socket;
this.emit("socket", socket);
this._flush();
}
_flush() {
this.flushHeaders();
}
detachSocket(_socket) {}
writeContinue(_callback) {}
writeHead(statusCode, arg1, arg2) {
if (statusCode) {
this.statusCode = statusCode;
}
if (typeof arg1 === "string") {
this.statusMessage = arg1;
arg1 = undefined;
}
const headers = arg2 || arg1;
if (headers) {
if (Array.isArray(headers)) {} else {
for (const key in headers) {
// @ts-ignore
this.setHeader(key, headers[key]);
}
}
}
this.headersSent = true;
return this;
}
writeProcessing() {}
setTimeout(_msecs, _callback) {
return this;
}
appendHeader(name, value) {
name = name.toLowerCase();
const current = this._headers[name];
const all = [...Array.isArray(current) ? current : [current], ...Array.isArray(value) ? value : [value]].filter(Boolean);
this._headers[name] = all.length > 1 ? all : all[0];
return this;
}
setHeader(name, value) {
this._headers[name.toLowerCase()] = Array.isArray(value) ? [...value] : value;
return this;
}
setHeaders(headers) {
for (const [key, value] of headers.entries()) {
this.setHeader(key, value);
}
return this;
}
getHeader(name) {
return this._headers[name.toLowerCase()];
}
getHeaders() {
return this._headers;
}
getHeaderNames() {
return Object.keys(this._headers);
}
hasHeader(name) {
return name.toLowerCase() in this._headers;
}
removeHeader(name) {
delete this._headers[name.toLowerCase()];
}
addTrailers(_headers) {}
flushHeaders() {}
writeEarlyHints(_headers, cb) {
if (typeof cb === "function") {
cb();
}
}
}

View file

@ -0,0 +1,241 @@
// npx -y node@22.14 -e 'const{constants}=require("http2");console.log(Object.entries(constants).map(([k,v]) => `export const ${k} = ${JSON.stringify(v)}`).join("\n"))'
export declare const NGHTTP2_ERR_FRAME_SIZE_ERROR = -522;
export declare const NGHTTP2_SESSION_SERVER = 0;
export declare const NGHTTP2_SESSION_CLIENT = 1;
export declare const NGHTTP2_STREAM_STATE_IDLE = 1;
export declare const NGHTTP2_STREAM_STATE_OPEN = 2;
export declare const NGHTTP2_STREAM_STATE_RESERVED_LOCAL = 3;
export declare const NGHTTP2_STREAM_STATE_RESERVED_REMOTE = 4;
export declare const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL = 5;
export declare const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE = 6;
export declare const NGHTTP2_STREAM_STATE_CLOSED = 7;
export declare const NGHTTP2_FLAG_NONE = 0;
export declare const NGHTTP2_FLAG_END_STREAM = 1;
export declare const NGHTTP2_FLAG_END_HEADERS = 4;
export declare const NGHTTP2_FLAG_ACK = 1;
export declare const NGHTTP2_FLAG_PADDED = 8;
export declare const NGHTTP2_FLAG_PRIORITY = 32;
export declare const DEFAULT_SETTINGS_HEADER_TABLE_SIZE = 4096;
export declare const DEFAULT_SETTINGS_ENABLE_PUSH = 1;
export declare const DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS = 4294967295;
export declare const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE = 65535;
export declare const DEFAULT_SETTINGS_MAX_FRAME_SIZE = 16384;
export declare const DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE = 65535;
export declare const DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL = 0;
export declare const MAX_MAX_FRAME_SIZE = 16777215;
export declare const MIN_MAX_FRAME_SIZE = 16384;
export declare const MAX_INITIAL_WINDOW_SIZE = 2147483647;
export declare const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE = 1;
export declare const NGHTTP2_SETTINGS_ENABLE_PUSH = 2;
export declare const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS = 3;
export declare const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE = 4;
export declare const NGHTTP2_SETTINGS_MAX_FRAME_SIZE = 5;
export declare const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE = 6;
export declare const NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL = 8;
export declare const PADDING_STRATEGY_NONE = 0;
export declare const PADDING_STRATEGY_ALIGNED = 1;
export declare const PADDING_STRATEGY_MAX = 2;
export declare const PADDING_STRATEGY_CALLBACK = 1;
export declare const NGHTTP2_NO_ERROR = 0;
export declare const NGHTTP2_PROTOCOL_ERROR = 1;
export declare const NGHTTP2_INTERNAL_ERROR = 2;
export declare const NGHTTP2_FLOW_CONTROL_ERROR = 3;
export declare const NGHTTP2_SETTINGS_TIMEOUT = 4;
export declare const NGHTTP2_STREAM_CLOSED = 5;
export declare const NGHTTP2_FRAME_SIZE_ERROR = 6;
export declare const NGHTTP2_REFUSED_STREAM = 7;
export declare const NGHTTP2_CANCEL = 8;
export declare const NGHTTP2_COMPRESSION_ERROR = 9;
export declare const NGHTTP2_CONNECT_ERROR = 10;
export declare const NGHTTP2_ENHANCE_YOUR_CALM = 11;
export declare const NGHTTP2_INADEQUATE_SECURITY = 12;
export declare const NGHTTP2_HTTP_1_1_REQUIRED = 13;
export declare const NGHTTP2_DEFAULT_WEIGHT = 16;
export declare const HTTP2_HEADER_STATUS = ":status";
export declare const HTTP2_HEADER_METHOD = ":method";
export declare const HTTP2_HEADER_AUTHORITY = ":authority";
export declare const HTTP2_HEADER_SCHEME = ":scheme";
export declare const HTTP2_HEADER_PATH = ":path";
export declare const HTTP2_HEADER_PROTOCOL = ":protocol";
export declare const HTTP2_HEADER_ACCEPT_ENCODING = "accept-encoding";
export declare const HTTP2_HEADER_ACCEPT_LANGUAGE = "accept-language";
export declare const HTTP2_HEADER_ACCEPT_RANGES = "accept-ranges";
export declare const HTTP2_HEADER_ACCEPT = "accept";
export declare const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS = "access-control-allow-credentials";
export declare const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS = "access-control-allow-headers";
export declare const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS = "access-control-allow-methods";
export declare const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = "access-control-allow-origin";
export declare const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS = "access-control-expose-headers";
export declare const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS = "access-control-request-headers";
export declare const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD = "access-control-request-method";
export declare const HTTP2_HEADER_AGE = "age";
export declare const HTTP2_HEADER_AUTHORIZATION = "authorization";
export declare const HTTP2_HEADER_CACHE_CONTROL = "cache-control";
export declare const HTTP2_HEADER_CONNECTION = "connection";
export declare const HTTP2_HEADER_CONTENT_DISPOSITION = "content-disposition";
export declare const HTTP2_HEADER_CONTENT_ENCODING = "content-encoding";
export declare const HTTP2_HEADER_CONTENT_LENGTH = "content-length";
export declare const HTTP2_HEADER_CONTENT_TYPE = "content-type";
export declare const HTTP2_HEADER_COOKIE = "cookie";
export declare const HTTP2_HEADER_DATE = "date";
export declare const HTTP2_HEADER_ETAG = "etag";
export declare const HTTP2_HEADER_FORWARDED = "forwarded";
export declare const HTTP2_HEADER_HOST = "host";
export declare const HTTP2_HEADER_IF_MODIFIED_SINCE = "if-modified-since";
export declare const HTTP2_HEADER_IF_NONE_MATCH = "if-none-match";
export declare const HTTP2_HEADER_IF_RANGE = "if-range";
export declare const HTTP2_HEADER_LAST_MODIFIED = "last-modified";
export declare const HTTP2_HEADER_LINK = "link";
export declare const HTTP2_HEADER_LOCATION = "location";
export declare const HTTP2_HEADER_RANGE = "range";
export declare const HTTP2_HEADER_REFERER = "referer";
export declare const HTTP2_HEADER_SERVER = "server";
export declare const HTTP2_HEADER_SET_COOKIE = "set-cookie";
export declare const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY = "strict-transport-security";
export declare const HTTP2_HEADER_TRANSFER_ENCODING = "transfer-encoding";
export declare const HTTP2_HEADER_TE = "te";
export declare const HTTP2_HEADER_UPGRADE_INSECURE_REQUESTS = "upgrade-insecure-requests";
export declare const HTTP2_HEADER_UPGRADE = "upgrade";
export declare const HTTP2_HEADER_USER_AGENT = "user-agent";
export declare const HTTP2_HEADER_VARY = "vary";
export declare const HTTP2_HEADER_X_CONTENT_TYPE_OPTIONS = "x-content-type-options";
export declare const HTTP2_HEADER_X_FRAME_OPTIONS = "x-frame-options";
export declare const HTTP2_HEADER_KEEP_ALIVE = "keep-alive";
export declare const HTTP2_HEADER_PROXY_CONNECTION = "proxy-connection";
export declare const HTTP2_HEADER_X_XSS_PROTECTION = "x-xss-protection";
export declare const HTTP2_HEADER_ALT_SVC = "alt-svc";
export declare const HTTP2_HEADER_CONTENT_SECURITY_POLICY = "content-security-policy";
export declare const HTTP2_HEADER_EARLY_DATA = "early-data";
export declare const HTTP2_HEADER_EXPECT_CT = "expect-ct";
export declare const HTTP2_HEADER_ORIGIN = "origin";
export declare const HTTP2_HEADER_PURPOSE = "purpose";
export declare const HTTP2_HEADER_TIMING_ALLOW_ORIGIN = "timing-allow-origin";
export declare const HTTP2_HEADER_X_FORWARDED_FOR = "x-forwarded-for";
export declare const HTTP2_HEADER_PRIORITY = "priority";
export declare const HTTP2_HEADER_ACCEPT_CHARSET = "accept-charset";
export declare const HTTP2_HEADER_ACCESS_CONTROL_MAX_AGE = "access-control-max-age";
export declare const HTTP2_HEADER_ALLOW = "allow";
export declare const HTTP2_HEADER_CONTENT_LANGUAGE = "content-language";
export declare const HTTP2_HEADER_CONTENT_LOCATION = "content-location";
export declare const HTTP2_HEADER_CONTENT_MD5 = "content-md5";
export declare const HTTP2_HEADER_CONTENT_RANGE = "content-range";
export declare const HTTP2_HEADER_DNT = "dnt";
export declare const HTTP2_HEADER_EXPECT = "expect";
export declare const HTTP2_HEADER_EXPIRES = "expires";
export declare const HTTP2_HEADER_FROM = "from";
export declare const HTTP2_HEADER_IF_MATCH = "if-match";
export declare const HTTP2_HEADER_IF_UNMODIFIED_SINCE = "if-unmodified-since";
export declare const HTTP2_HEADER_MAX_FORWARDS = "max-forwards";
export declare const HTTP2_HEADER_PREFER = "prefer";
export declare const HTTP2_HEADER_PROXY_AUTHENTICATE = "proxy-authenticate";
export declare const HTTP2_HEADER_PROXY_AUTHORIZATION = "proxy-authorization";
export declare const HTTP2_HEADER_REFRESH = "refresh";
export declare const HTTP2_HEADER_RETRY_AFTER = "retry-after";
export declare const HTTP2_HEADER_TRAILER = "trailer";
export declare const HTTP2_HEADER_TK = "tk";
export declare const HTTP2_HEADER_VIA = "via";
export declare const HTTP2_HEADER_WARNING = "warning";
export declare const HTTP2_HEADER_WWW_AUTHENTICATE = "www-authenticate";
export declare const HTTP2_HEADER_HTTP2_SETTINGS = "http2-settings";
export declare const HTTP2_METHOD_ACL = "ACL";
export declare const HTTP2_METHOD_BASELINE_CONTROL = "BASELINE-CONTROL";
export declare const HTTP2_METHOD_BIND = "BIND";
export declare const HTTP2_METHOD_CHECKIN = "CHECKIN";
export declare const HTTP2_METHOD_CHECKOUT = "CHECKOUT";
export declare const HTTP2_METHOD_CONNECT = "CONNECT";
export declare const HTTP2_METHOD_COPY = "COPY";
export declare const HTTP2_METHOD_DELETE = "DELETE";
export declare const HTTP2_METHOD_GET = "GET";
export declare const HTTP2_METHOD_HEAD = "HEAD";
export declare const HTTP2_METHOD_LABEL = "LABEL";
export declare const HTTP2_METHOD_LINK = "LINK";
export declare const HTTP2_METHOD_LOCK = "LOCK";
export declare const HTTP2_METHOD_MERGE = "MERGE";
export declare const HTTP2_METHOD_MKACTIVITY = "MKACTIVITY";
export declare const HTTP2_METHOD_MKCALENDAR = "MKCALENDAR";
export declare const HTTP2_METHOD_MKCOL = "MKCOL";
export declare const HTTP2_METHOD_MKREDIRECTREF = "MKREDIRECTREF";
export declare const HTTP2_METHOD_MKWORKSPACE = "MKWORKSPACE";
export declare const HTTP2_METHOD_MOVE = "MOVE";
export declare const HTTP2_METHOD_OPTIONS = "OPTIONS";
export declare const HTTP2_METHOD_ORDERPATCH = "ORDERPATCH";
export declare const HTTP2_METHOD_PATCH = "PATCH";
export declare const HTTP2_METHOD_POST = "POST";
export declare const HTTP2_METHOD_PRI = "PRI";
export declare const HTTP2_METHOD_PROPFIND = "PROPFIND";
export declare const HTTP2_METHOD_PROPPATCH = "PROPPATCH";
export declare const HTTP2_METHOD_PUT = "PUT";
export declare const HTTP2_METHOD_REBIND = "REBIND";
export declare const HTTP2_METHOD_REPORT = "REPORT";
export declare const HTTP2_METHOD_SEARCH = "SEARCH";
export declare const HTTP2_METHOD_TRACE = "TRACE";
export declare const HTTP2_METHOD_UNBIND = "UNBIND";
export declare const HTTP2_METHOD_UNCHECKOUT = "UNCHECKOUT";
export declare const HTTP2_METHOD_UNLINK = "UNLINK";
export declare const HTTP2_METHOD_UNLOCK = "UNLOCK";
export declare const HTTP2_METHOD_UPDATE = "UPDATE";
export declare const HTTP2_METHOD_UPDATEREDIRECTREF = "UPDATEREDIRECTREF";
export declare const HTTP2_METHOD_VERSION_CONTROL = "VERSION-CONTROL";
export declare const HTTP_STATUS_CONTINUE = 100;
export declare const HTTP_STATUS_SWITCHING_PROTOCOLS = 101;
export declare const HTTP_STATUS_PROCESSING = 102;
export declare const HTTP_STATUS_EARLY_HINTS = 103;
export declare const HTTP_STATUS_OK = 200;
export declare const HTTP_STATUS_CREATED = 201;
export declare const HTTP_STATUS_ACCEPTED = 202;
export declare const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203;
export declare const HTTP_STATUS_NO_CONTENT = 204;
export declare const HTTP_STATUS_RESET_CONTENT = 205;
export declare const HTTP_STATUS_PARTIAL_CONTENT = 206;
export declare const HTTP_STATUS_MULTI_STATUS = 207;
export declare const HTTP_STATUS_ALREADY_REPORTED = 208;
export declare const HTTP_STATUS_IM_USED = 226;
export declare const HTTP_STATUS_MULTIPLE_CHOICES = 300;
export declare const HTTP_STATUS_MOVED_PERMANENTLY = 301;
export declare const HTTP_STATUS_FOUND = 302;
export declare const HTTP_STATUS_SEE_OTHER = 303;
export declare const HTTP_STATUS_NOT_MODIFIED = 304;
export declare const HTTP_STATUS_USE_PROXY = 305;
export declare const HTTP_STATUS_TEMPORARY_REDIRECT = 307;
export declare const HTTP_STATUS_PERMANENT_REDIRECT = 308;
export declare const HTTP_STATUS_BAD_REQUEST = 400;
export declare const HTTP_STATUS_UNAUTHORIZED = 401;
export declare const HTTP_STATUS_PAYMENT_REQUIRED = 402;
export declare const HTTP_STATUS_FORBIDDEN = 403;
export declare const HTTP_STATUS_NOT_FOUND = 404;
export declare const HTTP_STATUS_METHOD_NOT_ALLOWED = 405;
export declare const HTTP_STATUS_NOT_ACCEPTABLE = 406;
export declare const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407;
export declare const HTTP_STATUS_REQUEST_TIMEOUT = 408;
export declare const HTTP_STATUS_CONFLICT = 409;
export declare const HTTP_STATUS_GONE = 410;
export declare const HTTP_STATUS_LENGTH_REQUIRED = 411;
export declare const HTTP_STATUS_PRECONDITION_FAILED = 412;
export declare const HTTP_STATUS_PAYLOAD_TOO_LARGE = 413;
export declare const HTTP_STATUS_URI_TOO_LONG = 414;
export declare const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415;
export declare const HTTP_STATUS_RANGE_NOT_SATISFIABLE = 416;
export declare const HTTP_STATUS_EXPECTATION_FAILED = 417;
export declare const HTTP_STATUS_TEAPOT = 418;
export declare const HTTP_STATUS_MISDIRECTED_REQUEST = 421;
export declare const HTTP_STATUS_UNPROCESSABLE_ENTITY = 422;
export declare const HTTP_STATUS_LOCKED = 423;
export declare const HTTP_STATUS_FAILED_DEPENDENCY = 424;
export declare const HTTP_STATUS_TOO_EARLY = 425;
export declare const HTTP_STATUS_UPGRADE_REQUIRED = 426;
export declare const HTTP_STATUS_PRECONDITION_REQUIRED = 428;
export declare const HTTP_STATUS_TOO_MANY_REQUESTS = 429;
export declare const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
export declare const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451;
export declare const HTTP_STATUS_INTERNAL_SERVER_ERROR = 500;
export declare const HTTP_STATUS_NOT_IMPLEMENTED = 501;
export declare const HTTP_STATUS_BAD_GATEWAY = 502;
export declare const HTTP_STATUS_SERVICE_UNAVAILABLE = 503;
export declare const HTTP_STATUS_GATEWAY_TIMEOUT = 504;
export declare const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED = 505;
export declare const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES = 506;
export declare const HTTP_STATUS_INSUFFICIENT_STORAGE = 507;
export declare const HTTP_STATUS_LOOP_DETECTED = 508;
export declare const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED = 509;
export declare const HTTP_STATUS_NOT_EXTENDED = 510;
export declare const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511;

View file

@ -0,0 +1,241 @@
// npx -y node@22.14 -e 'const{constants}=require("http2");console.log(Object.entries(constants).map(([k,v]) => `export const ${k} = ${JSON.stringify(v)}`).join("\n"))'
export const NGHTTP2_ERR_FRAME_SIZE_ERROR = -522;
export const NGHTTP2_SESSION_SERVER = 0;
export const NGHTTP2_SESSION_CLIENT = 1;
export const NGHTTP2_STREAM_STATE_IDLE = 1;
export const NGHTTP2_STREAM_STATE_OPEN = 2;
export const NGHTTP2_STREAM_STATE_RESERVED_LOCAL = 3;
export const NGHTTP2_STREAM_STATE_RESERVED_REMOTE = 4;
export const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL = 5;
export const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE = 6;
export const NGHTTP2_STREAM_STATE_CLOSED = 7;
export const NGHTTP2_FLAG_NONE = 0;
export const NGHTTP2_FLAG_END_STREAM = 1;
export const NGHTTP2_FLAG_END_HEADERS = 4;
export const NGHTTP2_FLAG_ACK = 1;
export const NGHTTP2_FLAG_PADDED = 8;
export const NGHTTP2_FLAG_PRIORITY = 32;
export const DEFAULT_SETTINGS_HEADER_TABLE_SIZE = 4096;
export const DEFAULT_SETTINGS_ENABLE_PUSH = 1;
export const DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS = 4294967295;
export const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE = 65535;
export const DEFAULT_SETTINGS_MAX_FRAME_SIZE = 16384;
export const DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE = 65535;
export const DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL = 0;
export const MAX_MAX_FRAME_SIZE = 16777215;
export const MIN_MAX_FRAME_SIZE = 16384;
export const MAX_INITIAL_WINDOW_SIZE = 2147483647;
export const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE = 1;
export const NGHTTP2_SETTINGS_ENABLE_PUSH = 2;
export const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS = 3;
export const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE = 4;
export const NGHTTP2_SETTINGS_MAX_FRAME_SIZE = 5;
export const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE = 6;
export const NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL = 8;
export const PADDING_STRATEGY_NONE = 0;
export const PADDING_STRATEGY_ALIGNED = 1;
export const PADDING_STRATEGY_MAX = 2;
export const PADDING_STRATEGY_CALLBACK = 1;
export const NGHTTP2_NO_ERROR = 0;
export const NGHTTP2_PROTOCOL_ERROR = 1;
export const NGHTTP2_INTERNAL_ERROR = 2;
export const NGHTTP2_FLOW_CONTROL_ERROR = 3;
export const NGHTTP2_SETTINGS_TIMEOUT = 4;
export const NGHTTP2_STREAM_CLOSED = 5;
export const NGHTTP2_FRAME_SIZE_ERROR = 6;
export const NGHTTP2_REFUSED_STREAM = 7;
export const NGHTTP2_CANCEL = 8;
export const NGHTTP2_COMPRESSION_ERROR = 9;
export const NGHTTP2_CONNECT_ERROR = 10;
export const NGHTTP2_ENHANCE_YOUR_CALM = 11;
export const NGHTTP2_INADEQUATE_SECURITY = 12;
export const NGHTTP2_HTTP_1_1_REQUIRED = 13;
export const NGHTTP2_DEFAULT_WEIGHT = 16;
export const HTTP2_HEADER_STATUS = ":status";
export const HTTP2_HEADER_METHOD = ":method";
export const HTTP2_HEADER_AUTHORITY = ":authority";
export const HTTP2_HEADER_SCHEME = ":scheme";
export const HTTP2_HEADER_PATH = ":path";
export const HTTP2_HEADER_PROTOCOL = ":protocol";
export const HTTP2_HEADER_ACCEPT_ENCODING = "accept-encoding";
export const HTTP2_HEADER_ACCEPT_LANGUAGE = "accept-language";
export const HTTP2_HEADER_ACCEPT_RANGES = "accept-ranges";
export const HTTP2_HEADER_ACCEPT = "accept";
export const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS = "access-control-allow-credentials";
export const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS = "access-control-allow-headers";
export const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS = "access-control-allow-methods";
export const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = "access-control-allow-origin";
export const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS = "access-control-expose-headers";
export const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS = "access-control-request-headers";
export const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD = "access-control-request-method";
export const HTTP2_HEADER_AGE = "age";
export const HTTP2_HEADER_AUTHORIZATION = "authorization";
export const HTTP2_HEADER_CACHE_CONTROL = "cache-control";
export const HTTP2_HEADER_CONNECTION = "connection";
export const HTTP2_HEADER_CONTENT_DISPOSITION = "content-disposition";
export const HTTP2_HEADER_CONTENT_ENCODING = "content-encoding";
export const HTTP2_HEADER_CONTENT_LENGTH = "content-length";
export const HTTP2_HEADER_CONTENT_TYPE = "content-type";
export const HTTP2_HEADER_COOKIE = "cookie";
export const HTTP2_HEADER_DATE = "date";
export const HTTP2_HEADER_ETAG = "etag";
export const HTTP2_HEADER_FORWARDED = "forwarded";
export const HTTP2_HEADER_HOST = "host";
export const HTTP2_HEADER_IF_MODIFIED_SINCE = "if-modified-since";
export const HTTP2_HEADER_IF_NONE_MATCH = "if-none-match";
export const HTTP2_HEADER_IF_RANGE = "if-range";
export const HTTP2_HEADER_LAST_MODIFIED = "last-modified";
export const HTTP2_HEADER_LINK = "link";
export const HTTP2_HEADER_LOCATION = "location";
export const HTTP2_HEADER_RANGE = "range";
export const HTTP2_HEADER_REFERER = "referer";
export const HTTP2_HEADER_SERVER = "server";
export const HTTP2_HEADER_SET_COOKIE = "set-cookie";
export const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY = "strict-transport-security";
export const HTTP2_HEADER_TRANSFER_ENCODING = "transfer-encoding";
export const HTTP2_HEADER_TE = "te";
export const HTTP2_HEADER_UPGRADE_INSECURE_REQUESTS = "upgrade-insecure-requests";
export const HTTP2_HEADER_UPGRADE = "upgrade";
export const HTTP2_HEADER_USER_AGENT = "user-agent";
export const HTTP2_HEADER_VARY = "vary";
export const HTTP2_HEADER_X_CONTENT_TYPE_OPTIONS = "x-content-type-options";
export const HTTP2_HEADER_X_FRAME_OPTIONS = "x-frame-options";
export const HTTP2_HEADER_KEEP_ALIVE = "keep-alive";
export const HTTP2_HEADER_PROXY_CONNECTION = "proxy-connection";
export const HTTP2_HEADER_X_XSS_PROTECTION = "x-xss-protection";
export const HTTP2_HEADER_ALT_SVC = "alt-svc";
export const HTTP2_HEADER_CONTENT_SECURITY_POLICY = "content-security-policy";
export const HTTP2_HEADER_EARLY_DATA = "early-data";
export const HTTP2_HEADER_EXPECT_CT = "expect-ct";
export const HTTP2_HEADER_ORIGIN = "origin";
export const HTTP2_HEADER_PURPOSE = "purpose";
export const HTTP2_HEADER_TIMING_ALLOW_ORIGIN = "timing-allow-origin";
export const HTTP2_HEADER_X_FORWARDED_FOR = "x-forwarded-for";
export const HTTP2_HEADER_PRIORITY = "priority";
export const HTTP2_HEADER_ACCEPT_CHARSET = "accept-charset";
export const HTTP2_HEADER_ACCESS_CONTROL_MAX_AGE = "access-control-max-age";
export const HTTP2_HEADER_ALLOW = "allow";
export const HTTP2_HEADER_CONTENT_LANGUAGE = "content-language";
export const HTTP2_HEADER_CONTENT_LOCATION = "content-location";
export const HTTP2_HEADER_CONTENT_MD5 = "content-md5";
export const HTTP2_HEADER_CONTENT_RANGE = "content-range";
export const HTTP2_HEADER_DNT = "dnt";
export const HTTP2_HEADER_EXPECT = "expect";
export const HTTP2_HEADER_EXPIRES = "expires";
export const HTTP2_HEADER_FROM = "from";
export const HTTP2_HEADER_IF_MATCH = "if-match";
export const HTTP2_HEADER_IF_UNMODIFIED_SINCE = "if-unmodified-since";
export const HTTP2_HEADER_MAX_FORWARDS = "max-forwards";
export const HTTP2_HEADER_PREFER = "prefer";
export const HTTP2_HEADER_PROXY_AUTHENTICATE = "proxy-authenticate";
export const HTTP2_HEADER_PROXY_AUTHORIZATION = "proxy-authorization";
export const HTTP2_HEADER_REFRESH = "refresh";
export const HTTP2_HEADER_RETRY_AFTER = "retry-after";
export const HTTP2_HEADER_TRAILER = "trailer";
export const HTTP2_HEADER_TK = "tk";
export const HTTP2_HEADER_VIA = "via";
export const HTTP2_HEADER_WARNING = "warning";
export const HTTP2_HEADER_WWW_AUTHENTICATE = "www-authenticate";
export const HTTP2_HEADER_HTTP2_SETTINGS = "http2-settings";
export const HTTP2_METHOD_ACL = "ACL";
export const HTTP2_METHOD_BASELINE_CONTROL = "BASELINE-CONTROL";
export const HTTP2_METHOD_BIND = "BIND";
export const HTTP2_METHOD_CHECKIN = "CHECKIN";
export const HTTP2_METHOD_CHECKOUT = "CHECKOUT";
export const HTTP2_METHOD_CONNECT = "CONNECT";
export const HTTP2_METHOD_COPY = "COPY";
export const HTTP2_METHOD_DELETE = "DELETE";
export const HTTP2_METHOD_GET = "GET";
export const HTTP2_METHOD_HEAD = "HEAD";
export const HTTP2_METHOD_LABEL = "LABEL";
export const HTTP2_METHOD_LINK = "LINK";
export const HTTP2_METHOD_LOCK = "LOCK";
export const HTTP2_METHOD_MERGE = "MERGE";
export const HTTP2_METHOD_MKACTIVITY = "MKACTIVITY";
export const HTTP2_METHOD_MKCALENDAR = "MKCALENDAR";
export const HTTP2_METHOD_MKCOL = "MKCOL";
export const HTTP2_METHOD_MKREDIRECTREF = "MKREDIRECTREF";
export const HTTP2_METHOD_MKWORKSPACE = "MKWORKSPACE";
export const HTTP2_METHOD_MOVE = "MOVE";
export const HTTP2_METHOD_OPTIONS = "OPTIONS";
export const HTTP2_METHOD_ORDERPATCH = "ORDERPATCH";
export const HTTP2_METHOD_PATCH = "PATCH";
export const HTTP2_METHOD_POST = "POST";
export const HTTP2_METHOD_PRI = "PRI";
export const HTTP2_METHOD_PROPFIND = "PROPFIND";
export const HTTP2_METHOD_PROPPATCH = "PROPPATCH";
export const HTTP2_METHOD_PUT = "PUT";
export const HTTP2_METHOD_REBIND = "REBIND";
export const HTTP2_METHOD_REPORT = "REPORT";
export const HTTP2_METHOD_SEARCH = "SEARCH";
export const HTTP2_METHOD_TRACE = "TRACE";
export const HTTP2_METHOD_UNBIND = "UNBIND";
export const HTTP2_METHOD_UNCHECKOUT = "UNCHECKOUT";
export const HTTP2_METHOD_UNLINK = "UNLINK";
export const HTTP2_METHOD_UNLOCK = "UNLOCK";
export const HTTP2_METHOD_UPDATE = "UPDATE";
export const HTTP2_METHOD_UPDATEREDIRECTREF = "UPDATEREDIRECTREF";
export const HTTP2_METHOD_VERSION_CONTROL = "VERSION-CONTROL";
export const HTTP_STATUS_CONTINUE = 100;
export const HTTP_STATUS_SWITCHING_PROTOCOLS = 101;
export const HTTP_STATUS_PROCESSING = 102;
export const HTTP_STATUS_EARLY_HINTS = 103;
export const HTTP_STATUS_OK = 200;
export const HTTP_STATUS_CREATED = 201;
export const HTTP_STATUS_ACCEPTED = 202;
export const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203;
export const HTTP_STATUS_NO_CONTENT = 204;
export const HTTP_STATUS_RESET_CONTENT = 205;
export const HTTP_STATUS_PARTIAL_CONTENT = 206;
export const HTTP_STATUS_MULTI_STATUS = 207;
export const HTTP_STATUS_ALREADY_REPORTED = 208;
export const HTTP_STATUS_IM_USED = 226;
export const HTTP_STATUS_MULTIPLE_CHOICES = 300;
export const HTTP_STATUS_MOVED_PERMANENTLY = 301;
export const HTTP_STATUS_FOUND = 302;
export const HTTP_STATUS_SEE_OTHER = 303;
export const HTTP_STATUS_NOT_MODIFIED = 304;
export const HTTP_STATUS_USE_PROXY = 305;
export const HTTP_STATUS_TEMPORARY_REDIRECT = 307;
export const HTTP_STATUS_PERMANENT_REDIRECT = 308;
export const HTTP_STATUS_BAD_REQUEST = 400;
export const HTTP_STATUS_UNAUTHORIZED = 401;
export const HTTP_STATUS_PAYMENT_REQUIRED = 402;
export const HTTP_STATUS_FORBIDDEN = 403;
export const HTTP_STATUS_NOT_FOUND = 404;
export const HTTP_STATUS_METHOD_NOT_ALLOWED = 405;
export const HTTP_STATUS_NOT_ACCEPTABLE = 406;
export const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407;
export const HTTP_STATUS_REQUEST_TIMEOUT = 408;
export const HTTP_STATUS_CONFLICT = 409;
export const HTTP_STATUS_GONE = 410;
export const HTTP_STATUS_LENGTH_REQUIRED = 411;
export const HTTP_STATUS_PRECONDITION_FAILED = 412;
export const HTTP_STATUS_PAYLOAD_TOO_LARGE = 413;
export const HTTP_STATUS_URI_TOO_LONG = 414;
export const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415;
export const HTTP_STATUS_RANGE_NOT_SATISFIABLE = 416;
export const HTTP_STATUS_EXPECTATION_FAILED = 417;
export const HTTP_STATUS_TEAPOT = 418;
export const HTTP_STATUS_MISDIRECTED_REQUEST = 421;
export const HTTP_STATUS_UNPROCESSABLE_ENTITY = 422;
export const HTTP_STATUS_LOCKED = 423;
export const HTTP_STATUS_FAILED_DEPENDENCY = 424;
export const HTTP_STATUS_TOO_EARLY = 425;
export const HTTP_STATUS_UPGRADE_REQUIRED = 426;
export const HTTP_STATUS_PRECONDITION_REQUIRED = 428;
export const HTTP_STATUS_TOO_MANY_REQUESTS = 429;
export const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
export const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451;
export const HTTP_STATUS_INTERNAL_SERVER_ERROR = 500;
export const HTTP_STATUS_NOT_IMPLEMENTED = 501;
export const HTTP_STATUS_BAD_GATEWAY = 502;
export const HTTP_STATUS_SERVICE_UNAVAILABLE = 503;
export const HTTP_STATUS_GATEWAY_TIMEOUT = 504;
export const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED = 505;
export const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES = 506;
export const HTTP_STATUS_INSUFFICIENT_STORAGE = 507;
export const HTTP_STATUS_LOOP_DETECTED = 508;
export const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED = 509;
export const HTTP_STATUS_NOT_EXTENDED = 510;
export const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511;

View file

@ -0,0 +1,17 @@
import type nodeNet from "node:net";
import { EventEmitter } from "node:events";
// Docs: https://nodejs.org/api/net.html#net_class_net_server
export declare class Server extends EventEmitter implements nodeNet.Server {
readonly __unenv__: true;
maxConnections: number;
connections: number;
readonly listening: boolean;
constructor(arg1?: nodeNet.ServerOpts | ((socket: nodeNet.Socket) => void), arg2?: (socket: nodeNet.Socket) => void);
listen(): this;
close(callback?: (err?: Error) => void): this;
address(): nodeNet.AddressInfo | string | null;
getConnections(cb: (error: Error | null, count: number) => void): void;
ref(): this;
unref(): this;
[Symbol.asyncDispose](): Promise<void>;
}

View file

@ -0,0 +1,33 @@
import { createNotImplementedError } from "../../../_internal/utils.mjs";
import { EventEmitter } from "node:events";
// Docs: https://nodejs.org/api/net.html#net_class_net_server
export class Server extends EventEmitter {
__unenv__ = true;
maxConnections = 1;
connections = 0;
listening = false;
constructor(arg1, arg2) {
super();
}
listen() {
throw createNotImplementedError("node:net.Server.listen()");
}
close(callback) {
throw createNotImplementedError("node:net.Server.close()");
}
address() {
return null;
}
getConnections(cb) {
cb(null, 0);
}
ref() {
return this;
}
unref() {
return this;
}
[Symbol.asyncDispose]() {
return Promise.resolve();
}
}

View file

@ -0,0 +1,45 @@
import type nodeNet from "node:net";
import { type Callback, type BufferEncoding } from "../../../_internal/types.mjs";
// Relative stream import required, see https://github.com/unjs/unenv/issues/353
import { Duplex } from "../stream/duplex.mjs";
// Docs: https://nodejs.org/api/net.html#net_class_net_socket
export declare class Socket extends Duplex implements nodeNet.Socket {
readonly __unenv__: true;
readonly bufferSize: number;
readonly bytesRead: number;
readonly bytesWritten: number;
readonly connecting: boolean;
readonly destroyed: boolean;
readonly pending: boolean;
readonly localAddress: string;
readonly localPort: number;
readonly remoteAddress?: string;
readonly remoteFamily?: string;
readonly remotePort?: number;
readonly autoSelectFamilyAttemptedAddresses: readonly [];
readonly readyState: nodeNet.SocketReadyState;
constructor(_options?: nodeNet.SocketConstructorOpts);
write(_buffer: Uint8Array | string, _arg1?: BufferEncoding | Callback<Error | undefined>, _arg2?: Callback<Error | undefined>): boolean;
connect(_arg1: number | string | nodeNet.SocketConnectOpts, _arg2?: string | Callback, _arg3?: Callback);
end(_arg1?: Callback | Uint8Array | string, _arg2?: BufferEncoding | Callback, _arg3?: Callback);
setEncoding(_encoding?: BufferEncoding): this;
pause();
resume();
setTimeout(_timeout: number, _callback?: Callback): this;
setNoDelay(_noDelay?: boolean): this;
setKeepAlive(_enable?: boolean, _initialDelay?: number): this;
address(): {};
unref();
ref();
destroySoon();
resetAndDestroy();
}
export declare class SocketAddress implements nodeNet.SocketAddress {
readonly __unenv__: true;
address: string;
family: "ipv4" | "ipv6";
port: number;
flowlabel: number;
static parse(_address: string, _port?: number): undefined;
constructor(options: nodeNet.SocketAddress);
}

View file

@ -0,0 +1,83 @@
// Relative stream import required, see https://github.com/unjs/unenv/issues/353
import { Duplex } from "../stream/duplex.mjs";
// Docs: https://nodejs.org/api/net.html#net_class_net_socket
export class Socket extends Duplex {
__unenv__ = true;
bufferSize = 0;
bytesRead = 0;
bytesWritten = 0;
connecting = false;
destroyed = false;
pending = false;
localAddress = "";
localPort = 0;
remoteAddress = "";
remoteFamily = "";
remotePort = 0;
autoSelectFamilyAttemptedAddresses = [];
readyState = "readOnly";
constructor(_options) {
super();
}
write(_buffer, _arg1, _arg2) {
return false;
}
connect(_arg1, _arg2, _arg3) {
return this;
}
end(_arg1, _arg2, _arg3) {
return this;
}
setEncoding(_encoding) {
return this;
}
pause() {
return this;
}
resume() {
return this;
}
setTimeout(_timeout, _callback) {
return this;
}
setNoDelay(_noDelay) {
return this;
}
setKeepAlive(_enable, _initialDelay) {
return this;
}
address() {
return {};
}
unref() {
return this;
}
ref() {
return this;
}
destroySoon() {
this.destroy();
}
resetAndDestroy() {
const err = new Error("ERR_SOCKET_CLOSED");
err.code = "ERR_SOCKET_CLOSED";
this.destroy(err);
return this;
}
}
export class SocketAddress {
__unenv__ = true;
address;
family;
port;
flowlabel;
static parse(_address, _port) {
return undefined;
}
constructor(options) {
this.address = options.address;
this.family = options.family;
this.port = options.port;
this.flowlabel = options.flowlabel;
}
}

View file

@ -0,0 +1,133 @@
// npx -y node@22.14 -e 'const{constants}=require("os");console.log(Object.entries(constants).map(([k,v]) => `export const ${k} = ${JSON.stringify(v)}`).join("\n"))'
export declare const UV_UDP_REUSEADDR = 4;
export declare const dlopen: {
RTLD_LAZY: number;
RTLD_NOW: number;
RTLD_GLOBAL: number;
RTLD_LOCAL: number;
RTLD_DEEPBIND: number;
};
export declare const errno: {
E2BIG: number;
EACCES: number;
EADDRINUSE: number;
EADDRNOTAVAIL: number;
EAFNOSUPPORT: number;
EAGAIN: number;
EALREADY: number;
EBADF: number;
EBADMSG: number;
EBUSY: number;
ECANCELED: number;
ECHILD: number;
ECONNABORTED: number;
ECONNREFUSED: number;
ECONNRESET: number;
EDEADLK: number;
EDESTADDRREQ: number;
EDOM: number;
EDQUOT: number;
EEXIST: number;
EFAULT: number;
EFBIG: number;
EHOSTUNREACH: number;
EIDRM: number;
EILSEQ: number;
EINPROGRESS: number;
EINTR: number;
EINVAL: number;
EIO: number;
EISCONN: number;
EISDIR: number;
ELOOP: number;
EMFILE: number;
EMLINK: number;
EMSGSIZE: number;
EMULTIHOP: number;
ENAMETOOLONG: number;
ENETDOWN: number;
ENETRESET: number;
ENETUNREACH: number;
ENFILE: number;
ENOBUFS: number;
ENODATA: number;
ENODEV: number;
ENOENT: number;
ENOEXEC: number;
ENOLCK: number;
ENOLINK: number;
ENOMEM: number;
ENOMSG: number;
ENOPROTOOPT: number;
ENOSPC: number;
ENOSR: number;
ENOSTR: number;
ENOSYS: number;
ENOTCONN: number;
ENOTDIR: number;
ENOTEMPTY: number;
ENOTSOCK: number;
ENOTSUP: number;
ENOTTY: number;
ENXIO: number;
EOPNOTSUPP: number;
EOVERFLOW: number;
EPERM: number;
EPIPE: number;
EPROTO: number;
EPROTONOSUPPORT: number;
EPROTOTYPE: number;
ERANGE: number;
EROFS: number;
ESPIPE: number;
ESRCH: number;
ESTALE: number;
ETIME: number;
ETIMEDOUT: number;
ETXTBSY: number;
EWOULDBLOCK: number;
EXDEV: number;
};
export declare const signals: {
SIGHUP: number;
SIGINT: number;
SIGQUIT: number;
SIGILL: number;
SIGTRAP: number;
SIGABRT: number;
SIGIOT: number;
SIGBUS: number;
SIGFPE: number;
SIGKILL: number;
SIGUSR1: number;
SIGSEGV: number;
SIGUSR2: number;
SIGPIPE: number;
SIGALRM: number;
SIGTERM: number;
SIGCHLD: number;
SIGSTKFLT: number;
SIGCONT: number;
SIGSTOP: number;
SIGTSTP: number;
SIGTTIN: number;
SIGTTOU: number;
SIGURG: number;
SIGXCPU: number;
SIGXFSZ: number;
SIGVTALRM: number;
SIGPROF: number;
SIGWINCH: number;
SIGIO: number;
SIGPOLL: number;
SIGPWR: number;
SIGSYS: number;
};
export declare const priority: {
PRIORITY_LOW: number;
PRIORITY_BELOW_NORMAL: number;
PRIORITY_NORMAL: number;
PRIORITY_ABOVE_NORMAL: number;
PRIORITY_HIGH: number;
PRIORITY_HIGHEST: number;
};

View file

@ -0,0 +1,133 @@
// npx -y node@22.14 -e 'const{constants}=require("os");console.log(Object.entries(constants).map(([k,v]) => `export const ${k} = ${JSON.stringify(v)}`).join("\n"))'
export const UV_UDP_REUSEADDR = 4;
export const dlopen = {
RTLD_LAZY: 1,
RTLD_NOW: 2,
RTLD_GLOBAL: 256,
RTLD_LOCAL: 0,
RTLD_DEEPBIND: 8
};
export const errno = {
E2BIG: 7,
EACCES: 13,
EADDRINUSE: 98,
EADDRNOTAVAIL: 99,
EAFNOSUPPORT: 97,
EAGAIN: 11,
EALREADY: 114,
EBADF: 9,
EBADMSG: 74,
EBUSY: 16,
ECANCELED: 125,
ECHILD: 10,
ECONNABORTED: 103,
ECONNREFUSED: 111,
ECONNRESET: 104,
EDEADLK: 35,
EDESTADDRREQ: 89,
EDOM: 33,
EDQUOT: 122,
EEXIST: 17,
EFAULT: 14,
EFBIG: 27,
EHOSTUNREACH: 113,
EIDRM: 43,
EILSEQ: 84,
EINPROGRESS: 115,
EINTR: 4,
EINVAL: 22,
EIO: 5,
EISCONN: 106,
EISDIR: 21,
ELOOP: 40,
EMFILE: 24,
EMLINK: 31,
EMSGSIZE: 90,
EMULTIHOP: 72,
ENAMETOOLONG: 36,
ENETDOWN: 100,
ENETRESET: 102,
ENETUNREACH: 101,
ENFILE: 23,
ENOBUFS: 105,
ENODATA: 61,
ENODEV: 19,
ENOENT: 2,
ENOEXEC: 8,
ENOLCK: 37,
ENOLINK: 67,
ENOMEM: 12,
ENOMSG: 42,
ENOPROTOOPT: 92,
ENOSPC: 28,
ENOSR: 63,
ENOSTR: 60,
ENOSYS: 38,
ENOTCONN: 107,
ENOTDIR: 20,
ENOTEMPTY: 39,
ENOTSOCK: 88,
ENOTSUP: 95,
ENOTTY: 25,
ENXIO: 6,
EOPNOTSUPP: 95,
EOVERFLOW: 75,
EPERM: 1,
EPIPE: 32,
EPROTO: 71,
EPROTONOSUPPORT: 93,
EPROTOTYPE: 91,
ERANGE: 34,
EROFS: 30,
ESPIPE: 29,
ESRCH: 3,
ESTALE: 116,
ETIME: 62,
ETIMEDOUT: 110,
ETXTBSY: 26,
EWOULDBLOCK: 11,
EXDEV: 18
};
export const signals = {
SIGHUP: 1,
SIGINT: 2,
SIGQUIT: 3,
SIGILL: 4,
SIGTRAP: 5,
SIGABRT: 6,
SIGIOT: 6,
SIGBUS: 7,
SIGFPE: 8,
SIGKILL: 9,
SIGUSR1: 10,
SIGSEGV: 11,
SIGUSR2: 12,
SIGPIPE: 13,
SIGALRM: 14,
SIGTERM: 15,
SIGCHLD: 17,
SIGSTKFLT: 16,
SIGCONT: 18,
SIGSTOP: 19,
SIGTSTP: 20,
SIGTTIN: 21,
SIGTTOU: 22,
SIGURG: 23,
SIGXCPU: 24,
SIGXFSZ: 25,
SIGVTALRM: 26,
SIGPROF: 27,
SIGWINCH: 28,
SIGIO: 29,
SIGPOLL: 29,
SIGPWR: 30,
SIGSYS: 31
};
export const priority = {
PRIORITY_LOW: 19,
PRIORITY_BELOW_NORMAL: 10,
PRIORITY_NORMAL: 0,
PRIORITY_ABOVE_NORMAL: -7,
PRIORITY_HIGH: -14,
PRIORITY_HIGHEST: -20
};

View file

@ -0,0 +1,25 @@
// npx -y node@22.14 -e 'const {constants}=require("perf_hooks");console.log(Object.entries(Object.getOwnPropertyDescriptors(constants)).map(([k,v]) => `export const ${k} = ${JSON.stringify(v.value)}`).join("\n"))'
export declare const NODE_PERFORMANCE_GC_MAJOR = 4;
export declare const NODE_PERFORMANCE_GC_MINOR = 1;
export declare const NODE_PERFORMANCE_GC_INCREMENTAL = 8;
export declare const NODE_PERFORMANCE_GC_WEAKCB = 16;
export declare const NODE_PERFORMANCE_GC_FLAGS_NO = 0;
export declare const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED = 2;
export declare const NODE_PERFORMANCE_GC_FLAGS_FORCED = 4;
export declare const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING = 8;
export declare const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE = 16;
export declare const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY = 32;
export declare const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE = 64;
export declare const NODE_PERFORMANCE_ENTRY_TYPE_GC = 0;
export declare const NODE_PERFORMANCE_ENTRY_TYPE_HTTP = 1;
export declare const NODE_PERFORMANCE_ENTRY_TYPE_HTTP2 = 2;
export declare const NODE_PERFORMANCE_ENTRY_TYPE_NET = 3;
export declare const NODE_PERFORMANCE_ENTRY_TYPE_DNS = 4;
export declare const NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN_TIMESTAMP = 0;
export declare const NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN = 1;
export declare const NODE_PERFORMANCE_MILESTONE_ENVIRONMENT = 2;
export declare const NODE_PERFORMANCE_MILESTONE_NODE_START = 3;
export declare const NODE_PERFORMANCE_MILESTONE_V8_START = 4;
export declare const NODE_PERFORMANCE_MILESTONE_LOOP_START = 5;
export declare const NODE_PERFORMANCE_MILESTONE_LOOP_EXIT = 6;
export declare const NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE = 7;

View file

@ -0,0 +1,25 @@
// npx -y node@22.14 -e 'const {constants}=require("perf_hooks");console.log(Object.entries(Object.getOwnPropertyDescriptors(constants)).map(([k,v]) => `export const ${k} = ${JSON.stringify(v.value)}`).join("\n"))'
export const NODE_PERFORMANCE_GC_MAJOR = 4;
export const NODE_PERFORMANCE_GC_MINOR = 1;
export const NODE_PERFORMANCE_GC_INCREMENTAL = 8;
export const NODE_PERFORMANCE_GC_WEAKCB = 16;
export const NODE_PERFORMANCE_GC_FLAGS_NO = 0;
export const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED = 2;
export const NODE_PERFORMANCE_GC_FLAGS_FORCED = 4;
export const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING = 8;
export const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE = 16;
export const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY = 32;
export const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE = 64;
export const NODE_PERFORMANCE_ENTRY_TYPE_GC = 0;
export const NODE_PERFORMANCE_ENTRY_TYPE_HTTP = 1;
export const NODE_PERFORMANCE_ENTRY_TYPE_HTTP2 = 2;
export const NODE_PERFORMANCE_ENTRY_TYPE_NET = 3;
export const NODE_PERFORMANCE_ENTRY_TYPE_DNS = 4;
export const NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN_TIMESTAMP = 0;
export const NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN = 1;
export const NODE_PERFORMANCE_MILESTONE_ENVIRONMENT = 2;
export const NODE_PERFORMANCE_MILESTONE_NODE_START = 3;
export const NODE_PERFORMANCE_MILESTONE_V8_START = 4;
export const NODE_PERFORMANCE_MILESTONE_LOOP_START = 5;
export const NODE_PERFORMANCE_MILESTONE_LOOP_EXIT = 6;
export const NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE = 7;

View file

@ -0,0 +1,28 @@
import type nodePerfHooks from "node:perf_hooks";
declare class Histogram implements nodePerfHooks.Histogram {
min: number;
max: number;
mean;
exceeds: number;
stddev;
count: number;
countBigInt: bigint;
exceedsBigInt: bigint;
maxBigInt: number;
minBigInt: bigint;
percentiles: Map<number, number>;
percentilesBigInt: Map<bigint, bigint>;
percentileBigInt(_percentile: number): bigint;
percentile(percentile: number): number;
reset(): void;
}
export declare class IntervalHistogram extends Histogram implements nodePerfHooks.IntervalHistogram {
enable(): boolean;
disable(): boolean;
}
export declare class RecordableHistogram extends Histogram implements nodePerfHooks.RecordableHistogram {
record(val: number | bigint): void;
recordDelta(): void;
add(other: nodePerfHooks.RecordableHistogram): void;
}
export {};

View file

@ -0,0 +1,43 @@
import { createNotImplementedError } from "../../../_internal/utils.mjs";
class Histogram {
min = 0x8000000000000000;
max = 0;
mean = Number.NaN;
exceeds = 0;
stddev = Number.NaN;
count = 0;
countBigInt = BigInt(0);
exceedsBigInt = BigInt(0);
maxBigInt = 0;
minBigInt = BigInt(9223372036854775807n);
percentiles = new Map();
percentilesBigInt = new Map();
percentileBigInt(_percentile) {
throw createNotImplementedError("Histogram.percentileBigInt");
}
percentile(percentile) {
return this.percentiles.get(percentile) ?? Number.NaN;
}
reset() {
throw createNotImplementedError("Histogram.reset");
}
}
export class IntervalHistogram extends Histogram {
enable() {
return true;
}
disable() {
return true;
}
}
export class RecordableHistogram extends Histogram {
record(val) {
throw createNotImplementedError("RecordableHistogram.record");
}
recordDelta() {
throw createNotImplementedError("RecordableHistogram.recordDelta");
}
add(other) {
throw createNotImplementedError("RecordableHistogram.add");
}
}

View file

@ -0,0 +1,103 @@
import type nodePerfHooks from "node:perf_hooks";
// PerformanceEntry
export declare class PerformanceEntry implements nodePerfHooks.PerformanceEntry {
readonly __unenv__: true;
detail: any | undefined;
entryType: any;
name: string;
startTime: number;
constructor(name: string, options?: PerformanceMarkOptions);
get duration(): number;
toJSON(): {};
}
// PerformanceMark
export declare const PerformanceMark: typeof nodePerfHooks.PerformanceMark;
// PerformanceMark
export declare class PerformanceMeasure extends PerformanceEntry implements globalThis.PerformanceMeasure {
entryType: "measure";
}
// PerformanceResourceTiming
export declare class PerformanceResourceTiming extends PerformanceEntry implements globalThis.PerformanceResourceTiming {
entryType: "resource";
serverTiming: readonly PerformanceServerTiming[];
connectEnd: number;
connectStart: number;
decodedBodySize: number;
domainLookupEnd: number;
domainLookupStart: number;
encodedBodySize: number;
fetchStart: number;
initiatorType: string;
name: string;
nextHopProtocol: string;
redirectEnd: number;
redirectStart: number;
requestStart: number;
responseEnd: number;
responseStart: number;
secureConnectionStart: number;
startTime: number;
transferSize: number;
workerStart: number;
responseStatus: number;
}
// PerformanceObserverEntryList
export declare class PerformanceObserverEntryList implements globalThis.PerformanceObserverEntryList {
readonly __unenv__: true;
getEntries(): PerformanceEntryList;
getEntriesByName(_name: string, _type?: string | undefined): PerformanceEntryList;
getEntriesByType(type: string): PerformanceEntryList;
}
// Performance
export declare class Performance implements nodePerfHooks.Performance {
readonly __unenv__: true;
timeOrigin: number;
eventCounts: EventCounts;
_entries: PerformanceEntry[];
_resourceTimingBufferSize: number;
navigation: any;
timing: any;
timerify<T extends (...params: any[]) => any>(_fn: T, _options?: nodePerfHooks.TimerifyOptions | undefined): T;
get nodeTiming(): nodePerfHooks.PerformanceNodeTiming;
eventLoopUtilization(): nodePerfHooks.EventLoopUtilization;
markResourceTiming(): nodePerfHooks.PerformanceResourceTiming;
onresourcetimingbufferfull: ((this: Performance, ev: Event) => any) | null;
now(): number;
clearMarks(markName?: string | undefined): void;
clearMeasures(measureName?: string | undefined): void;
clearResourceTimings(): void;
getEntries(): any;
getEntriesByName(name: string, type?: string | undefined): any;
getEntriesByType(type: string): any[];
mark(name: string, options?: PerformanceMarkOptions | undefined): any;
measure(measureName: string, startOrMeasureOptions?: string | PerformanceMeasureOptions, endMark?: string);
setResourceTimingBufferSize(maxSize: number): void;
addEventListener<K extends "resourcetimingbufferfull">(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void;
removeEventListener<K extends "resourcetimingbufferfull">(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | EventListenerOptions | undefined): void;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions | undefined): void;
dispatchEvent(event: Event): boolean;
toJSON();
}
// PerformanceObserver
export declare class PerformanceObserver implements nodePerfHooks.PerformanceObserver {
readonly __unenv__: true;
static supportedEntryTypes: ReadonlyArray<string>;
_callback: PerformanceObserverCallback | null;
constructor(callback: PerformanceObserverCallback);
takeRecords(): unknown;
disconnect(): void;
observe(options: any);
bind<Func extends (...args: any[]) => any>(fn: Func): Func;
runInAsyncScope<
This,
Result
>(fn: (this: This, ...args: any[]) => Result, thisArg?: This | undefined, ...args: any[]);
asyncId(): number;
triggerAsyncId(): number;
emitDestroy(): this;
}
// workerd implements a subset of globalThis.performance (as of last check, only timeOrigin set to 0 + now() implemented)
// We already use performance.now() from globalThis.performance, if provided (see top of this file)
// If we detect this condition, we can just use polyfill instead.
export declare const performance: unknown;

View file

@ -0,0 +1,232 @@
import { createNotImplementedError } from "../../../_internal/utils.mjs";
const _timeOrigin = globalThis.performance?.timeOrigin ?? Date.now();
const _performanceNow = globalThis.performance?.now ? globalThis.performance.now.bind(globalThis.performance) : () => Date.now() - _timeOrigin;
const nodeTiming = {
name: "node",
entryType: "node",
startTime: 0,
duration: 0,
nodeStart: 0,
v8Start: 0,
bootstrapComplete: 0,
environment: 0,
loopStart: 0,
loopExit: 0,
idleTime: 0,
uvMetricsInfo: {
loopCount: 0,
events: 0,
eventsWaiting: 0
},
detail: undefined,
toJSON() {
return this;
}
};
// PerformanceEntry
export class PerformanceEntry {
__unenv__ = true;
detail;
entryType = "event";
name;
startTime;
constructor(name, options) {
this.name = name;
this.startTime = options?.startTime || _performanceNow();
this.detail = options?.detail;
}
get duration() {
return _performanceNow() - this.startTime;
}
toJSON() {
return {
name: this.name,
entryType: this.entryType,
startTime: this.startTime,
duration: this.duration,
detail: this.detail
};
}
}
// PerformanceMark
export const PerformanceMark = class PerformanceMark extends PerformanceEntry {
entryType = "mark";
constructor() {
// @ts-ignore
super(...arguments);
}
get duration() {
return 0;
}
};
// PerformanceMark
export class PerformanceMeasure extends PerformanceEntry {
entryType = "measure";
}
// PerformanceResourceTiming
export class PerformanceResourceTiming extends PerformanceEntry {
entryType = "resource";
serverTiming = [];
connectEnd = 0;
connectStart = 0;
decodedBodySize = 0;
domainLookupEnd = 0;
domainLookupStart = 0;
encodedBodySize = 0;
fetchStart = 0;
initiatorType = "";
name = "";
nextHopProtocol = "";
redirectEnd = 0;
redirectStart = 0;
requestStart = 0;
responseEnd = 0;
responseStart = 0;
secureConnectionStart = 0;
startTime = 0;
transferSize = 0;
workerStart = 0;
responseStatus = 0;
}
// PerformanceObserverEntryList
export class PerformanceObserverEntryList {
__unenv__ = true;
getEntries() {
return [];
}
getEntriesByName(_name, _type) {
return [];
}
getEntriesByType(type) {
return [];
}
}
// Performance
export class Performance {
__unenv__ = true;
timeOrigin = _timeOrigin;
eventCounts = new Map();
_entries = [];
_resourceTimingBufferSize = 0;
navigation = undefined;
timing = undefined;
timerify(_fn, _options) {
throw createNotImplementedError("Performance.timerify");
}
get nodeTiming() {
return nodeTiming;
}
eventLoopUtilization() {
return {};
}
markResourceTiming() {
// TODO: create a new PerformanceResourceTiming entry
// so that performance.getEntries, getEntriesByName, and getEntriesByType return it
// see: https://nodejs.org/api/perf_hooks.html#performancemarkresourcetimingtiminginfo-requestedurl-initiatortype-global-cachemode-bodyinfo-responsestatus-deliverytype
return new PerformanceResourceTiming("");
}
onresourcetimingbufferfull = null;
now() {
// https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
if (this.timeOrigin === _timeOrigin) {
return _performanceNow();
}
return Date.now() - this.timeOrigin;
}
clearMarks(markName) {
this._entries = markName ? this._entries.filter((e) => e.name !== markName) : this._entries.filter((e) => e.entryType !== "mark");
}
clearMeasures(measureName) {
this._entries = measureName ? this._entries.filter((e) => e.name !== measureName) : this._entries.filter((e) => e.entryType !== "measure");
}
clearResourceTimings() {
this._entries = this._entries.filter((e) => e.entryType !== "resource" || e.entryType !== "navigation");
}
getEntries() {
return this._entries;
}
getEntriesByName(name, type) {
return this._entries.filter((e) => e.name === name && (!type || e.entryType === type));
}
getEntriesByType(type) {
return this._entries.filter((e) => e.entryType === type);
}
mark(name, options) {
// @ts-expect-error constructor is not protected
const entry = new PerformanceMark(name, options);
this._entries.push(entry);
return entry;
}
measure(measureName, startOrMeasureOptions, endMark) {
let start;
let end;
if (typeof startOrMeasureOptions === "string") {
start = this.getEntriesByName(startOrMeasureOptions, "mark")[0]?.startTime;
end = this.getEntriesByName(endMark, "mark")[0]?.startTime;
} else {
start = Number.parseFloat(startOrMeasureOptions?.start) || this.now();
end = Number.parseFloat(startOrMeasureOptions?.end) || this.now();
}
const entry = new PerformanceMeasure(measureName, {
startTime: start,
detail: {
start,
end
}
});
this._entries.push(entry);
return entry;
}
setResourceTimingBufferSize(maxSize) {
this._resourceTimingBufferSize = maxSize;
}
addEventListener(type, listener, options) {
throw createNotImplementedError("Performance.addEventListener");
}
removeEventListener(type, listener, options) {
throw createNotImplementedError("Performance.removeEventListener");
}
dispatchEvent(event) {
throw createNotImplementedError("Performance.dispatchEvent");
}
toJSON() {
return this;
}
}
// PerformanceObserver
export class PerformanceObserver {
__unenv__ = true;
static supportedEntryTypes = [];
_callback = null;
constructor(callback) {
this._callback = callback;
}
takeRecords() {
return [];
}
disconnect() {
throw createNotImplementedError("PerformanceObserver.disconnect");
}
observe(options) {
throw createNotImplementedError("PerformanceObserver.observe");
}
bind(fn) {
return fn;
}
runInAsyncScope(fn, thisArg, ...args) {
return fn.call(thisArg, ...args);
}
asyncId() {
return 0;
}
triggerAsyncId() {
return 0;
}
emitDestroy() {
return this;
}
}
// workerd implements a subset of globalThis.performance (as of last check, only timeOrigin set to 0 + now() implemented)
// We already use performance.now() from globalThis.performance, if provided (see top of this file)
// If we detect this condition, we can just use polyfill instead.
export const performance = globalThis.performance && "addEventListener" in globalThis.performance ? globalThis.performance : new Performance();

View file

@ -0,0 +1 @@
export declare const env: NodeJS.Process["env"];

View file

@ -0,0 +1,40 @@
const _envShim = Object.create(null);
// Keep a reference to the original process to avoid circular references after polyfilling
const originalProcess = globalThis["process"];
const _getEnv = (useShim) => globalThis.__env__ || originalProcess?.env || (useShim ? _envShim : globalThis);
export const env = /* @__PURE__ */ new Proxy(_envShim, {
get(_, prop) {
const env = _getEnv();
return env[prop] ?? _envShim[prop];
},
has(_, prop) {
const env = _getEnv();
return prop in env || prop in _envShim;
},
set(_, prop, value) {
const env = _getEnv(true);
env[prop] = value;
return true;
},
deleteProperty(_, prop) {
const env = _getEnv(true);
delete env[prop];
return true;
},
ownKeys() {
const env = _getEnv();
return Object.keys(env);
},
getOwnPropertyDescriptor(_, prop) {
const env = _getEnv();
if (prop in env) {
return {
value: env[prop],
writable: true,
enumerable: true,
configurable: true
};
}
return undefined;
}
});

View file

@ -0,0 +1,2 @@
// https://nodejs.org/api/process.html#processhrtime
export declare const hrtime: NodeJS.Process["hrtime"];

View file

@ -0,0 +1,21 @@
// https://nodejs.org/api/process.html#processhrtime
export const hrtime = /* @__PURE__ */ Object.assign(function hrtime(startTime) {
const now = Date.now();
// millis to seconds
const seconds = Math.trunc(now / 1e3);
// convert millis to nanos
const nanos = now % 1e3 * 1e6;
if (startTime) {
let diffSeconds = seconds - startTime[0];
let diffNanos = nanos - startTime[0];
if (diffNanos < 0) {
diffSeconds = diffSeconds - 1;
diffNanos = 1e9 + diffNanos;
}
return [diffSeconds, diffNanos];
}
return [seconds, nanos];
}, { bigint: function bigint() {
// Convert milliseconds to nanoseconds
return BigInt(Date.now() * 1e6);
} });

View file

@ -0,0 +1,3 @@
// https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask
// https://nodejs.org/api/process.html#when-to-use-queuemicrotask-vs-processnexttick
export declare const nextTick: NodeJS.Process["nextTick"];

View file

@ -0,0 +1,55 @@
// https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask
// https://nodejs.org/api/process.html#when-to-use-queuemicrotask-vs-processnexttick
export const nextTick = globalThis.queueMicrotask ? (cb, ...args) => {
globalThis.queueMicrotask(cb.bind(undefined, ...args));
} : /* @__PURE__ */ createNextTickWithTimeout();
// Fallback for runtimes not implementing queueMicrotask
function createNextTickWithTimeout() {
let queue = [];
let draining = false;
let currentQueue;
let queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length > 0) {
queue = [...currentQueue, ...queue];
} else {
queueIndex = -1;
}
if (queue.length > 0) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
const timeout = setTimeout(cleanUpNextTick);
draining = true;
let len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex]();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = undefined;
draining = false;
clearTimeout(timeout);
}
const nextTick = (cb, ...args) => {
queue.push(cb.bind(undefined, ...args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue);
}
};
return nextTick;
}

View file

@ -0,0 +1,2 @@
// Extracted from .nvmrc
export declare const NODE_VERSION = "22.14.0";

View file

@ -0,0 +1,2 @@
// Extracted from .nvmrc
export const NODE_VERSION = "22.14.0";

View file

@ -0,0 +1,113 @@
import { EventEmitter } from "node:events";
export declare class Process extends EventEmitter implements NodeJS.Process {
#private;
env: NodeJS.ProcessEnv;
hrtime: NodeJS.Process["hrtime"];
nextTick: NodeJS.Process["nextTick"];
constructor(impl: {
env: NodeJS.ProcessEnv;
hrtime: NodeJS.Process["hrtime"];
nextTick: NodeJS.Process["nextTick"];
});
// --- event emitter ---
emitWarning(warning: unknown, type?: unknown, code?: unknown): void;
emit(...args: any[]): any;
listeners(eventName: string | symbol): any;
get stdin();
get stdout();
get stderr();
chdir(cwd: string): void;
cwd(): string;
// --- dummy props and getters ---
arch: NodeJS.Architecture;
platform: NodeJS.Platform;
argv: string[];
argv0: string;
execArgv: string[];
execPath: string;
title: string;
pid: number;
ppid: number;
get version(): string;
get versions(): NodeJS.Process["versions"];
get allowedNodeEnvironmentFlags();
get sourceMapsEnabled(): boolean;
get debugPort(): number;
get throwDeprecation(): boolean;
get traceDeprecation(): boolean;
get features(): NodeJS.Process["features"];
get release(): NodeJS.Process["release"];
get connected(): boolean;
get config(): NodeJS.Process["config"];
get moduleLoadList(): unknown;
constrainedMemory(): number;
availableMemory(): number;
uptime(): number;
resourceUsage(): NodeJS.ResourceUsage;
// --- noop methods ---
ref();
unref();
// --- unimplemented methods ---
umask(): number;
getBuiltinModule(): any;
getActiveResourcesInfo(): string[];
exit(): never;
reallyExit(): never;
kill(): true;
abort(): never;
dlopen(): void;
setSourceMapsEnabled(): void;
loadEnvFile(): void;
disconnect(): void;
cpuUsage(): NodeJS.CpuUsage;
setUncaughtExceptionCaptureCallback(): void;
hasUncaughtExceptionCaptureCallback(): boolean;
initgroups(): void;
openStdin(): NodeJS.Socket;
assert();
binding();
// --- attached interfaces ---
permission: NodeJS.ProcessPermission;
report: NodeJS.ProcessReport;
finalization: NodeJS.Process["finalization"];
memoryUsage;
// --- undefined props ---
mainModule?: NodeJS.Module | undefined;
domain: undefined;
// optional
send: undefined;
exitCode: undefined;
channel: undefined;
getegid: undefined;
geteuid: undefined;
getgid: undefined;
getgroups: undefined;
getuid: undefined;
setegid: undefined;
seteuid: undefined;
setgid: undefined;
setgroups: undefined;
setuid: undefined;
// internals
_events: undefined;
_eventsCount: undefined;
_exiting: undefined;
_maxListeners: undefined;
_debugEnd: undefined;
_debugProcess: undefined;
_fatalException: undefined;
_getActiveHandles: undefined;
_getActiveRequests: undefined;
_kill: undefined;
_preload_modules: undefined;
_rawDebug: undefined;
_startProfilerIdleNotifier: undefined;
_stopProfilerIdleNotifier: undefined;
_tickCallback: undefined;
_disconnect: undefined;
_handleQueue: undefined;
_pendingMessage: undefined;
_channel: undefined;
_send: undefined;
_linkedBinding: undefined;
}

View file

@ -0,0 +1,238 @@
import { EventEmitter } from "node:events";
import { ReadStream, WriteStream } from "node:tty";
import { notImplemented, createNotImplementedError } from "../../../_internal/utils.mjs";
// node-version.ts is generated at build time
import { NODE_VERSION } from "./node-version.mjs";
export class Process extends EventEmitter {
env;
hrtime;
nextTick;
constructor(impl) {
super();
this.env = impl.env;
this.hrtime = impl.hrtime;
this.nextTick = impl.nextTick;
for (const prop of [...Object.getOwnPropertyNames(Process.prototype), ...Object.getOwnPropertyNames(EventEmitter.prototype)]) {
const value = this[prop];
if (typeof value === "function") {
this[prop] = value.bind(this);
}
}
}
// --- event emitter ---
emitWarning(warning, type, code) {
console.warn(`${code ? `[${code}] ` : ""}${type ? `${type}: ` : ""}${warning}`);
}
emit(...args) {
// @ts-ignore
return super.emit(...args);
}
listeners(eventName) {
return super.listeners(eventName);
}
// --- stdio (lazy initializers) ---
#stdin;
#stdout;
#stderr;
get stdin() {
return this.#stdin ??= new ReadStream(0);
}
get stdout() {
return this.#stdout ??= new WriteStream(1);
}
get stderr() {
return this.#stderr ??= new WriteStream(2);
}
// --- cwd ---
#cwd = "/";
chdir(cwd) {
this.#cwd = cwd;
}
cwd() {
return this.#cwd;
}
// --- dummy props and getters ---
arch = "";
platform = "";
argv = [];
argv0 = "";
execArgv = [];
execPath = "";
title = "";
pid = 200;
ppid = 100;
get version() {
return `v${NODE_VERSION}`;
}
get versions() {
return { node: NODE_VERSION };
}
get allowedNodeEnvironmentFlags() {
return new Set();
}
get sourceMapsEnabled() {
return false;
}
get debugPort() {
return 0;
}
get throwDeprecation() {
return false;
}
get traceDeprecation() {
return false;
}
get features() {
return {};
}
get release() {
return {};
}
get connected() {
return false;
}
get config() {
return {};
}
get moduleLoadList() {
return [];
}
constrainedMemory() {
return 0;
}
availableMemory() {
return 0;
}
uptime() {
return 0;
}
resourceUsage() {
return {};
}
// --- noop methods ---
ref() {
// noop
}
unref() {
// noop
}
// --- unimplemented methods ---
umask() {
throw createNotImplementedError("process.umask");
}
getBuiltinModule() {
return undefined;
}
getActiveResourcesInfo() {
throw createNotImplementedError("process.getActiveResourcesInfo");
}
exit() {
throw createNotImplementedError("process.exit");
}
reallyExit() {
throw createNotImplementedError("process.reallyExit");
}
kill() {
throw createNotImplementedError("process.kill");
}
abort() {
throw createNotImplementedError("process.abort");
}
dlopen() {
throw createNotImplementedError("process.dlopen");
}
setSourceMapsEnabled() {
throw createNotImplementedError("process.setSourceMapsEnabled");
}
loadEnvFile() {
throw createNotImplementedError("process.loadEnvFile");
}
disconnect() {
throw createNotImplementedError("process.disconnect");
}
cpuUsage() {
throw createNotImplementedError("process.cpuUsage");
}
setUncaughtExceptionCaptureCallback() {
throw createNotImplementedError("process.setUncaughtExceptionCaptureCallback");
}
hasUncaughtExceptionCaptureCallback() {
throw createNotImplementedError("process.hasUncaughtExceptionCaptureCallback");
}
initgroups() {
throw createNotImplementedError("process.initgroups");
}
openStdin() {
throw createNotImplementedError("process.openStdin");
}
assert() {
throw createNotImplementedError("process.assert");
}
binding() {
throw createNotImplementedError("process.binding");
}
// --- attached interfaces ---
permission = { has: /* @__PURE__ */ notImplemented("process.permission.has") };
report = {
directory: "",
filename: "",
signal: "SIGUSR2",
compact: false,
reportOnFatalError: false,
reportOnSignal: false,
reportOnUncaughtException: false,
getReport: /* @__PURE__ */ notImplemented("process.report.getReport"),
writeReport: /* @__PURE__ */ notImplemented("process.report.writeReport")
};
finalization = {
register: /* @__PURE__ */ notImplemented("process.finalization.register"),
unregister: /* @__PURE__ */ notImplemented("process.finalization.unregister"),
registerBeforeExit: /* @__PURE__ */ notImplemented("process.finalization.registerBeforeExit")
};
memoryUsage = Object.assign(() => ({
arrayBuffers: 0,
rss: 0,
external: 0,
heapTotal: 0,
heapUsed: 0
}), { rss: () => 0 });
// --- undefined props ---
mainModule = undefined;
domain = undefined;
// optional
send = undefined;
exitCode = undefined;
channel = undefined;
getegid = undefined;
geteuid = undefined;
getgid = undefined;
getgroups = undefined;
getuid = undefined;
setegid = undefined;
seteuid = undefined;
setgid = undefined;
setgroups = undefined;
setuid = undefined;
// internals
_events = undefined;
_eventsCount = undefined;
_exiting = undefined;
_maxListeners = undefined;
_debugEnd = undefined;
_debugProcess = undefined;
_fatalException = undefined;
_getActiveHandles = undefined;
_getActiveRequests = undefined;
_kill = undefined;
_preload_modules = undefined;
_rawDebug = undefined;
_startProfilerIdleNotifier = undefined;
_stopProfilerIdleNotifier = undefined;
_tickCallback = undefined;
_disconnect = undefined;
_handleQueue = undefined;
_pendingMessage = undefined;
_channel = undefined;
_send = undefined;
_linkedBinding = undefined;
}

View file

@ -0,0 +1,59 @@
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
declare const decode: unknown;
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
declare const encode: unknown;
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
declare const toUnicode: unknown;
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
declare const toASCII: unknown;
/*--------------------------------------------------------------------------*/
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
declare const version = "2.3.1";
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
declare const ucs2: {};
/** Define the public API */
declare const punycode: {};
export { version, ucs2, decode, encode, toASCII, toUnicode };
export default punycode;

View file

@ -0,0 +1,410 @@
// Source:
// - https://unpkg.com/punycode@2.3.1/punycode.es6.js
// - https://github.com/mathiasbynens/punycode.js/blob/v2.3.1/punycode.js
/**
Copyright Mathias Bynens <https://mathiasbynens.be/>
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.
*/
/** Highest positive signed 32-bit float value */
const maxInt = 2147483647;
/** Bootstring parameters */
const base = 36;
const tMin = 1;
const tMax = 26;
const skew = 38;
const damp = 700;
const initialBias = 72;
const initialN = 128;
const delimiter = "-";
/** Regular expressions */
const regexPunycode = /^xn--/;
const regexNonASCII = /[^\0-\u007F]/;
const regexSeparators = /[.\u3002\uFF0E\uFF61]/g;
/** Error messages */
const errors = {
overflow: "Overflow: input needs wider integers to process",
"not-basic": "Illegal input >= 0x80 (not a basic code point)",
"invalid-input": "Invalid input"
};
/** Convenience shortcuts */
const baseMinusTMin = base - tMin;
const floor = Math.floor;
const stringFromCharCode = String.fromCharCode;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, callback) {
const result = [];
let length = array.length;
while (length--) {
result[length] = callback(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {String} A new string of characters returned by the callback
* function.
*/
function mapDomain(domain, callback) {
const parts = domain.split("@");
let result = "";
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + "@";
domain = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
domain = domain.replace(regexSeparators, ".");
const labels = domain.split(".");
const encoded = map(labels, callback).join(".");
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
const output = [];
let counter = 0;
const length = string.length;
while (counter < length) {
const value = string.charCodeAt(counter++);
if (value >= 55296 && value <= 56319 && counter < length) {
// It's a high surrogate, and there is a next character.
const extra = string.charCodeAt(counter++);
if ((extra & 64512) == 56320) {
// Low surrogate.
output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
} else {
// It's an unmatched surrogate; only append this code unit, in case the
// next code unit is the high surrogate of a surrogate pair.
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
const ucs2encode = (codePoints) => String.fromCodePoint(...codePoints);
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
const basicToDigit = function(codePoint) {
if (codePoint >= 48 && codePoint < 58) {
return 26 + (codePoint - 48);
}
if (codePoint >= 65 && codePoint < 91) {
return codePoint - 65;
}
if (codePoint >= 97 && codePoint < 123) {
return codePoint - 97;
}
return base;
};
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
const digitToBasic = function(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
// @ts-ignore
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
const adapt = function(delta, numPoints, firstTime) {
let k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
const decode = function(input) {
// Don't use UCS-2.
const output = [];
const inputLength = input.length;
let i = 0;
let n = initialN;
let bias = initialBias;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
let basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (let j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 128) {
error("not-basic");
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (let index = basic > 0 ? basic + 1 : 0; index < inputLength;) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
const oldi = i;
for (let w = 1, k = base;; k += base) {
if (index >= inputLength) {
error("invalid-input");
}
const digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base) {
error("invalid-input");
}
if (digit > floor((maxInt - i) / w)) {
error("overflow");
}
i += digit * w;
const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (digit < t) {
break;
}
const baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error("overflow");
}
w *= baseMinusT;
}
const out = output.length + 1;
bias = adapt(i - oldi, out, oldi === 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error("overflow");
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output.
output.splice(i++, 0, n);
}
return String.fromCodePoint(...output);
};
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
const encode = function(_input) {
const output = [];
// Convert the input in UCS-2 to an array of Unicode code points.
const input = ucs2decode(_input);
// Cache the length.
const inputLength = input.length;
// Initialize the state.
let n = initialN;
let delta = 0;
let bias = initialBias;
// Handle the basic code points.
for (const currentValue of input) {
if (currentValue < 128) {
output.push(stringFromCharCode(currentValue));
}
}
const basicLength = output.length;
let handledCPCount = basicLength;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string with a delimiter unless it's empty.
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
let m = maxInt;
for (const currentValue of input) {
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow.
const handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error("overflow");
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (const currentValue of input) {
if (currentValue < n && ++delta > maxInt) {
error("overflow");
}
if (currentValue === n) {
// Represent delta as a generalized variable-length integer.
let q = delta;
for (let k = base;; k += base) {
const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (q < t) {
break;
}
const qMinusT = q - t;
const baseMinusT = base - t;
output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join("");
};
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
const toUnicode = function(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
});
};
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
const toASCII = function(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string) ? "xn--" + encode(string) : string;
});
};
/*--------------------------------------------------------------------------*/
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
const version = "2.3.1";
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
const ucs2 = {
decode: ucs2decode,
encode: ucs2encode
};
/** Define the public API */
const punycode = {
version,
ucs2,
decode,
encode,
toASCII,
toUnicode
};
export { version, ucs2, decode, encode, toASCII, toUnicode };
export default punycode;

View file

@ -0,0 +1,11 @@
declare const hexTable: string[];
// prettier-ignore
declare const isHexTable: unknown;
/**
* @param {string} str
* @param {Int8Array} noEscapeTable
* @param {string[]} hexTable
* @returns {string}
*/
declare function encodeStr(str: string, noEscapeTable: Int8Array, hexTable: string[]): string;
export { encodeStr, hexTable, isHexTable };

View file

@ -0,0 +1,320 @@
// Source: https://github.com/nodejs/node/blob/v22.7.0/lib/internal/querystring.js
class ERR_INVALID_URI extends URIError {
code = "ERR_INVALID_URI";
constructor() {
super("URI malformed");
}
}
const hexTable = Array.from({ length: 256 });
for (let i = 0; i < 256; ++i) hexTable[i] = "%" + String.prototype.toUpperCase.call((i < 16 ? "0" : "") + Number.prototype.toString.call(i, 16));
// prettier-ignore
const isHexTable = new Int8Array([
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]);
/**
* @param {string} str
* @param {Int8Array} noEscapeTable
* @param {string[]} hexTable
* @returns {string}
*/
function encodeStr(str, noEscapeTable, hexTable) {
const len = str.length;
if (len === 0) return "";
let out = "";
let lastPos = 0;
let i = 0;
outer: for (; i < len; i++) {
let c = String.prototype.charCodeAt.call(str, i);
// ASCII
while (c < 128) {
if (noEscapeTable[c] !== 1) {
if (lastPos < i) out += String.prototype.slice.call(str, lastPos, i);
lastPos = i + 1;
out += hexTable[c];
}
if (++i === len) break outer;
c = String.prototype.charCodeAt.call(str, i);
}
if (lastPos < i) out += String.prototype.slice.call(str, lastPos, i);
// Multi-byte characters ...
if (c < 2048) {
lastPos = i + 1;
out += hexTable[192 | c >> 6] + hexTable[128 | c & 63];
continue;
}
if (c < 55296 || c >= 57344) {
lastPos = i + 1;
out += hexTable[224 | c >> 12] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63];
continue;
}
// Surrogate pair
++i;
// This branch should never happen because all URLSearchParams entries
// should already be converted to USVString. But, included for
// completion's sake anyway.
if (i >= len) throw new ERR_INVALID_URI();
const c2 = String.prototype.charCodeAt.call(str, i) & 1023;
lastPos = i + 1;
c = 65536 + ((c & 1023) << 10 | c2);
out += hexTable[240 | c >> 18] + hexTable[128 | c >> 12 & 63] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63];
}
if (lastPos === 0) return str;
if (lastPos < len) return out + String.prototype.slice.call(str, lastPos);
return out;
}
export { encodeStr, hexTable, isHexTable };

View file

@ -0,0 +1,20 @@
import type nodeReadline from "node:readline";
import type { Abortable } from "node:events";
import { EventEmitter } from "node:events";
export declare class Interface extends EventEmitter implements nodeReadline.Interface {
terminal: boolean;
line: string;
cursor: number;
getPrompt(): string;
setPrompt(prompt: string): void;
prompt(preserveCursor?: boolean | undefined): void;
question(query: string, callback: (answer: string) => void): void;
question(query: string, options: Abortable, callback: (answer: string) => void): void;
resume();
close();
write(data: string | Buffer, key?: nodeReadline.Key | undefined): void;
write(data: string | Buffer | null | undefined, key: nodeReadline.Key): void;
getCursorPos(): nodeReadline.CursorPos;
pause();
[Symbol.asyncIterator](): NodeJS.AsyncIterator<string>;
}

View file

@ -0,0 +1,31 @@
import { EventEmitter } from "node:events";
export class Interface extends EventEmitter {
terminal = false;
line = "";
cursor = 0;
getPrompt() {
return "";
}
setPrompt(prompt) {}
prompt(preserveCursor) {}
question(query, options, callback) {
callback && typeof callback === "function" && callback("");
}
resume() {
return this;
}
close() {}
write(data, key) {}
getCursorPos() {
return {
rows: 0,
cols: 0
};
}
pause() {
return this;
}
async *[Symbol.asyncIterator]() {
yield "";
}
}

View file

@ -0,0 +1,7 @@
import type nodeReadlinePromises from "node:readline/promises";
import type { Abortable } from "node:events";
import { Interface as _Interface } from "../interface.mjs";
export declare class Interface extends _Interface implements nodeReadlinePromises.Interface {
question(query: string): Promise<string>;
question(query: string, options: Abortable): Promise<string>;
}

View file

@ -0,0 +1,6 @@
import { Interface as _Interface } from "../interface.mjs";
export class Interface extends _Interface {
question(query, options) {
return Promise.resolve("");
}
}

View file

@ -0,0 +1,10 @@
import type nodeReadlinePromises from "node:readline/promises";
import type { Direction } from "node:readline";
export declare class Readline implements nodeReadlinePromises.Readline {
clearLine(dir: Direction);
clearScreenDown();
commit(): Promise<void>;
cursorTo(x: number, y?: number | undefined);
moveCursor(dx: number, dy: number);
rollback();
}

View file

@ -0,0 +1,20 @@
export class Readline {
clearLine(dir) {
return this;
}
clearScreenDown() {
return this;
}
commit() {
return Promise.resolve();
}
cursorTo(x, y) {
return this;
}
moveCursor(dx, dy) {
return this;
}
rollback() {
return this;
}
}

View file

@ -0,0 +1,3 @@
import type nodeStream from "node:stream";
export declare const _Duplex: unknown;
export declare const Duplex: typeof nodeStream.Duplex;

View file

@ -0,0 +1,19 @@
import { mergeFns } from "../../../_internal/utils.mjs";
import { Readable } from "./readable.mjs";
import { Writable } from "./writable.mjs";
const __Duplex = class {
allowHalfOpen = true;
_destroy;
constructor(readable = new Readable(), writable = new Writable()) {
Object.assign(this, readable);
Object.assign(this, writable);
this._destroy = mergeFns(readable._destroy, writable._destroy);
}
};
function getDuplex() {
Object.assign(__Duplex.prototype, Readable.prototype);
Object.assign(__Duplex.prototype, Writable.prototype);
return __Duplex;
}
export const _Duplex = /* @__PURE__ */ getDuplex();
export const Duplex = globalThis.Duplex || _Duplex;

View file

@ -0,0 +1,67 @@
import type nodeStream from "node:stream";
import type { BufferEncoding, Callback } from "../../../_internal/types.mjs";
import { EventEmitter } from "node:events";
// Docs: https://nodejs.org/api/stream.html#stream_readable_streams
// Implementation: https://github.com/nodejs/node/blob/master/lib/internal/streams/readable.js
interface ArrayOptions {
/** the maximum concurrent invocations of `fn` to call on the stream at once. **Default: 1**. */
concurrency?: number;
/** allows destroying the stream if the signal is aborted. */
signal?: AbortSignal;
}
export declare class _Readable extends EventEmitter implements nodeStream.Readable {
__unenv__: unknown;
readonly readableEncoding: BufferEncoding | null;
readonly readableEnded: boolean;
readonly readableFlowing: boolean | null;
readonly readableHighWaterMark: number;
readonly readableLength: number;
readonly readableObjectMode: boolean;
readonly readableAborted: boolean;
readonly readableDidRead: boolean;
readonly closed: boolean;
readonly errored: Error | null;
readable: boolean;
destroyed: boolean;
static from(_iterable: Iterable<any> | AsyncIterable<any>, options?: nodeStream.ReadableOptions);
constructor(_opts?: nodeStream.ReadableOptions);
_read(_size: number);
read(_size?: number);
setEncoding(_encoding: BufferEncoding);
pause();
resume();
isPaused(): boolean;
unpipe(_destination?: any);
unshift(_chunk: any, _encoding?: BufferEncoding);
wrap(_oldStream: any);
push(_chunk: any, _encoding?: BufferEncoding): boolean;
_destroy(_error?: any, _callback?: Callback<any>);
destroy(error?: Error);
pipe<T>(_destenition: T, _options?: {
end?: boolean;
}): T;
compose<T extends NodeJS.ReadableStream>(stream: T | ((source: any) => void) | Iterable<T> | AsyncIterable<T>, options?: {
signal: AbortSignal;
} | undefined): T;
[Symbol.asyncDispose]();
// eslint-disable-next-line require-yield
[Symbol.asyncIterator](): NodeJS.AsyncIterator<any>;
iterator(options?: {
destroyOnReturn?: boolean | undefined;
} | undefined): NodeJS.AsyncIterator<any>;
map(fn: (data: any, options?: Pick<ArrayOptions, "signal"> | undefined) => any, options?: ArrayOptions | undefined): nodeStream.Readable;
filter(fn: (data: any, options?: Pick<ArrayOptions, "signal"> | undefined) => boolean, options?: ArrayOptions | undefined): nodeStream.Readable;
forEach(fn: (data: any, options?: Pick<ArrayOptions, "signal"> | undefined) => void | Promise<void>, options?: ArrayOptions | undefined): Promise<void>;
reduce(fn: (accumulator: any, data: any, options?: Pick<ArrayOptions, "signal"> | undefined) => any, initialValue?: any, options?: ArrayOptions | undefined): Promise<any>;
find(fn: (data: any, options?: Pick<ArrayOptions, "signal"> | undefined) => boolean, options?: ArrayOptions | undefined): Promise<any>;
findIndex(fn: (data: any, options?: Pick<ArrayOptions, "signal"> | undefined) => boolean, options?: ArrayOptions | undefined): Promise<number>;
some(fn: (data: any, options?: Pick<ArrayOptions, "signal"> | undefined) => boolean, options?: ArrayOptions | undefined): Promise<boolean>;
toArray(options?: Pick<ArrayOptions, "signal"> | undefined): Promise<any[]>;
every(fn: (data: any, options?: Pick<ArrayOptions, "signal"> | undefined) => boolean | Promise<boolean>, options?: ArrayOptions | undefined): Promise<boolean>;
flatMap(fn: (data: any, options?: Pick<ArrayOptions, "signal"> | undefined) => any, options?: ArrayOptions | undefined): nodeStream.Readable;
drop(limit: number, options?: Pick<ArrayOptions, "signal"> | undefined): nodeStream.Readable;
take(limit: number, options?: Pick<ArrayOptions, "signal"> | undefined): nodeStream.Readable;
asIndexedPairs(options?: Pick<ArrayOptions, "signal"> | undefined): nodeStream.Readable;
}
export declare const Readable: typeof nodeStream.Readable;
export {};

View file

@ -0,0 +1,112 @@
import { createNotImplementedError } from "../../../_internal/utils.mjs";
import { EventEmitter } from "node:events";
export class _Readable extends EventEmitter {
__unenv__ = true;
readableEncoding = null;
readableEnded = true;
readableFlowing = false;
readableHighWaterMark = 0;
readableLength = 0;
readableObjectMode = false;
readableAborted = false;
readableDidRead = false;
closed = false;
errored = null;
readable = false;
destroyed = false;
static from(_iterable, options) {
return new _Readable(options);
}
constructor(_opts) {
super();
}
_read(_size) {}
read(_size) {}
setEncoding(_encoding) {
return this;
}
pause() {
return this;
}
resume() {
return this;
}
isPaused() {
return true;
}
unpipe(_destination) {
return this;
}
unshift(_chunk, _encoding) {}
wrap(_oldStream) {
return this;
}
push(_chunk, _encoding) {
return false;
}
_destroy(_error, _callback) {
this.removeAllListeners();
}
destroy(error) {
this.destroyed = true;
this._destroy(error);
return this;
}
pipe(_destenition, _options) {
return {};
}
compose(stream, options) {
throw new Error("[unenv] Method not implemented.");
}
[Symbol.asyncDispose]() {
this.destroy();
return Promise.resolve();
}
// eslint-disable-next-line require-yield
async *[Symbol.asyncIterator]() {
throw createNotImplementedError("Readable.asyncIterator");
}
iterator(options) {
throw createNotImplementedError("Readable.iterator");
}
map(fn, options) {
throw createNotImplementedError("Readable.map");
}
filter(fn, options) {
throw createNotImplementedError("Readable.filter");
}
forEach(fn, options) {
throw createNotImplementedError("Readable.forEach");
}
reduce(fn, initialValue, options) {
throw createNotImplementedError("Readable.reduce");
}
find(fn, options) {
throw createNotImplementedError("Readable.find");
}
findIndex(fn, options) {
throw createNotImplementedError("Readable.findIndex");
}
some(fn, options) {
throw createNotImplementedError("Readable.some");
}
toArray(options) {
throw createNotImplementedError("Readable.toArray");
}
every(fn, options) {
throw createNotImplementedError("Readable.every");
}
flatMap(fn, options) {
throw createNotImplementedError("Readable.flatMap");
}
drop(limit, options) {
throw createNotImplementedError("Readable.drop");
}
take(limit, options) {
throw createNotImplementedError("Readable.take");
}
asIndexedPairs(options) {
throw createNotImplementedError("Readable.asIndexedPairs");
}
}
export const Readable = globalThis.Readable || _Readable;

View file

@ -0,0 +1,10 @@
import type nodeStream from "node:stream";
import { Duplex } from "./duplex.mjs";
// Docs: https://nodejs.org/api/stream.html#stream_duplex_and_transform_streams
// Implementation: https://github.com/nodejs/node/blob/master/lib/internal/streams/transform.js
export declare class _Transform extends Duplex implements nodeStream.Transform {
readonly __unenv__: true;
_transform(chunk: any, encoding: globalThis.BufferEncoding, callback: nodeStream.TransformCallback): void;
_flush(callback: nodeStream.TransformCallback): void;
}
export declare const Transform: typeof nodeStream.Transform;

View file

@ -0,0 +1,9 @@
import { Duplex } from "./duplex.mjs";
// Docs: https://nodejs.org/api/stream.html#stream_duplex_and_transform_streams
// Implementation: https://github.com/nodejs/node/blob/master/lib/internal/streams/transform.js
export class _Transform extends Duplex {
__unenv__ = true;
_transform(chunk, encoding, callback) {}
_flush(callback) {}
}
export const Transform = globalThis.Transform || _Transform;

View file

@ -0,0 +1,2 @@
import type nodeStream from "node:stream";
export declare const Writable: typeof nodeStream.Writable;

View file

@ -0,0 +1,87 @@
import { EventEmitter } from "node:events";
// Docs: https://nodejs.org/api/stream.html#stream_writable_streams
// Implementation: https://github.com/nodejs/node/blob/master/lib/internal/streams/writable.js
class _Writable extends EventEmitter {
__unenv__ = true;
writable = true;
writableEnded = false;
writableFinished = false;
writableHighWaterMark = 0;
writableLength = 0;
writableObjectMode = false;
writableCorked = 0;
closed = false;
errored = null;
writableNeedDrain = false;
destroyed = false;
_data;
_encoding = "utf-8";
constructor(_opts) {
super();
}
pipe(_destenition, _options) {
return {};
}
_write(chunk, encoding, callback) {
if (this.writableEnded) {
if (callback) {
callback();
}
return;
}
if (this._data === undefined) {
this._data = chunk;
} else {
const a = typeof this._data === "string" ? Buffer.from(this._data, this._encoding || encoding || "utf8") : this._data;
const b = typeof chunk === "string" ? Buffer.from(chunk, encoding || this._encoding || "utf8") : chunk;
this._data = Buffer.concat([a, b]);
}
this._encoding = encoding;
if (callback) {
callback();
}
}
_writev(_chunks, _callback) {}
_destroy(_error, _callback) {}
_final(_callback) {}
write(chunk, arg2, arg3) {
const encoding = typeof arg2 === "string" ? this._encoding : "utf-8";
const cb = typeof arg2 === "function" ? arg2 : typeof arg3 === "function" ? arg3 : undefined;
this._write(chunk, encoding, cb);
return true;
}
setDefaultEncoding(_encoding) {
return this;
}
end(arg1, arg2, arg3) {
const callback = typeof arg1 === "function" ? arg1 : typeof arg2 === "function" ? arg2 : typeof arg3 === "function" ? arg3 : undefined;
if (this.writableEnded) {
if (callback) {
callback();
}
return this;
}
const data = arg1 === callback ? undefined : arg1;
if (data) {
const encoding = arg2 === callback ? undefined : arg2;
this.write(data, encoding, callback);
}
this.writableEnded = true;
this.writableFinished = true;
this.emit("close");
this.emit("finish");
return this;
}
cork() {}
uncork() {}
destroy(_error) {
this.destroyed = true;
delete this._data;
this.removeAllListeners();
return this;
}
compose(stream, options) {
throw new Error("[h3] Method not implemented.");
}
}
export const Writable = globalThis.Writable || _Writable;

View file

@ -0,0 +1,9 @@
export declare class Immediate<TArgs extends any[]> implements NodeJS.Immediate {
_onImmediate: (...args: TArgs) => void;
private _timeout?;
constructor(callback: (...args: TArgs) => void, args: TArgs);
ref(): this;
unref(): this;
hasRef(): boolean;
[Symbol.dispose]();
}

View file

@ -0,0 +1,28 @@
export class Immediate {
_onImmediate;
_timeout;
constructor(callback, args) {
this._onImmediate = callback;
if ("setTimeout" in globalThis) {
this._timeout = setTimeout(callback, 0, ...args);
} else {
callback(...args);
}
}
ref() {
this._timeout?.ref();
return this;
}
unref() {
this._timeout?.unref();
return this;
}
hasRef() {
return this._timeout?.hasRef() ?? false;
}
[Symbol.dispose]() {
if ("clearTimeout" in globalThis) {
clearTimeout(this._timeout);
}
}
}

View file

@ -0,0 +1,6 @@
import timers from "node:timers/promises";
import type { TimerOptions } from "node:timers";
export declare class Scheduler implements timers.Scheduler {
wait(delay?: number | undefined, options?: Pick<TimerOptions, "signal"> | undefined);
yield();
}

View file

@ -0,0 +1,10 @@
import { setTimeoutFallbackPromises as setTimeout } from "./set-timeout.mjs";
import { setImmediateFallbackPromises as setImmediate } from "./set-immediate.mjs";
export class Scheduler {
wait(delay, options) {
return setTimeout(delay, undefined, options);
}
yield() {
return setImmediate();
}
}

View file

@ -0,0 +1,3 @@
export declare function setImmediateFallbackPromises<T = void>(value?: T): Promise<T>;
export declare function setImmediateFallback<TArgs extends any[]>(callback: (...args: TArgs) => void, ...args: TArgs): NodeJS.Immediate;
export declare function clearImmediateFallback(immediate: NodeJS.Immediate | undefined);

View file

@ -0,0 +1,13 @@
import { Immediate } from "./immediate.mjs";
export function setImmediateFallbackPromises(value) {
return new Promise((res) => {
res(value);
});
}
export function setImmediateFallback(callback, ...args) {
return new Immediate(callback, args);
}
setImmediateFallback.__promisify__ = setImmediateFallbackPromises;
export function clearImmediateFallback(immediate) {
immediate?.[Symbol.dispose]();
}

View file

@ -0,0 +1,2 @@
export declare function setIntervalFallbackPromises<T = void>(delay?: number, value?: T): NodeJS.AsyncIterator<T>;
export declare function setIntervalFallback(callback: (args: void) => void, ms?: number): NodeJS.Timeout;

View file

@ -0,0 +1,8 @@
import { Timeout } from "./timeout.mjs";
export async function* setIntervalFallbackPromises(delay, value) {
yield value;
}
export function setIntervalFallback(callback, ms, ...args) {
return new Timeout(callback, args);
}
setIntervalFallback.__promisify__ = setIntervalFallbackPromises;

View file

@ -0,0 +1,3 @@
import type nodeTimers from "node:timers";
export declare function setTimeoutFallbackPromises<T = void>(delay?: number, value?: T, options?: nodeTimers.TimerOptions): Promise<T>;
export declare function setTimeoutFallback(callback: TimerHandler, ms?: number): NodeJS.Timeout;

View file

@ -0,0 +1,11 @@
import { Timeout } from "./timeout.mjs";
export function setTimeoutFallbackPromises(delay, value, options) {
return new Promise((res) => {
// NOTE: we are ignoring options?.signal? as promise is immediately resolved
res(value);
});
}
export function setTimeoutFallback(callback, ms, ...args) {
return new Timeout(callback, args);
}
setTimeoutFallback.__promisify__ = setTimeoutFallbackPromises;

Some files were not shown because too many files have changed in this diff Show more