WIP: bootstrap and partial real Solana watcher implementation

This commit is contained in:
2026-08-16 09:17:45 +00:00
commit dc23412c3f
7232 changed files with 1687637 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
import Dispatcher from './dispatcher'
import RetryHandler from './retry-handler'
export default RetryAgent
declare class RetryAgent extends Dispatcher {
constructor (dispatcher: Dispatcher, options?: RetryHandler.RetryOptions)
}

View File

@@ -0,0 +1,179 @@
'use strict'
const { describe, test } = require('node:test')
const assert = require('node:assert')
const pino = require('../')
const descLevels = {
trace: 60,
debug: 50,
info: 40,
warn: 30,
error: 20,
fatal: 10
}
const ascLevels = {
trace: 10,
debug: 20,
info: 30,
warn: 40,
error: 50,
fatal: 60
}
describe('Default levels suite', () => {
test('can check if current level enabled', async () => {
const log = pino({ level: 'debug' })
assert.equal(true, log.isLevelEnabled('debug'))
})
test('can check if level enabled after level set', async () => {
const log = pino()
assert.equal(false, log.isLevelEnabled('debug'))
log.level = 'debug'
assert.equal(true, log.isLevelEnabled('debug'))
})
test('can check if higher level enabled', async () => {
const log = pino({ level: 'debug' })
assert.equal(true, log.isLevelEnabled('error'))
})
test('can check if lower level is disabled', async () => {
const log = pino({ level: 'error' })
assert.equal(false, log.isLevelEnabled('trace'))
})
test('ASC: can check if child has current level enabled', async () => {
const log = pino().child({}, { level: 'debug' })
assert.equal(true, log.isLevelEnabled('debug'))
assert.equal(true, log.isLevelEnabled('error'))
assert.equal(false, log.isLevelEnabled('trace'))
})
test('can check if custom level is enabled', async () => {
const log = pino({
customLevels: { foo: 35 },
level: 'debug'
})
assert.equal(true, log.isLevelEnabled('foo'))
assert.equal(true, log.isLevelEnabled('error'))
assert.equal(false, log.isLevelEnabled('trace'))
})
})
describe('Ascending levels suite', () => {
const customLevels = ascLevels
const levelComparison = 'ASC'
test('can check if current level enabled', async () => {
const log = pino({ level: 'debug', levelComparison, customLevels, useOnlyCustomLevels: true })
assert.equal(true, log.isLevelEnabled('debug'))
})
test('can check if level enabled after level set', async () => {
const log = pino({ levelComparison, customLevels, useOnlyCustomLevels: true })
assert.equal(false, log.isLevelEnabled('debug'))
log.level = 'debug'
assert.equal(true, log.isLevelEnabled('debug'))
})
test('can check if higher level enabled', async () => {
const log = pino({ level: 'debug', levelComparison, customLevels, useOnlyCustomLevels: true })
assert.equal(true, log.isLevelEnabled('error'))
})
test('can check if lower level is disabled', async () => {
const log = pino({ level: 'error', customLevels, useOnlyCustomLevels: true })
assert.equal(false, log.isLevelEnabled('trace'))
})
test('can check if child has current level enabled', async () => {
const log = pino().child({ levelComparison, customLevels, useOnlyCustomLevels: true }, { level: 'debug' })
assert.equal(true, log.isLevelEnabled('debug'))
assert.equal(true, log.isLevelEnabled('error'))
assert.equal(false, log.isLevelEnabled('trace'))
})
test('can check if custom level is enabled', async () => {
const log = pino({
levelComparison,
useOnlyCustomLevels: true,
customLevels: { foo: 35, ...customLevels },
level: 'debug'
})
assert.equal(true, log.isLevelEnabled('foo'))
assert.equal(true, log.isLevelEnabled('error'))
assert.equal(false, log.isLevelEnabled('trace'))
})
})
describe('Descending levels suite', () => {
const customLevels = descLevels
const levelComparison = 'DESC'
test('can check if current level enabled', async () => {
const log = pino({ level: 'debug', levelComparison, customLevels, useOnlyCustomLevels: true })
assert.equal(true, log.isLevelEnabled('debug'))
})
test('can check if level enabled after level set', async () => {
const log = pino({ levelComparison, customLevels, useOnlyCustomLevels: true })
assert.equal(false, log.isLevelEnabled('debug'))
log.level = 'debug'
assert.equal(true, log.isLevelEnabled('debug'))
})
test('can check if higher level enabled', async () => {
const log = pino({ level: 'debug', levelComparison, customLevels, useOnlyCustomLevels: true })
assert.equal(true, log.isLevelEnabled('error'))
})
test('can check if lower level is disabled', async () => {
const log = pino({ level: 'error', levelComparison, customLevels, useOnlyCustomLevels: true })
assert.equal(false, log.isLevelEnabled('trace'))
})
test('can check if child has current level enabled', async () => {
const log = pino({ levelComparison, customLevels, useOnlyCustomLevels: true }).child({}, { level: 'debug' })
assert.equal(true, log.isLevelEnabled('debug'))
assert.equal(true, log.isLevelEnabled('error'))
assert.equal(false, log.isLevelEnabled('trace'))
})
test('can check if custom level is enabled', async () => {
const log = pino({
levelComparison,
customLevels: { foo: 35, ...customLevels },
useOnlyCustomLevels: true,
level: 'debug'
})
assert.equal(true, log.isLevelEnabled('foo'))
assert.equal(true, log.isLevelEnabled('error'))
assert.equal(false, log.isLevelEnabled('trace'))
})
})
describe('Custom levels comparison', () => {
test('Custom comparison returns true cause level is enabled', async () => {
const log = pino({ level: 'error', levelComparison: () => true })
assert.equal(true, log.isLevelEnabled('debug'))
})
test('Custom comparison returns false cause level is disabled', async () => {
const log = pino({ level: 'error', levelComparison: () => false })
assert.equal(false, log.isLevelEnabled('debug'))
})
test('Custom comparison returns true cause child level is enabled', async () => {
const log = pino({ levelComparison: () => true }).child({ level: 'error' })
assert.equal(true, log.isLevelEnabled('debug'))
})
test('Custom comparison returns false cause child level is disabled', async () => {
const log = pino({ levelComparison: () => false }).child({ level: 'error' })
assert.equal(false, log.isLevelEnabled('debug'))
})
})

View File

@@ -0,0 +1,4 @@
function _iterableToArray(r) {
if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
}
module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,289 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EXPANSION_MAX_LENGTH = exports.EXPANSION_MAX = void 0;
exports.expand = expand;
const balanced_match_1 = require("balanced-match");
const escSlash = '\0SLASH' + Math.random() + '\0';
const escOpen = '\0OPEN' + Math.random() + '\0';
const escClose = '\0CLOSE' + Math.random() + '\0';
const escComma = '\0COMMA' + Math.random() + '\0';
const escPeriod = '\0PERIOD' + Math.random() + '\0';
const escSlashPattern = new RegExp(escSlash, 'g');
const escOpenPattern = new RegExp(escOpen, 'g');
const escClosePattern = new RegExp(escClose, 'g');
const escCommaPattern = new RegExp(escComma, 'g');
const escPeriodPattern = new RegExp(escPeriod, 'g');
const slashPattern = /\\\\/g;
const openPattern = /\\{/g;
const closePattern = /\\}/g;
const commaPattern = /\\,/g;
const periodPattern = /\\\./g;
exports.EXPANSION_MAX = 100_000;
// `EXPANSION_MAX` caps the *number* of expansions, but not their length. An
// input like `'{a,b}'.repeat(1500)` stays under that count - its output is
// truncated to 100k results - while making every result ~1500 characters
// long. The result set, and the intermediate arrays built while combining
// brace sets, then grow large enough to exhaust memory and crash the process
// (CVE-2026-14257). `EXPANSION_MAX_LENGTH` bounds the total number of
// characters the accumulator may hold at any point, so memory stays flat no
// matter how many brace groups are chained. The limit sits well above any
// realistic expansion (100k results hitting `EXPANSION_MAX` measure ~1M
// characters) so legitimate input is unaffected.
exports.EXPANSION_MAX_LENGTH = 4_000_000;
function numeric(str) {
return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
}
function escapeBraces(str) {
return str
.replace(slashPattern, escSlash)
.replace(openPattern, escOpen)
.replace(closePattern, escClose)
.replace(commaPattern, escComma)
.replace(periodPattern, escPeriod);
}
function unescapeBraces(str) {
return str
.replace(escSlashPattern, '\\')
.replace(escOpenPattern, '{')
.replace(escClosePattern, '}')
.replace(escCommaPattern, ',')
.replace(escPeriodPattern, '.');
}
/**
* Basically just str.split(","), but handling cases
* where we have nested braced sections, which should be
* treated as individual members, like {a,{b,c},d}
*/
function parseCommaParts(str) {
if (!str) {
return [''];
}
const parts = [];
const m = (0, balanced_match_1.balanced)('{', '}', str);
if (!m) {
return str.split(',');
}
const { pre, body, post } = m;
const p = pre.split(',');
p[p.length - 1] += '{' + body + '}';
const postParts = parseCommaParts(post);
if (post.length) {
;
p[p.length - 1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expand(str, options = {}) {
if (!str) {
return [];
}
const { max = exports.EXPANSION_MAX, maxLength = exports.EXPANSION_MAX_LENGTH } = options;
// I don't know why Bash 4.3 does this, but it does.
// Anything starting with {} will have the first two bytes preserved
// but *only* at the top level, so {},a}b will not expand to anything,
// but a{},b}c will be expanded to [a}c,abc].
// One could argue that this is a bug in Bash, but since the goal of
// this module is to match Bash's rules, we escape a leading {}
if (str.slice(0, 2) === '{}') {
str = '\\{\\}' + str.slice(2);
}
return expand_(escapeBraces(str), max, maxLength, true).map(unescapeBraces);
}
function embrace(str) {
return '{' + str + '}';
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i, y) {
return i <= y;
}
function gte(i, y) {
return i >= y;
}
// Build `{ acc[a] + pre + values[v] }` for every combination, capping the
// number of results at `max` and the total number of characters at `maxLength`.
// This is the one place output grows, so bounding it here keeps the single
// accumulator - and therefore memory - flat regardless of how many brace groups
// are combined (CVE-2026-14257).
function combine(acc, pre, values, max, maxLength, dropEmpties) {
const out = [];
let length = 0;
for (let a = 0; a < acc.length; a++) {
for (let v = 0; v < values.length; v++) {
if (out.length >= max)
return out;
const expansion = acc[a] + pre + values[v];
// Bash drops empty results at the top level. Skip them before they count
// against `max`, so `max` bounds the number of *kept* results.
if (dropEmpties && !expansion)
continue;
if (length + expansion.length > maxLength)
return out;
out.push(expansion);
length += expansion.length;
}
}
return out;
}
// The expansion values of a single numeric (`1..5`) or alphabetic (`a..e..2`)
// sequence body.
function expandSequence(body, isAlphaSequence, max, maxLength) {
const n = body.split(/\.\./);
const N = [];
// A sequence body always splits into two or three parts, but the compiler
// can't know that.
/* c8 ignore start */
if (n[0] === undefined || n[1] === undefined) {
return N;
}
/* c8 ignore stop */
const x = numeric(n[0]);
const y = numeric(n[1]);
const width = Math.max(n[0].length, n[1].length);
let incr = n.length === 3 && n[2] !== undefined ?
Math.max(Math.abs(numeric(n[2])), 1)
: 1;
let test = lte;
const reverse = y < x;
if (reverse) {
incr *= -1;
test = gte;
}
const pad = n.some(isPadded);
let length = 0;
for (let i = x; test(i, y) && N.length < max; i += incr) {
let c;
if (isAlphaSequence) {
c = String.fromCharCode(i);
if (c === '\\') {
c = '';
}
}
else {
c = String(i);
if (pad) {
const need = width - c.length;
if (need > 0) {
const z = new Array(need + 1).join('0');
if (i < 0) {
c = '-' + z + c.slice(1);
}
else {
c = z + c;
}
}
}
}
if (length + c.length > maxLength)
break;
N.push(c);
length += c.length;
}
return N;
}
function expand_(str, max, maxLength, isTop) {
// Consume the string's top-level brace groups left to right, threading a
// running set of combined prefixes (`acc`). Expanding the tail iteratively -
// rather than recursing on `m.post` once per group - keeps the native stack
// depth constant, so deeply chained input (`'{a,b}'.repeat(3000)`) can no
// longer overflow the stack, and leaves a single accumulator whose size
// `maxLength` bounds directly (CVE-2026-14257).
let acc = [''];
// Bash drops empty results, but only when the *first* top-level group is a
// comma set - a sequence like `{a..\}` may legitimately yield ''. The drop
// is on the final strings, so it is applied to whichever `combine` produces
// them (the one with no brace set left in the tail).
let dropEmpties = false;
let firstGroup = true;
for (;;) {
const m = (0, balanced_match_1.balanced)('{', '}', str);
// No brace set left: the rest of the string is literal.
if (!m) {
return combine(acc, str, [''], max, maxLength, dropEmpties);
}
// no need to expand pre, since it is guaranteed to be free of brace-sets
const pre = m.pre;
if (/\$$/.test(pre)) {
acc = combine(acc, pre + '{' + m.body + '}', [''], max, maxLength, dropEmpties && !m.post.length);
firstGroup = false;
if (!m.post.length)
break;
str = m.post;
continue;
}
const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
const isSequence = isNumericSequence || isAlphaSequence;
const isOptions = m.body.indexOf(',') >= 0;
if (!isSequence && !isOptions) {
// {a},b}
if (m.post.match(/,(?!,).*\}/)) {
str = m.pre + '{' + m.body + escClose + m.post;
isTop = true;
continue;
}
// Nothing here expands, so the whole remaining string is literal.
return combine(acc, pre + '{' + m.body + '}' + m.post, [''], max, maxLength, dropEmpties);
}
if (firstGroup) {
dropEmpties = isTop && !isSequence;
firstGroup = false;
}
let values;
if (isSequence) {
values = expandSequence(m.body, isAlphaSequence, max, maxLength);
}
else {
let n = parseCommaParts(m.body);
if (n.length === 1 && n[0] !== undefined) {
// x{{a,b}}y ==> x{a}y x{b}y
n = expand_(n[0], max, maxLength, false).map(embrace);
//XXX is this necessary? Can't seem to hit it in tests.
/* c8 ignore start */
if (n.length === 1) {
acc = combine(acc, pre + n[0], [''], max, maxLength, dropEmpties && !m.post.length);
if (!m.post.length)
break;
str = m.post;
continue;
}
/* c8 ignore stop */
}
// Values that `combine` is going to drop as empty produce no result, so
// they must not count against `max` - otherwise `{a,,b}` with `max: 2`
// would stop at `['a', '']` and yield one result instead of two. Skipping
// them outright keeps `values` bounded while leaving `max` a bound on
// *kept* results.
let dropsEmpties = dropEmpties && !m.post.length && !pre;
for (let d = 0; dropsEmpties && d < acc.length; d++) {
if (acc[d]) {
dropsEmpties = false;
}
}
values = [];
let valuesLength = 0;
outer: for (let j = 0; j < n.length; j++) {
const expanded = expand_(n[j], max, maxLength, false);
for (let k = 0; k < expanded.length; k++) {
const v = expanded[k];
if (dropsEmpties && !v)
continue;
if (values.length >= max || valuesLength + v.length > maxLength) {
break outer;
}
values.push(v);
valuesLength += v.length;
}
}
}
acc = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length);
if (!m.post.length)
break;
str = m.post;
}
return acc;
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,5 @@
'use strict'
const compareBuild = require('./compare-build')
const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
module.exports = sort

View File

@@ -0,0 +1,9 @@
import { SolanaError } from './error';
export declare function getSolanaErrorFromInstructionError(
/**
* The index of the instruction inside the transaction.
*/
index: bigint | number, instructionError: string | {
[key: string]: unknown;
}): SolanaError;
//# sourceMappingURL=instruction-error.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"nist.d.ts","sourceRoot":"","sources":["src/nist.ts"],"names":[],"mappings":"AAOA,OAAO,EAAe,KAAK,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAgB,KAAK,SAAS,EAAE,MAAM,6BAA6B,CAAC;AA+E3E,2EAA2E;AAC3E,eAAO,MAAM,IAAI,EAAE,iBAGlB,CAAC;AACF,mEAAmE;AACnE,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,MAAM,CAkBtC,CAAC;AAUL,+DAA+D;AAC/D,eAAO,MAAM,IAAI,EAAE,iBAGlB,CAAC;AACF,mEAAmE;AACnE,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,MAAM,CAkBtC,CAAC;AAWL,+DAA+D;AAC/D,eAAO,MAAM,IAAI,EAAE,iBAGlB,CAAC;AAEF,gEAAgE;AAChE,eAAO,MAAM,SAAS,EAAE,OAAO,IAAW,CAAC;AAC3C,gEAAgE;AAChE,eAAO,MAAM,SAAS,EAAE,OAAO,IAAW,CAAC;AAC3C,gEAAgE;AAChE,eAAO,MAAM,SAAS,EAAE,OAAO,IAAW,CAAC;AAE3C,mEAAmE;AACnE,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,MAAM,CAkBtC,CAAC"}

View File

@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.groupHash = exports.findGroupHash = exports.jubjub = void 0;
/**
* @deprecated
* @module
*/
const misc_ts_1 = require("./misc.js");
/** @deprecated use `import { jubjub } from '@noble/curves/misc.js';` */
exports.jubjub = misc_ts_1.jubjub;
/** @deprecated use `import { jubjub_findGroupHash } from '@noble/curves/misc.js';` */
exports.findGroupHash = misc_ts_1.jubjub_findGroupHash;
/** @deprecated use `import { jubjub_groupHash } from '@noble/curves/misc.js';` */
exports.groupHash = misc_ts_1.jubjub_groupHash;
//# sourceMappingURL=jubjub.js.map

View File

@@ -0,0 +1,24 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2020" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />

View File

@@ -0,0 +1,2 @@
import type * as ts from 'typescript';
export declare function typeDeclaredInFile(relativePath: string | undefined, declarationFiles: ts.SourceFile[], program: ts.Program): boolean;

View File

@@ -0,0 +1,476 @@
'use strict';
const events = require('events');
const jayson = require('../');
const utils = require('../utils');
/**
* Constructor for a Jayson Server
* @class Server
* @extends require('events').EventEmitter
* @param {Object<String,Function>} [methods] Methods to add
* @param {Object} [options]
* @param {Array|Object} [options.params] Passed to Jayson.Method as an option when created
* @param {Boolean} [options.useContext=false] Passed to Jayson.Method as an option when created
* @param {Function} [options.reviver] Reviver function for JSON
* @param {Function} [options.replacer] Replacer function for JSON
* @param {Function} [options.methodConstructor] Methods will be made instances of this class
* @param {String} [options.encoding="utf8"] Encoding to use
* @param {Number} [options.version=2] JSON-RPC version to use (1|2)
* @param {Number} [options.maxBatchLength=Infinity] Maximum requests allowed in a batch
* @param {Function} [options.router] Function to use for routing methods
* @property {Object} options A reference to the internal options object that can be modified directly
* @property {Object} errorMessages Map of error code to error message pairs that will be used in server responses
* @property {ServerHttp} http HTTP interface constructor
* @property {ServerHttps} https HTTPS interface constructor
* @property {ServerTcp} tcp TCP interface constructor
* @property {ServerTls} tls TLS interface constructor
* @property {Middleware} middleware Middleware generator function
* @return {Server}
*/
const Server = function(methods, options) {
if(!(this instanceof Server)) {
return new Server(methods, options);
}
const defaults = {
reviver: null,
replacer: null,
encoding: 'utf8',
version: 2,
useContext: false,
methodConstructor: jayson.Method,
maxBatchLength: Infinity,
router: function(method) {
return this.getMethod(method);
}
};
this.options = utils.merge(defaults, options || {});
// bind router to the server
this.options.router = this.options.router.bind(this);
this._methods = {};
// adds methods passed to constructor
this.methods(methods || {});
// assigns interfaces to this instance
const interfaces = Server.interfaces;
for(let name in interfaces) {
this[name] = interfaces[name].bind(interfaces[name], this);
}
// copies error messages for defined codes into this instance
this.errorMessages = {};
for(let handle in Server.errors) {
const code = Server.errors[handle];
this.errorMessages[code] = Server.errorMessages[code];
}
};
require('util').inherits(Server, events.EventEmitter);
module.exports = Server;
/**
* Interfaces that will be automatically bound as properties of a Server instance
* @enum {Function}
* @static
*/
Server.interfaces = {
http: require('./http'),
https: require('./https'),
tcp: require('./tcp'),
tls: require('./tls'),
websocket: require('./websocket'),
middleware: require('./middleware')
};
/**
* JSON-RPC specification errors that map to an integer code
* @enum {Number}
* @static
*/
Server.errors = {
PARSE_ERROR: -32700,
INVALID_REQUEST: -32600,
METHOD_NOT_FOUND: -32601,
INVALID_PARAMS: -32602,
INTERNAL_ERROR: -32603,
INVALID_REQUEST_MAX_BATCH_LENGTH_EXCEEDED: -32099,
};
/*
* Error codes that map to an error message
* @enum {String}
* @static
*/
Server.errorMessages = {};
Server.errorMessages[Server.errors.PARSE_ERROR] = 'Parse Error';
Server.errorMessages[Server.errors.INVALID_REQUEST] = 'Invalid request';
Server.errorMessages[Server.errors.METHOD_NOT_FOUND] = 'Method not found';
Server.errorMessages[Server.errors.INVALID_PARAMS] = 'Invalid method parameter(s)';
Server.errorMessages[Server.errors.INTERNAL_ERROR] = 'Internal error';
Server.errorMessages[Server.errors.INVALID_REQUEST_MAX_BATCH_LENGTH_EXCEEDED] = 'Invalid request: Maximum batch length exceeded';
/**
* Adds a single method to the server
* @param {String} name Name of method to add
* @param {Function|Client} definition Function or Client for a relayed method
* @throws {TypeError} Invalid parameters
*/
Server.prototype.method = function(name, definition) {
const Method = this.options.methodConstructor;
const isRelay = definition instanceof jayson.Client;
const isMethod = definition instanceof Method;
const isDefinitionFunction = typeof definition === 'function';
// a valid method is either a function or a client (relayed method)
if(!isRelay && !isMethod && !isDefinitionFunction) {
throw new TypeError('method definition must be either a function, an instance of jayson.Client or an instance of jayson.Method');
}
if(!name || typeof(name) !== 'string') {
throw new TypeError('"' + name + '" must be a non-zero length string');
}
if(/^rpc\./.test(name)) {
throw new TypeError('"' + name + '" is a reserved method name');
}
// make instance of jayson.Method
if(!isRelay && !isMethod) {
definition = new Method(definition, {
params: this.options.params,
useContext: this.options.useContext
});
}
this._methods[name] = definition;
};
/**
* Adds a batch of methods to the server
* @param {Object} methods Methods to add
*/
Server.prototype.methods = function(methods) {
methods = methods || {};
for(let name in methods) {
this.method(name, methods[name]);
}
};
/**
* Checks if a method is registered with the server
* @param {String} name Name of method
* @return {Boolean}
*/
Server.prototype.hasMethod = function(name) {
return name in this._methods;
};
/**
* Removes a method from the server
* @param {String} name
*/
Server.prototype.removeMethod = function(name) {
if(this.hasMethod(name)) {
delete this._methods[name];
}
};
/**
* Gets a method from the server
* @param {String} name
* @return {Method}
*/
Server.prototype.getMethod = function(name) {
if (Object.prototype.hasOwnProperty.call(this._methods, name)) {
return this._methods[name];
}
};
/**
* Returns a JSON-RPC compatible error property
* @param {Number} [code=-32603] Error code
* @param {String} [message="Internal error"] Error message
* @param {Object} [data] Additional data that should be provided
* @return {Object}
*/
Server.prototype.error = function(code, message, data) {
if(typeof(code) !== 'number') {
code = Server.errors.INTERNAL_ERROR;
}
if(typeof(message) !== 'string') {
message = this.errorMessages[code] || '';
}
const error = { code: code, message: message };
if(typeof(data) !== 'undefined') {
error.data = data;
}
return error;
};
/**
* Calls a method on the server
* @param {Object|Array|String} request A JSON-RPC request object. Object for single request, Array for batches and String for automatic parsing (using the reviver option)
* @param {Object} [context] Optional context object passed to methods
* @param {Function} [originalCallback] Callback that receives one of two arguments: first is an error and the second a response
*/
Server.prototype.call = function(request, context, originalCallback) {
const self = this;
if(typeof(context) === 'function') {
originalCallback = context;
context = {};
}
if(typeof(context) === 'undefined') {
context = {};
}
if(typeof(originalCallback) !== 'function') {
originalCallback = function() {};
}
// compose the callback so that we may emit an event on every response
const callback = function(error, response) {
self.emit('response', request, response || error);
originalCallback.apply(null, arguments);
};
maybeParse(request, this.options, function(err, request) {
let error = null; // JSON-RPC error
if(err) {
error = self.error(Server.errors.PARSE_ERROR, null, err);
callback(utils.response(error, undefined, undefined, self.options.version));
return;
}
// is this a batch request?
if(utils.Request.isBatch(request)) {
// batch requests not allowed for version 1
if(self.options.version === 1) {
error = self.error(Server.errors.INVALID_REQUEST);
callback(utils.response(error, undefined, undefined, self.options.version));
return;
}
// special case if empty batch request
if(!request.length) {
error = self.error(Server.errors.INVALID_REQUEST);
callback(utils.response(error, undefined, undefined, self.options.version));
return;
}
// verify number of batch requests does not exceed maximum allowed length
if (self.options.maxBatchLength >= 0 && request.length > self.options.maxBatchLength) {
error = self.error(Server.errors.INVALID_REQUEST_MAX_BATCH_LENGTH_EXCEEDED);
callback(utils.response(error, undefined, undefined, self.options.version));
return;
}
self._batch(request, context, callback);
return;
}
self.emit('request', request);
// is the request valid?
if(!utils.Request.isValidRequest(request, self.options.version)) {
error = self.error(Server.errors.INVALID_REQUEST);
callback(utils.response(error, undefined, undefined, self.options.version));
return;
}
// from now on we are "notification-aware" and can deliberately ignore errors for such requests
const respond = function(error, result) {
if(utils.Request.isNotification(request)) {
callback();
return;
}
const response = utils.response(error, result, request.id, self.options.version);
if(response.error) {
callback(response);
} else {
callback(null, response);
}
};
const method = self._resolveRouter(request.method, request.params);
// are we attempting to invoke a relayed method?
if(method instanceof jayson.Client) {
return method.request(request.method, request.params, request.id, function(error, response) {
if(utils.Request.isNotification(request)) {
callback();
return;
}
callback(error, response);
});
}
// does the method exist?
if(!(method instanceof jayson.Method)) {
respond(self.error(Server.errors.METHOD_NOT_FOUND));
return;
}
// execute jayson.Method instance
method.execute(self, request.params, context, function(error, result) {
if(utils.Response.isValidError(error, self.options.version)) {
respond(error);
return;
}
// got an invalid error
if(error) {
respond(self.error(Server.errors.INTERNAL_ERROR));
return;
}
respond(null, result);
});
});
};
/**
* Calls a method on the server returning a promise
* @param {Object|Array|String} request A JSON-RPC request object. Object for single request, Array for batches and String for automatic parsing (using the reviver option)
* @param {Object} [context] Optional context object passed to methods
* @return {Promise<Object>}
*/
Server.prototype.callp = function (...args) {
const self = this;
return new Promise(function (resolve, reject) {
return self.call(...args, function (err, response) {
if (err) {
reject(err);
return;
}
resolve(response);
});
});
};
/**
* Invoke the router
* @param {String} method Method to resolve
* @param {Array|Object} params Request params
* @return {Method}
*/
Server.prototype._resolveRouter = function(method, params) {
let router = this.options.router;
if(typeof router !== 'function') {
router = function(method) {
return this.getMethod(method);
};
}
const resolved = router.call(this, method, params);
// got a jayson.Method or a jayson.Client, return it
if((resolved instanceof jayson.Method) || (resolved instanceof jayson.Client)) {
return resolved;
}
// got a regular function, make it an instance of jayson.Method
if(typeof resolved === 'function') {
return new jayson.Method(resolved);
}
};
/**
* Evaluates a batch request
* @private
*/
Server.prototype._batch = function(requests, context, callback) {
const self = this;
const responses = [];
this.emit('batch', requests);
/**
* @ignore
*/
const maybeRespond = function() {
// done when we have filled up all the responses with a truthy value
const isDone = responses.every(function(response) { return response !== null; });
if(isDone) {
// filters away notifications
const filtered = responses.filter(function(res) {
return res !== true;
});
// only notifications in request means empty response
if(!filtered.length) {
callback();
return;
}
callback(null, filtered);
}
};
/**
* @ignore
*/
const wrapper = function(request, index) {
responses[index] = null;
return function() {
if(utils.Request.isValidRequest(request, self.options.version)) {
self.call(request, context, function(error, response) {
responses[index] = error || response || true;
maybeRespond();
});
} else {
const error = self.error(Server.errors.INVALID_REQUEST);
responses[index] = utils.response(error, undefined, undefined, self.options.version);
maybeRespond();
}
};
};
const stack = requests.map(function(request, index) {
// ignore possibly nested requests
if(utils.Request.isBatch(request)) {
return null;
}
return wrapper(request, index);
});
stack.forEach(function(method) {
if(typeof(method) === 'function') {
method();
}
});
};
/**
* Parse "request" if it is a string, else just invoke callback
* @ignore
*/
function maybeParse(request, options, callback) {
if(typeof(request) === 'string') {
utils.JSON.parse(request, options, callback);
} else {
callback(null, request);
}
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"scrypt.d.ts","sourceRoot":"","sources":["src/scrypt.ts"],"names":[],"mappings":"AAOA,OAAO,EAGL,KAAK,QAAQ,EAGd,MAAM,YAAY,CAAC;AAuEpB,MAAM,MAAM,UAAU,GAAG;IACvB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC,CAAC;AAoFF;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,GAAG,UAAU,CA0BvF;AAED;;;;GAIG;AACH,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,QAAQ,EACd,IAAI,EAAE,UAAU,GACf,OAAO,CAAC,UAAU,CAAC,CA2BrB"}

View File

@@ -0,0 +1,22 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.TYPE_VALUE = exports.VALUE = exports.TYPE = void 0;
exports.TYPE = Object.freeze({
eslintImplicitGlobalSetting: 'readonly',
isTypeVariable: true,
isValueVariable: false,
});
exports.VALUE = Object.freeze({
eslintImplicitGlobalSetting: 'readonly',
isTypeVariable: false,
isValueVariable: true,
});
exports.TYPE_VALUE = Object.freeze({
eslintImplicitGlobalSetting: 'readonly',
isTypeVariable: true,
isValueVariable: true,
});

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_ts_metadata.cjs",
"module": "../../esm/_ts_metadata.js"
}

View File

@@ -0,0 +1,37 @@
interface RuntimeCoverageModuleLoader {
import: (id: string) => Promise<{
default: RuntimeCoverageProviderModule;
}>;
isBrowser?: boolean;
moduleExecutionInfo?: Map<string, {
startOffset: number;
}>;
}
interface RuntimeCoverageProviderModule {
/**
* Factory for creating a new coverage provider
*/
getProvider: () => any;
/**
* Executed before tests are run in the worker thread.
*/
startCoverage?: (runtimeOptions: {
isolate: boolean;
}) => unknown | Promise<unknown>;
/**
* Executed on after each run in the worker thread. Possible to return a payload passed to the provider
*/
takeCoverage?: (runtimeOptions?: {
moduleExecutionInfo?: Map<string, {
startOffset: number;
}>;
}) => unknown | Promise<unknown>;
/**
* Executed after all tests have been run in the worker thread.
*/
stopCoverage?: (runtimeOptions: {
isolate: boolean;
}) => unknown | Promise<unknown>;
}
export type { RuntimeCoverageModuleLoader as R, RuntimeCoverageProviderModule as a };

View File

@@ -0,0 +1,203 @@
# URI.js
URI.js is an [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt) compliant, scheme extendable URI parsing/validating/resolving library for all JavaScript environments (browsers, Node.js, etc).
It is also compliant with the IRI ([RFC 3987](http://www.ietf.org/rfc/rfc3987.txt)), IDNA ([RFC 5890](http://www.ietf.org/rfc/rfc5890.txt)), IPv6 Address ([RFC 5952](http://www.ietf.org/rfc/rfc5952.txt)), IPv6 Zone Identifier ([RFC 6874](http://www.ietf.org/rfc/rfc6874.txt)) specifications.
URI.js has an extensive test suite, and works in all (Node.js, web) environments. It weighs in at 6.4kb (gzipped, 17kb deflated).
## API
### Parsing
URI.parse("uri://user:pass@example.com:123/one/two.three?q1=a1&q2=a2#body");
//returns:
//{
// scheme : "uri",
// userinfo : "user:pass",
// host : "example.com",
// port : 123,
// path : "/one/two.three",
// query : "q1=a1&q2=a2",
// fragment : "body"
//}
### Serializing
URI.serialize({scheme : "http", host : "example.com", fragment : "footer"}) === "http://example.com/#footer"
### Resolving
URI.resolve("uri://a/b/c/d?q", "../../g") === "uri://a/g"
### Normalizing
URI.normalize("HTTP://ABC.com:80/%7Esmith/home.html") === "http://abc.com/~smith/home.html"
### Comparison
URI.equal("example://a/b/c/%7Bfoo%7D", "eXAMPLE://a/./b/../b/%63/%7bfoo%7d") === true
### IP Support
//IPv4 normalization
URI.normalize("//192.068.001.000") === "//192.68.1.0"
//IPv6 normalization
URI.normalize("//[2001:0:0DB8::0:0001]") === "//[2001:0:db8::1]"
//IPv6 zone identifier support
URI.parse("//[2001:db8::7%25en1]");
//returns:
//{
// host : "2001:db8::7%en1"
//}
### IRI Support
//convert IRI to URI
URI.serialize(URI.parse("http://examplé.org/rosé")) === "http://xn--exampl-gva.org/ros%C3%A9"
//convert URI to IRI
URI.serialize(URI.parse("http://xn--exampl-gva.org/ros%C3%A9"), {iri:true}) === "http://examplé.org/rosé"
### Options
All of the above functions can accept an additional options argument that is an object that can contain one or more of the following properties:
* `scheme` (string)
Indicates the scheme that the URI should be treated as, overriding the URI's normal scheme parsing behavior.
* `reference` (string)
If set to `"suffix"`, it indicates that the URI is in the suffix format, and the validator will use the option's `scheme` property to determine the URI's scheme.
* `tolerant` (boolean, false)
If set to `true`, the parser will relax URI resolving rules.
* `absolutePath` (boolean, false)
If set to `true`, the serializer will not resolve a relative `path` component.
* `iri` (boolean, false)
If set to `true`, the serializer will unescape non-ASCII characters as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt).
* `unicodeSupport` (boolean, false)
If set to `true`, the parser will unescape non-ASCII characters in the parsed output as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt).
* `domainHost` (boolean, false)
If set to `true`, the library will treat the `host` component as a domain name, and convert IDNs (International Domain Names) as per [RFC 5891](http://www.ietf.org/rfc/rfc5891.txt).
## Scheme Extendable
URI.js supports inserting custom [scheme](http://en.wikipedia.org/wiki/URI_scheme) dependent processing rules. Currently, URI.js has built in support for the following schemes:
* http \[[RFC 2616](http://www.ietf.org/rfc/rfc2616.txt)\]
* https \[[RFC 2818](http://www.ietf.org/rfc/rfc2818.txt)\]
* ws \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\]
* wss \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\]
* mailto \[[RFC 6068](http://www.ietf.org/rfc/rfc6068.txt)\]
* urn \[[RFC 2141](http://www.ietf.org/rfc/rfc2141.txt)\]
* urn:uuid \[[RFC 4122](http://www.ietf.org/rfc/rfc4122.txt)\]
### HTTP/HTTPS Support
URI.equal("HTTP://ABC.COM:80", "http://abc.com/") === true
URI.equal("https://abc.com", "HTTPS://ABC.COM:443/") === true
### WS/WSS Support
URI.parse("wss://example.com/foo?bar=baz");
//returns:
//{
// scheme : "wss",
// host: "example.com",
// resourceName: "/foo?bar=baz",
// secure: true,
//}
URI.equal("WS://ABC.COM:80/chat#one", "ws://abc.com/chat") === true
### Mailto Support
URI.parse("mailto:alpha@example.com,bravo@example.com?subject=SUBSCRIBE&body=Sign%20me%20up!");
//returns:
//{
// scheme : "mailto",
// to : ["alpha@example.com", "bravo@example.com"],
// subject : "SUBSCRIBE",
// body : "Sign me up!"
//}
URI.serialize({
scheme : "mailto",
to : ["alpha@example.com"],
subject : "REMOVE",
body : "Please remove me",
headers : {
cc : "charlie@example.com"
}
}) === "mailto:alpha@example.com?cc=charlie@example.com&subject=REMOVE&body=Please%20remove%20me"
### URN Support
URI.parse("urn:example:foo");
//returns:
//{
// scheme : "urn",
// nid : "example",
// nss : "foo",
//}
#### URN UUID Support
URI.parse("urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6");
//returns:
//{
// scheme : "urn",
// nid : "uuid",
// uuid : "f81d4fae-7dec-11d0-a765-00a0c91e6bf6",
//}
## Usage
To load in a browser, use the following tag:
<script type="text/javascript" src="uri-js/dist/es5/uri.all.min.js"></script>
To load in a CommonJS/Module environment, first install with npm/yarn by running on the command line:
npm install uri-js
# OR
yarn add uri-js
Then, in your code, load it using:
const URI = require("uri-js");
If you are writing your code in ES6+ (ESNEXT) or TypeScript, you would load it using:
import * as URI from "uri-js";
Or you can load just what you need using named exports:
import { parse, serialize, resolve, resolveComponents, normalize, equal, removeDotSegments, pctEncChar, pctDecChars, escapeComponent, unescapeComponent } from "uri-js";
## Breaking changes
### Breaking changes from 3.x
URN parsing has been completely changed to better align with the specification. Scheme is now always `urn`, but has two new properties: `nid` which contains the Namspace Identifier, and `nss` which contains the Namespace Specific String. The `nss` property will be removed by higher order scheme handlers, such as the UUID URN scheme handler.
The UUID of a URN can now be found in the `uuid` property.
### Breaking changes from 2.x
URI validation has been removed as it was slow, exposed a vulnerabilty, and was generally not useful.
### Breaking changes from 1.x
The `errors` array on parsed components is now an `error` string.

View File

@@ -0,0 +1 @@
export { _ as default } from "../esm/_apply_decorated_descriptor.js";

View File

@@ -0,0 +1,456 @@
declare module 'http' {
import * as stream from 'stream';
import { URL } from 'url';
import { Socket, Server as NetServer, LookupFunction } from 'net';
// incoming headers will never contain number
interface IncomingHttpHeaders {
'accept'?: string | undefined;
'accept-language'?: string | undefined;
'accept-patch'?: string | undefined;
'accept-ranges'?: string | undefined;
'access-control-allow-credentials'?: string | undefined;
'access-control-allow-headers'?: string | undefined;
'access-control-allow-methods'?: string | undefined;
'access-control-allow-origin'?: string | undefined;
'access-control-expose-headers'?: string | undefined;
'access-control-max-age'?: string | undefined;
'access-control-request-headers'?: string | undefined;
'access-control-request-method'?: string | undefined;
'age'?: string | undefined;
'allow'?: string | undefined;
'alt-svc'?: string | undefined;
'authorization'?: string | undefined;
'cache-control'?: string | undefined;
'connection'?: string | undefined;
'content-disposition'?: string | undefined;
'content-encoding'?: string | undefined;
'content-language'?: string | undefined;
'content-length'?: string | undefined;
'content-location'?: string | undefined;
'content-range'?: string | undefined;
'content-type'?: string | undefined;
'cookie'?: string | undefined;
'date'?: string | undefined;
'etag'?: string | undefined;
'expect'?: string | undefined;
'expires'?: string | undefined;
'forwarded'?: string | undefined;
'from'?: string | undefined;
'host'?: string | undefined;
'if-match'?: string | undefined;
'if-modified-since'?: string | undefined;
'if-none-match'?: string | undefined;
'if-unmodified-since'?: string | undefined;
'last-modified'?: string | undefined;
'location'?: string | undefined;
'origin'?: string | undefined;
'pragma'?: string | undefined;
'proxy-authenticate'?: string | undefined;
'proxy-authorization'?: string | undefined;
'public-key-pins'?: string | undefined;
'range'?: string | undefined;
'referer'?: string | undefined;
'retry-after'?: string | undefined;
'set-cookie'?: string[] | undefined;
'strict-transport-security'?: string | undefined;
'tk'?: string | undefined;
'trailer'?: string | undefined;
'transfer-encoding'?: string | undefined;
'upgrade'?: string | undefined;
'user-agent'?: string | undefined;
'vary'?: string | undefined;
'via'?: string | undefined;
'warning'?: string | undefined;
'www-authenticate'?: string | undefined;
[header: string]: string | string[] | undefined;
}
// outgoing headers allows numbers (as they are converted internally to strings)
interface OutgoingHttpHeaders {
[header: string]: number | string | string[] | undefined;
}
interface ClientRequestArgs {
protocol?: string | null | undefined;
host?: string | null | undefined;
hostname?: string | null | undefined;
family?: number | undefined;
port?: number | string | null | undefined;
defaultPort?: number | string | undefined;
localAddress?: string | undefined;
socketPath?: string | undefined;
method?: string | undefined;
path?: string | null | undefined;
headers?: OutgoingHttpHeaders | undefined;
auth?: string | null | undefined;
agent?: Agent | boolean | undefined;
_defaultAgent?: Agent | undefined;
timeout?: number | undefined;
setHost?: boolean | undefined;
// https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278
createConnection?: ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) | undefined;
lookup?: LookupFunction | undefined;
}
interface ServerOptions {
IncomingMessage?: typeof IncomingMessage | undefined;
ServerResponse?: typeof ServerResponse | undefined;
}
type RequestListener = (req: IncomingMessage, res: ServerResponse) => void;
class Server extends NetServer {
constructor(requestListener?: RequestListener);
constructor(options: ServerOptions, requestListener?: RequestListener);
setTimeout(msecs?: number, callback?: () => void): this;
setTimeout(callback: () => void): this;
/**
* Limits maximum incoming headers count. If set to 0, no limit will be applied.
* @default 2000
* {@link https://nodejs.org/api/http.html#http_server_maxheaderscount}
*/
maxHeadersCount: number | null;
timeout: number;
/**
* Limit the amount of time the parser will wait to receive the complete HTTP headers.
* @default 40000
* {@link https://nodejs.org/api/http.html#http_server_headerstimeout}
*/
headersTimeout: number;
keepAliveTimeout: number;
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'close', listener: () => void): this;
addListener(event: 'connection', listener: (socket: Socket) => void): this;
addListener(event: 'error', listener: (err: Error) => void): this;
addListener(event: 'listening', listener: () => void): this;
addListener(event: 'checkContinue', listener: RequestListener): this;
addListener(event: 'checkExpectation', listener: RequestListener): this;
addListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this;
addListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
addListener(event: 'request', listener: RequestListener): this;
addListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
emit(event: string, ...args: any[]): boolean;
emit(event: 'close'): boolean;
emit(event: 'connection', socket: Socket): boolean;
emit(event: 'error', err: Error): boolean;
emit(event: 'listening'): boolean;
emit(event: 'checkContinue', req: IncomingMessage, res: ServerResponse): boolean;
emit(event: 'checkExpectation', req: IncomingMessage, res: ServerResponse): boolean;
emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean;
emit(event: 'connect', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean;
emit(event: 'request', req: IncomingMessage, res: ServerResponse): boolean;
emit(event: 'upgrade', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'close', listener: () => void): this;
on(event: 'connection', listener: (socket: Socket) => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'listening', listener: () => void): this;
on(event: 'checkContinue', listener: RequestListener): this;
on(event: 'checkExpectation', listener: RequestListener): this;
on(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this;
on(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
on(event: 'request', listener: RequestListener): this;
on(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'close', listener: () => void): this;
once(event: 'connection', listener: (socket: Socket) => void): this;
once(event: 'error', listener: (err: Error) => void): this;
once(event: 'listening', listener: () => void): this;
once(event: 'checkContinue', listener: RequestListener): this;
once(event: 'checkExpectation', listener: RequestListener): this;
once(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this;
once(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
once(event: 'request', listener: RequestListener): this;
once(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'close', listener: () => void): this;
prependListener(event: 'connection', listener: (socket: Socket) => void): this;
prependListener(event: 'error', listener: (err: Error) => void): this;
prependListener(event: 'listening', listener: () => void): this;
prependListener(event: 'checkContinue', listener: RequestListener): this;
prependListener(event: 'checkExpectation', listener: RequestListener): this;
prependListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this;
prependListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
prependListener(event: 'request', listener: RequestListener): this;
prependListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'close', listener: () => void): this;
prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this;
prependOnceListener(event: 'error', listener: (err: Error) => void): this;
prependOnceListener(event: 'listening', listener: () => void): this;
prependOnceListener(event: 'checkContinue', listener: RequestListener): this;
prependOnceListener(event: 'checkExpectation', listener: RequestListener): this;
prependOnceListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this;
prependOnceListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
prependOnceListener(event: 'request', listener: RequestListener): this;
prependOnceListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this;
}
// https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js
class OutgoingMessage extends stream.Writable {
upgrading: boolean;
chunkedEncoding: boolean;
shouldKeepAlive: boolean;
useChunkedEncodingByDefault: boolean;
sendDate: boolean;
finished: boolean;
headersSent: boolean;
connection: Socket;
constructor();
setTimeout(msecs: number, callback?: () => void): this;
setHeader(name: string, value: number | string | ReadonlyArray<string>): void;
getHeader(name: string): number | string | string[] | undefined;
getHeaders(): OutgoingHttpHeaders;
getHeaderNames(): string[];
hasHeader(name: string): boolean;
removeHeader(name: string): void;
addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void;
flushHeaders(): void;
}
// https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256
class ServerResponse extends OutgoingMessage {
statusCode: number;
statusMessage: string;
writableFinished: boolean;
constructor(req: IncomingMessage);
assignSocket(socket: Socket): void;
detachSocket(socket: Socket): void;
// https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53
// no args in writeContinue callback
writeContinue(callback?: () => void): void;
writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): this;
writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this;
writeProcessing(): void;
}
interface InformationEvent {
statusCode: number;
statusMessage: string;
httpVersion: string;
httpVersionMajor: number;
httpVersionMinor: number;
headers: IncomingHttpHeaders;
rawHeaders: string[];
}
// https://github.com/nodejs/node/blob/v12.20.0/lib/_http_client.js#L85
class ClientRequest extends OutgoingMessage {
connection: Socket;
socket: Socket;
aborted: boolean;
host: string;
protocol: string;
reusedSocket: boolean;
maxHeadersCount: number;
constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void);
method: string;
readonly path: string;
abort(): void;
onSocket(socket: Socket): void;
setTimeout(timeout: number, callback?: () => void): this;
setNoDelay(noDelay?: boolean): void;
setSocketKeepAlive(enable?: boolean, initialDelay?: number): void;
addListener(event: 'abort', listener: () => void): this;
addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
addListener(event: 'continue', listener: () => void): this;
addListener(event: 'information', listener: (info: InformationEvent) => void): this;
addListener(event: 'response', listener: (response: IncomingMessage) => void): this;
addListener(event: 'socket', listener: (socket: Socket) => void): this;
addListener(event: 'timeout', listener: () => void): this;
addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
addListener(event: 'close', listener: () => void): this;
addListener(event: 'drain', listener: () => void): this;
addListener(event: 'error', listener: (err: Error) => void): this;
addListener(event: 'finish', listener: () => void): this;
addListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
on(event: 'abort', listener: () => void): this;
on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
on(event: 'continue', listener: () => void): this;
on(event: 'information', listener: (info: InformationEvent) => void): this;
on(event: 'response', listener: (response: IncomingMessage) => void): this;
on(event: 'socket', listener: (socket: Socket) => void): this;
on(event: 'timeout', listener: () => void): this;
on(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
on(event: 'close', listener: () => void): this;
on(event: 'drain', listener: () => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'finish', listener: () => void): this;
on(event: 'pipe', listener: (src: stream.Readable) => void): this;
on(event: 'unpipe', listener: (src: stream.Readable) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: 'abort', listener: () => void): this;
once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
once(event: 'continue', listener: () => void): this;
once(event: 'information', listener: (info: InformationEvent) => void): this;
once(event: 'response', listener: (response: IncomingMessage) => void): this;
once(event: 'socket', listener: (socket: Socket) => void): this;
once(event: 'timeout', listener: () => void): this;
once(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
once(event: 'close', listener: () => void): this;
once(event: 'drain', listener: () => void): this;
once(event: 'error', listener: (err: Error) => void): this;
once(event: 'finish', listener: () => void): this;
once(event: 'pipe', listener: (src: stream.Readable) => void): this;
once(event: 'unpipe', listener: (src: stream.Readable) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: 'abort', listener: () => void): this;
prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
prependListener(event: 'continue', listener: () => void): this;
prependListener(event: 'information', listener: (info: InformationEvent) => void): this;
prependListener(event: 'response', listener: (response: IncomingMessage) => void): this;
prependListener(event: 'socket', listener: (socket: Socket) => void): this;
prependListener(event: 'timeout', listener: () => void): this;
prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
prependListener(event: 'close', listener: () => void): this;
prependListener(event: 'drain', listener: () => void): this;
prependListener(event: 'error', listener: (err: Error) => void): this;
prependListener(event: 'finish', listener: () => void): this;
prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'abort', listener: () => void): this;
prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
prependOnceListener(event: 'continue', listener: () => void): this;
prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this;
prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this;
prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this;
prependOnceListener(event: 'timeout', listener: () => void): this;
prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this;
prependOnceListener(event: 'close', listener: () => void): this;
prependOnceListener(event: 'drain', listener: () => void): this;
prependOnceListener(event: 'error', listener: (err: Error) => void): this;
prependOnceListener(event: 'finish', listener: () => void): this;
prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
class IncomingMessage extends stream.Readable {
constructor(socket: Socket);
aborted: boolean;
httpVersion: string;
httpVersionMajor: number;
httpVersionMinor: number;
complete: boolean;
connection: Socket;
headers: IncomingHttpHeaders;
rawHeaders: string[];
trailers: { [key: string]: string | undefined };
rawTrailers: string[];
setTimeout(msecs: number, callback?: () => void): this;
/**
* Only valid for request obtained from http.Server.
*/
method?: string | undefined;
/**
* Only valid for request obtained from http.Server.
*/
url?: string | undefined;
/**
* Only valid for response obtained from http.ClientRequest.
*/
statusCode?: number | undefined;
/**
* Only valid for response obtained from http.ClientRequest.
*/
statusMessage?: string | undefined;
socket: Socket;
destroy(error?: Error): this;
}
interface AgentOptions {
/**
* Keep sockets around in a pool to be used by other requests in the future. Default = false
*/
keepAlive?: boolean | undefined;
/**
* When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
* Only relevant if keepAlive is set to true.
*/
keepAliveMsecs?: number | undefined;
/**
* Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
*/
maxSockets?: number | undefined;
/**
* Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity.
*/
maxTotalSockets?: number | undefined;
/**
* Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.
*/
maxFreeSockets?: number | undefined;
/**
* Socket timeout in milliseconds. This will set the timeout after the socket is connected.
*/
timeout?: number | undefined;
/**
* Scheduling strategy to apply when picking the next free socket to use. Default: 'fifo'.
*/
scheduling?: 'fifo' | 'lifo' | undefined;
}
class Agent {
maxFreeSockets: number;
maxSockets: number;
maxTotalSockets: number;
readonly sockets: {
readonly [key: string]: Socket[];
};
readonly requests: {
readonly [key: string]: IncomingMessage[];
};
constructor(opts?: AgentOptions);
/**
* Destroy any sockets that are currently in use by the agent.
* It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled,
* then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise,
* sockets may hang open for quite a long time before the server terminates them.
*/
destroy(): void;
}
const METHODS: string[];
const STATUS_CODES: {
[errorCode: number]: string | undefined;
[errorCode: string]: string | undefined;
};
function createServer(requestListener?: RequestListener): Server;
function createServer(options: ServerOptions, requestListener?: RequestListener): Server;
// although RequestOptions are passed as ClientRequestArgs to ClientRequest directly,
// create interface RequestOptions would make the naming more clear to developers
interface RequestOptions extends ClientRequestArgs { }
function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest;
function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
let globalAgent: Agent;
/**
* Read-only property specifying the maximum allowed size of HTTP headers in bytes.
* Defaults to 8KB. Configurable using the [`--max-http-header-size`][] CLI option.
*/
const maxHeaderSize: number;
}

View File

@@ -0,0 +1,6 @@
"use strict";
function _class_name_tdz_error(name) {
throw new ReferenceError("Class \"" + name + "\" cannot be referenced in computed property keys.");
}
exports._ = _class_name_tdz_error;

View File

@@ -0,0 +1,26 @@
extends: eslint:recommended
env:
node: true
browser: true
rules:
block-scoped-var: 2
callback-return: 2
dot-notation: 2
indent: 2
linebreak-style: [2, unix]
new-cap: 2
no-console: [2, allow: [warn, error]]
no-else-return: 2
no-eq-null: 2
no-fallthrough: 2
no-invalid-this: 2
no-return-assign: 2
no-shadow: 1
no-trailing-spaces: 2
no-use-before-define: [2, nofunc]
quotes: [2, single, avoid-escape]
semi: [2, always]
strict: [2, global]
valid-jsdoc: [2, requireReturn: false]
no-control-regex: 0
no-useless-escape: 2

View File

@@ -0,0 +1,139 @@
declare module "node:querystring" {
interface StringifyOptions {
/**
* The function to use when converting URL-unsafe characters to percent-encoding in the query string.
* @default `querystring.escape()`
*/
encodeURIComponent?: ((str: string) => string) | undefined;
}
interface ParseOptions {
/**
* Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations.
* @default 1000
*/
maxKeys?: number | undefined;
/**
* The function to use when decoding percent-encoded characters in the query string.
* @default `querystring.unescape()`
*/
decodeURIComponent?: ((str: string) => string) | undefined;
}
interface ParsedUrlQuery extends NodeJS.Dict<string | string[]> {}
interface ParsedUrlQueryInput extends
NodeJS.Dict<
| string
| number
| boolean
| bigint
| ReadonlyArray<string | number | boolean | bigint>
| null
>
{}
/**
* The `querystring.stringify()` method produces a URL query string from a
* given `obj` by iterating through the object's "own properties".
*
* It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) |
* [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) |
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) |
* [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) |
* [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) |
* [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) |
* [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) |
* [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to
* empty strings.
*
* ```js
* querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
* // Returns 'foo=bar&#x26;baz=qux&#x26;baz=quux&#x26;corge='
*
* querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
* // Returns 'foo:bar;baz:qux'
* ```
*
* By default, characters requiring percent-encoding within the query string will
* be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified:
*
* ```js
* // Assuming gbkEncodeURIComponent function already exists,
*
* querystring.stringify({ w: '中文', foo: 'bar' }, null, null,
* { encodeURIComponent: gbkEncodeURIComponent });
* ```
* @since v0.1.25
* @param obj The object to serialize into a URL query string
* @param [sep='&'] The substring used to delimit key and value pairs in the query string.
* @param [eq='='] . The substring used to delimit keys and values in the query string.
*/
function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string;
/**
* The `querystring.parse()` method parses a URL query string (`str`) into a
* collection of key and value pairs.
*
* For example, the query string `'foo=bar&#x26;abc=xyz&#x26;abc=123'` is parsed into:
*
* ```json
* {
* "foo": "bar",
* "abc": ["xyz", "123"]
* }
* ```
*
* The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`,
* `obj.hasOwnProperty()`, and others
* are not defined and _will not work_.
*
* By default, percent-encoded characters within the query string will be assumed
* to use UTF-8 encoding. If an alternative character encoding is used, then an
* alternative `decodeURIComponent` option will need to be specified:
*
* ```js
* // Assuming gbkDecodeURIComponent function already exists...
*
* querystring.parse('w=%D6%D0%CE%C4&#x26;foo=bar', null, null,
* { decodeURIComponent: gbkDecodeURIComponent });
* ```
* @since v0.1.25
* @param str The URL query string to parse
* @param [sep='&'] The substring used to delimit key and value pairs in the query string.
* @param [eq='='] The substring used to delimit keys and values in the query string.
*/
function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery;
/**
* The querystring.encode() function is an alias for querystring.stringify().
*/
const encode: typeof stringify;
/**
* The querystring.decode() function is an alias for querystring.parse().
*/
const decode: typeof parse;
/**
* The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL
* query strings.
*
* The `querystring.escape()` method is used by `querystring.stringify()` and is
* generally not expected to be used directly. It is exported primarily to allow
* application code to provide a replacement percent-encoding implementation if
* necessary by assigning `querystring.escape` to an alternative function.
* @since v0.1.25
*/
function escape(str: string): string;
/**
* The `querystring.unescape()` method performs decoding of URL percent-encoded
* characters on the given `str`.
*
* The `querystring.unescape()` method is used by `querystring.parse()` and is
* generally not expected to be used directly. It is exported primarily to allow
* application code to provide a replacement decoding implementation if
* necessary by assigning `querystring.unescape` to an alternative function.
*
* By default, the `querystring.unescape()` method will attempt to use the
* JavaScript built-in `decodeURIComponent()` method to decode. If that fails,
* a safer equivalent that does not throw on malformed URLs will be used.
* @since v0.1.25
*/
function unescape(str: string): string;
}
declare module "querystring" {
export * from "node:querystring";
}

View File

@@ -0,0 +1,231 @@
// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license)
// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license)
/// <reference types="node" />
import { Blob } from 'node:buffer'
import { URL, URLSearchParams } from 'node:url'
import { ReadableStream } from 'node:stream/web'
import { FormData } from './formdata'
import { HeaderRecord } from './header'
import Dispatcher from './dispatcher'
export type RequestInfo = string | URL | Request
export declare function fetch (
input: RequestInfo,
init?: RequestInit
): Promise<Response>
export type BodyInit =
| ArrayBuffer
| AsyncIterable<Uint8Array>
| Blob
| FormData
| Iterable<Uint8Array>
| NodeJS.ArrayBufferView
| URLSearchParams
| null
| string
export class BodyMixin {
readonly body: ReadableStream | null
readonly bodyUsed: boolean
readonly arrayBuffer: () => Promise<ArrayBuffer>
readonly blob: () => Promise<Blob>
readonly bytes: () => Promise<Uint8Array>
/**
* @deprecated This method is not recommended for parsing multipart/form-data bodies in server environments.
* It is recommended to use a library such as [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy) as follows:
*
* @example
* ```js
* import { Busboy } from '@fastify/busboy'
* import { Readable } from 'node:stream'
*
* const response = await fetch('...')
* const busboy = new Busboy({ headers: { 'content-type': response.headers.get('content-type') } })
*
* // handle events emitted from `busboy`
*
* Readable.fromWeb(response.body).pipe(busboy)
* ```
*/
readonly formData: () => Promise<FormData>
readonly json: () => Promise<unknown>
readonly text: () => Promise<string>
}
export interface SpecIterator<T, TReturn = any, TNext = undefined> {
next(...args: [] | [TNext]): IteratorResult<T, TReturn>;
}
export interface SpecIteratorObject<T, TReturn = undefined, TNext = unknown> extends SpecIterator<T, TReturn, TNext> {
[Symbol.iterator](): SpecIteratorObject<T, TReturn, TNext>;
map<U>(callbackfn: (value: T, index: number) => U): SpecIteratorObject<U>;
filter<S extends T>(predicate: (value: T, index: number) => value is S): SpecIteratorObject<S>;
filter(predicate: (value: T, index: number) => unknown): SpecIteratorObject<T>;
take(limit: number): SpecIteratorObject<T>;
drop(count: number): SpecIteratorObject<T>;
flatMap<U>(callbackfn: (value: T, index: number) => Iterator<U> | Iterable<U>): SpecIteratorObject<U>;
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T): T;
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T, initialValue: T): T;
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U, initialValue: U): U;
toArray(): T[];
forEach(callbackfn: (value: T, index: number) => void): void;
some(predicate: (value: T, index: number) => unknown): boolean;
every(predicate: (value: T, index: number) => unknown): boolean;
find<S extends T>(predicate: (value: T, index: number) => value is S): S | undefined;
find(predicate: (value: T, index: number) => unknown): T | undefined;
readonly [Symbol.toStringTag]: string;
}
export interface SpecIterableIterator<T> extends SpecIteratorObject<T> {
[Symbol.iterator](): SpecIterableIterator<T>;
}
export interface SpecIterable<T> {
[Symbol.iterator](): SpecIterableIterator<T>;
}
export type HeadersInit = [string, string][] | HeaderRecord | Headers
export declare class Headers implements SpecIterable<[string, string]> {
constructor (init?: HeadersInit)
readonly append: (name: string, value: string) => void
readonly delete: (name: string) => void
readonly get: (name: string) => string | null
readonly has: (name: string) => boolean
readonly set: (name: string, value: string) => void
readonly getSetCookie: () => string[]
readonly forEach: (
callbackfn: (value: string, key: string, iterable: Headers) => void,
thisArg?: unknown
) => void
readonly keys: () => SpecIterableIterator<string>
readonly values: () => SpecIterableIterator<string>
readonly entries: () => SpecIterableIterator<[string, string]>
readonly [Symbol.iterator]: () => SpecIterableIterator<[string, string]>
}
export type RequestCache =
| 'default'
| 'force-cache'
| 'no-cache'
| 'no-store'
| 'only-if-cached'
| 'reload'
export type RequestCredentials = 'omit' | 'include' | 'same-origin'
type RequestDestination =
| ''
| 'audio'
| 'audioworklet'
| 'document'
| 'embed'
| 'font'
| 'image'
| 'manifest'
| 'object'
| 'paintworklet'
| 'report'
| 'script'
| 'sharedworker'
| 'style'
| 'track'
| 'video'
| 'worker'
| 'xslt'
export interface RequestInit {
body?: BodyInit | null
cache?: RequestCache
credentials?: RequestCredentials
dispatcher?: Dispatcher
duplex?: RequestDuplex
headers?: HeadersInit
integrity?: string
keepalive?: boolean
method?: string
mode?: RequestMode
redirect?: RequestRedirect
referrer?: string
referrerPolicy?: ReferrerPolicy
signal?: AbortSignal | null
window?: null
}
export type ReferrerPolicy =
| ''
| 'no-referrer'
| 'no-referrer-when-downgrade'
| 'origin'
| 'origin-when-cross-origin'
| 'same-origin'
| 'strict-origin'
| 'strict-origin-when-cross-origin'
| 'unsafe-url'
export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin'
export type RequestRedirect = 'error' | 'follow' | 'manual'
export type RequestDuplex = 'half'
export declare class Request extends BodyMixin {
constructor (input: RequestInfo, init?: RequestInit)
readonly cache: RequestCache
readonly credentials: RequestCredentials
readonly destination: RequestDestination
readonly headers: Headers
readonly integrity: string
readonly method: string
readonly mode: RequestMode
readonly redirect: RequestRedirect
readonly referrer: string
readonly referrerPolicy: ReferrerPolicy
readonly url: string
readonly keepalive: boolean
readonly signal: AbortSignal
readonly duplex: RequestDuplex
public clone (): Request
}
export interface ResponseInit {
readonly status?: number
readonly statusText?: string
readonly headers?: HeadersInit
}
export type ResponseType =
| 'basic'
| 'cors'
| 'default'
| 'error'
| 'opaque'
| 'opaqueredirect'
export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308
export declare class Response extends BodyMixin {
constructor (body?: BodyInit, init?: ResponseInit)
readonly headers: Headers
readonly ok: boolean
readonly status: number
readonly statusText: string
readonly type: ResponseType
readonly url: string
readonly redirected: boolean
public clone (): Response
static error (): Response
static json (data: any, init?: ResponseInit): Response
static redirect (url: string | URL, status?: ResponseRedirectStatus): Response
}

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_class_static_private_field_destructure.cjs",
"module": "../../esm/_class_static_private_field_destructure.js"
}

View File

@@ -0,0 +1,46 @@
{
"name": "@vitest/spy",
"type": "module",
"version": "4.1.10",
"description": "Lightweight Jest compatible spy implementation",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://vitest.dev/api/mock",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
"directory": "packages/spy"
},
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"keywords": [
"vitest",
"test",
"mock",
"spy",
"intercept"
],
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./optional-types.js": {
"types": "./optional-types.d.ts"
},
"./*": "./*"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist",
"optional-types.d.ts"
],
"scripts": {
"build": "premove dist && rollup -c",
"dev": "rollup -c --watch"
}
}

View File

@@ -0,0 +1,12 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.es2016_intl = void 0;
const base_config_1 = require("./base-config");
exports.es2016_intl = {
libs: [],
variables: [['Intl', base_config_1.TYPE_VALUE]],
};

View File

@@ -0,0 +1,3 @@
rules:
no-console: 0
no-empty: [2, allowEmptyCatch: true]

View File

@@ -0,0 +1,20 @@
export { l as loadDiffConfig, a as loadSnapshotSerializers, s as setupCommonEnv, b as startCoverageInsideWorker, c as stopCoverageInsideWorker, t as takeCoverageInsideWorker } from './chunks/setup-common.DYx3LtFI.js';
export { T as Traces } from './chunks/traces.DT5aQ62U.js';
export { collectTests, startTests } from '@vitest/runner';
import * as spyModule from '@vitest/spy';
export { spyModule as SpyModule };
export { browserFormat, format, inspect, stringify } from '@vitest/utils/display';
export { processError } from '@vitest/utils/error';
export { getType } from '@vitest/utils/helpers';
export { DecodedMap, getOriginalPosition } from '@vitest/utils/source-map';
export { getSafeTimers, setSafeTimers } from '@vitest/utils/timers';
import './chunks/coverage.CTzCuANN.js';
import '@vitest/snapshot';
import './chunks/utils.BX5Fg8C4.js';
/**
* @internal
*/
const __INTERNAL = { _extendedMethods: /* @__PURE__ */ new Set() };
export { __INTERNAL };

View File

@@ -0,0 +1,259 @@
'use strict'
const { test } = require('node:test')
const assert = require('node:assert')
const { join } = require('path')
const { readFile } = require('fs')
const { file } = require('./helper')
const ThreadStream = require('..')
const { MessageChannel } = require('worker_threads')
const { once } = require('events')
test('base sync=true', function (t, done) {
const dest = file()
const stream = new ThreadStream({
filename: join(__dirname, 'to-file.js'),
workerData: { dest },
sync: true
})
assert.deepStrictEqual(stream.writableObjectMode, false)
assert.deepStrictEqual(stream.writableFinished, false)
stream.on('finish', () => {
assert.deepStrictEqual(stream.writableFinished, true)
readFile(dest, 'utf8', (err, data) => {
assert.ifError(err)
assert.strictEqual(data, 'hello world\nsomething else\n')
})
})
assert.deepStrictEqual(stream.closed, false)
stream.on('close', () => {
assert.deepStrictEqual(stream.closed, true)
assert.ok(!stream.writable)
done()
})
assert.deepStrictEqual(stream.writableNeedDrain, false)
assert.ok(stream.write('hello world\n'))
assert.ok(stream.write('something else\n'))
assert.ok(stream.writable)
assert.deepStrictEqual(stream.writableEnded, false)
stream.end()
assert.deepStrictEqual(stream.writableEnded, true)
})
test('overflow sync=true', function (t, done) {
const dest = file()
const stream = new ThreadStream({
bufferSize: 128,
filename: join(__dirname, 'to-file.js'),
workerData: { dest },
sync: true
})
let count = 0
// Write 10 chars, 20 times
function write () {
if (count++ === 20) {
stream.end()
return
}
stream.write('aaaaaaaaaa')
// do not wait for drain event
setImmediate(write)
}
write()
stream.on('close', () => {
readFile(dest, 'utf8', (err, data) => {
assert.ifError(err)
assert.strictEqual(data.length, 200)
done()
})
})
})
test('overflow sync=false', function (t, done) {
const dest = file()
const stream = new ThreadStream({
bufferSize: 128,
filename: join(__dirname, 'to-file.js'),
workerData: { dest },
sync: false
})
let count = 0
assert.deepStrictEqual(stream.writableNeedDrain, false)
// Write 10 chars, 20 times
function write () {
if (count++ === 20) {
stream.end()
return
}
if (!stream.write('aaaaaaaaaa')) {
assert.deepStrictEqual(stream.writableNeedDrain, true)
}
// do not wait for drain event
setImmediate(write)
}
write()
stream.on('drain', () => {
assert.deepStrictEqual(stream.writableNeedDrain, false)
})
stream.on('close', () => {
readFile(dest, 'utf8', (err, data) => {
assert.ifError(err)
assert.strictEqual(data.length, 200)
done()
})
})
})
test('over the bufferSize at startup', function (t, done) {
const dest = file()
const stream = new ThreadStream({
bufferSize: 10,
filename: join(__dirname, 'to-file.js'),
workerData: { dest },
sync: true
})
stream.on('finish', () => {
readFile(dest, 'utf8', (err, data) => {
assert.ifError(err)
assert.strictEqual(data, 'hello world\nsomething else\n')
})
})
stream.on('close', () => {
done()
})
assert.ok(stream.write('hello'))
assert.ok(stream.write(' world\n'))
assert.ok(stream.write('something else\n'))
stream.end()
})
test('over the bufferSize at startup (async)', function (t, done) {
const dest = file()
const stream = new ThreadStream({
bufferSize: 10,
filename: join(__dirname, 'to-file.js'),
workerData: { dest },
sync: false
})
assert.ok(stream.write('hello'))
assert.ok(!stream.write(' world\n'))
assert.ok(!stream.write('something else\n'))
stream.end()
stream.on('finish', () => {
readFile(dest, 'utf8', (err, data) => {
assert.ifError(err)
assert.strictEqual(data, 'hello world\nsomething else\n')
})
})
stream.on('close', () => {
done()
})
})
test('flushSync sync=false', function (t, done) {
const dest = file()
const stream = new ThreadStream({
bufferSize: 128,
filename: join(__dirname, 'to-file.js'),
workerData: { dest },
sync: false
})
stream.on('drain', () => {
stream.end()
})
stream.on('close', () => {
readFile(dest, 'utf8', (err, data) => {
assert.ifError(err)
assert.strictEqual(data.length, 200)
done()
})
})
for (let count = 0; count < 20; count++) {
stream.write('aaaaaaaaaa')
}
stream.flushSync()
})
test('pass down MessagePorts', async function (t) {
const { port1, port2 } = new MessageChannel()
const stream = new ThreadStream({
filename: join(__dirname, 'port.js'),
workerData: { port: port1 },
workerOpts: {
transferList: [port1]
},
sync: false
})
t.after(() => {
stream.end()
})
assert.ok(stream.write('hello world\n'))
assert.ok(stream.write('something else\n'))
const [strings] = await once(port2, 'message')
assert.strictEqual(strings, 'hello world\nsomething else\n')
})
test('destroy does not error', function (t, done) {
const dest = file()
const stream = new ThreadStream({
filename: join(__dirname, 'to-file.js'),
workerData: { dest },
sync: false
})
stream.on('ready', () => {
stream.worker.terminate()
})
stream.on('error', (err) => {
assert.strictEqual(err.message, 'the worker thread exited')
stream.flush((err) => {
assert.strictEqual(err.message, 'the worker has exited')
})
assert.doesNotThrow(() => stream.flushSync())
assert.doesNotThrow(() => stream.end())
done()
})
})
test('syntax error', function (t, done) {
const stream = new ThreadStream({
filename: join(__dirname, 'syntax-error.mjs')
})
stream.on('error', (err) => {
assert.strictEqual(err.message, 'Unexpected end of input')
done()
})
})

View File

@@ -0,0 +1,8 @@
import type { TSESTree } from '@typescript-eslint/types';
import { DefinitionBase } from './DefinitionBase';
import { DefinitionType } from './DefinitionType';
export declare class CatchClauseDefinition extends DefinitionBase<DefinitionType.CatchClause, TSESTree.CatchClause, null, TSESTree.Identifier> {
readonly isTypeDefinition = false;
readonly isVariableDefinition = true;
constructor(name: TSESTree.Identifier, node: CatchClauseDefinition['node']);
}