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,233 @@
'use strict';
Object.defineProperty(exports, 'commentRegex', {
get: function getCommentRegex () {
// Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data.
return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg;
}
});
Object.defineProperty(exports, 'mapFileCommentRegex', {
get: function getMapFileCommentRegex () {
// Matches sourceMappingURL in either // or /* comment styles.
return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg;
}
});
var decodeBase64;
if (typeof Buffer !== 'undefined') {
if (typeof Buffer.from === 'function') {
decodeBase64 = decodeBase64WithBufferFrom;
} else {
decodeBase64 = decodeBase64WithNewBuffer;
}
} else {
decodeBase64 = decodeBase64WithAtob;
}
function decodeBase64WithBufferFrom(base64) {
return Buffer.from(base64, 'base64').toString();
}
function decodeBase64WithNewBuffer(base64) {
if (typeof value === 'number') {
throw new TypeError('The value to decode must not be of type number.');
}
return new Buffer(base64, 'base64').toString();
}
function decodeBase64WithAtob(base64) {
return decodeURIComponent(escape(atob(base64)));
}
function stripComment(sm) {
return sm.split(',').pop();
}
function readFromFileMap(sm, read) {
var r = exports.mapFileCommentRegex.exec(sm);
// for some odd reason //# .. captures in 1 and /* .. */ in 2
var filename = r[1] || r[2];
try {
var sm = read(filename);
if (sm != null && typeof sm.catch === 'function') {
return sm.catch(throwError);
} else {
return sm;
}
} catch (e) {
throwError(e);
}
function throwError(e) {
throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack);
}
}
function Converter (sm, opts) {
opts = opts || {};
if (opts.hasComment) {
sm = stripComment(sm);
}
if (opts.encoding === 'base64') {
sm = decodeBase64(sm);
} else if (opts.encoding === 'uri') {
sm = decodeURIComponent(sm);
}
if (opts.isJSON || opts.encoding) {
sm = JSON.parse(sm);
}
this.sourcemap = sm;
}
Converter.prototype.toJSON = function (space) {
return JSON.stringify(this.sourcemap, null, space);
};
if (typeof Buffer !== 'undefined') {
if (typeof Buffer.from === 'function') {
Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
} else {
Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
}
} else {
Converter.prototype.toBase64 = encodeBase64WithBtoa;
}
function encodeBase64WithBufferFrom() {
var json = this.toJSON();
return Buffer.from(json, 'utf8').toString('base64');
}
function encodeBase64WithNewBuffer() {
var json = this.toJSON();
if (typeof json === 'number') {
throw new TypeError('The json to encode must not be of type number.');
}
return new Buffer(json, 'utf8').toString('base64');
}
function encodeBase64WithBtoa() {
var json = this.toJSON();
return btoa(unescape(encodeURIComponent(json)));
}
Converter.prototype.toURI = function () {
var json = this.toJSON();
return encodeURIComponent(json);
};
Converter.prototype.toComment = function (options) {
var encoding, content, data;
if (options != null && options.encoding === 'uri') {
encoding = '';
content = this.toURI();
} else {
encoding = ';base64';
content = this.toBase64();
}
data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content;
return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
};
// returns copy instead of original
Converter.prototype.toObject = function () {
return JSON.parse(this.toJSON());
};
Converter.prototype.addProperty = function (key, value) {
if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
return this.setProperty(key, value);
};
Converter.prototype.setProperty = function (key, value) {
this.sourcemap[key] = value;
return this;
};
Converter.prototype.getProperty = function (key) {
return this.sourcemap[key];
};
exports.fromObject = function (obj) {
return new Converter(obj);
};
exports.fromJSON = function (json) {
return new Converter(json, { isJSON: true });
};
exports.fromURI = function (uri) {
return new Converter(uri, { encoding: 'uri' });
};
exports.fromBase64 = function (base64) {
return new Converter(base64, { encoding: 'base64' });
};
exports.fromComment = function (comment) {
var m, encoding;
comment = comment
.replace(/^\/\*/g, '//')
.replace(/\*\/$/g, '');
m = exports.commentRegex.exec(comment);
encoding = m && m[4] || 'uri';
return new Converter(comment, { encoding: encoding, hasComment: true });
};
function makeConverter(sm) {
return new Converter(sm, { isJSON: true });
}
exports.fromMapFileComment = function (comment, read) {
if (typeof read === 'string') {
throw new Error(
'String directory paths are no longer supported with `fromMapFileComment`\n' +
'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
)
}
var sm = readFromFileMap(comment, read);
if (sm != null && typeof sm.then === 'function') {
return sm.then(makeConverter);
} else {
return makeConverter(sm);
}
};
// Finds last sourcemap comment in file or returns null if none was found
exports.fromSource = function (content) {
var m = content.match(exports.commentRegex);
return m ? exports.fromComment(m.pop()) : null;
};
// Finds last sourcemap comment in file or returns null if none was found
exports.fromMapFileSource = function (content, read) {
if (typeof read === 'string') {
throw new Error(
'String directory paths are no longer supported with `fromMapFileSource`\n' +
'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
)
}
var m = content.match(exports.mapFileCommentRegex);
return m ? exports.fromMapFileComment(m.pop(), read) : null;
};
exports.removeComments = function (src) {
return src.replace(exports.commentRegex, '');
};
exports.removeMapFileComments = function (src) {
return src.replace(exports.mapFileCommentRegex, '');
};
exports.generateMapFileComment = function (file, options) {
var data = 'sourceMappingURL=' + file;
return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
};

View File

@@ -0,0 +1 @@
{"version":3,"file":"blake3.d.ts","sourceRoot":"","sources":["src/blake3.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,MAAM,EAAY,MAAM,aAAa,CAAC;AAE/C,OAAO,EAGL,KAAK,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,KAAK,EACvC,MAAM,YAAY,CAAC;AAwBpB;;;;;;GAMG;AACH,MAAM,MAAM,UAAU,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,KAAK,CAAC;IAAC,OAAO,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAE1E,+CAA+C;AAC/C,qBAAa,MAAO,SAAQ,MAAM,CAAC,MAAM,CAAE,YAAW,OAAO,CAAC,MAAM,CAAC;IACnE,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,EAAE,CAAc;IACxB,OAAO,CAAC,KAAK,CAAc;IAC3B,OAAO,CAAC,KAAK,CAAqB;IAElC,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,SAAS,CAAa;IAC9B,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,SAAS,CAAQ;gBAEb,IAAI,GAAE,UAAe,EAAE,KAAK,SAAI;IA2B5C,SAAS,CAAC,GAAG,IAAI,EAAE;IAGnB,SAAS,CAAC,GAAG,IAAI,IAAI;IACrB,OAAO,CAAC,UAAU;IAmBlB,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,GAAE,MAAU,EAAE,MAAM,GAAE,OAAe,GAAG,IAAI;IAiCvF,UAAU,CAAC,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM;IAe/B,OAAO,IAAI,IAAI;IAMf,OAAO,CAAC,aAAa;IA+BrB,SAAS,CAAC,MAAM,IAAI,IAAI;IAoBxB,OAAO,CAAC,SAAS;IAcjB,OAAO,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU;IAIpC,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU;IAI9B,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU;IAQvC,MAAM,IAAI,UAAU;CAGrB;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,MAAM,EAAE,OAEpB,CAAC"}

View File

@@ -0,0 +1,81 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'no-misused-new',
meta: {
type: 'problem',
docs: {
description: 'Enforce valid definition of `new` and `constructor`',
recommended: 'recommended',
},
messages: {
errorMessageClass: 'Class cannot have method named `new`.',
errorMessageInterface: 'Interfaces cannot be constructed, only classes.',
},
schema: [],
},
defaultOptions: [],
create(context) {
/**
* @param node type to be inspected.
* @returns name of simple type or null
*/
function getTypeReferenceName(node) {
if (node) {
switch (node.type) {
case utils_1.AST_NODE_TYPES.TSTypeAnnotation:
return getTypeReferenceName(node.typeAnnotation);
case utils_1.AST_NODE_TYPES.TSTypeReference:
return getTypeReferenceName(node.typeName);
case utils_1.AST_NODE_TYPES.Identifier:
return node.name;
default:
break;
}
}
return null;
}
/**
* @param parent parent node.
* @param returnType type to be compared
*/
function isMatchingParentType(parent, returnType) {
if (parent &&
(parent.type === utils_1.AST_NODE_TYPES.ClassDeclaration ||
parent.type === utils_1.AST_NODE_TYPES.ClassExpression ||
parent.type === utils_1.AST_NODE_TYPES.TSInterfaceDeclaration) &&
parent.id) {
return getTypeReferenceName(returnType) === parent.id.name;
}
return false;
}
return {
"ClassBody > MethodDefinition[key.name='new']"(node) {
if (node.value.type === utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression &&
isMatchingParentType(node.parent.parent, node.value.returnType)) {
context.report({
node,
messageId: 'errorMessageClass',
});
}
},
'TSInterfaceBody > TSConstructSignatureDeclaration'(node) {
if (isMatchingParentType(node.parent.parent, node.returnType)) {
// constructor
context.report({
node,
messageId: 'errorMessageInterface',
});
}
},
"TSMethodSignature[key.name='constructor']"(node) {
context.report({
node,
messageId: 'errorMessageInterface',
});
},
};
},
});

View File

@@ -0,0 +1,26 @@
import { expect, test } from "vitest";
import { type infer as _infer, json, nullable, object, pipe, transform } from "../../mini/index.js";
// biome-ignore lint/correctness/noUnusedImports: This import verifies the type is exported
import type { _ZodMiniJSONSchema } from "../../mini/schemas.js";
const DataType = object({
data: json(),
});
type DataType = _infer<typeof DataType>;
// biome-ignore lint/suspicious/noExportsInTest: This export is required to reproduce TS4023
export const Container = object({
contained: pipe(
nullable(DataType),
transform<DataType | null>(
(v) =>
v ?? {
data: "",
}
)
),
});
test("issue reproduction should compile without type errors", () => {
expect(Container).toBeDefined();
});

View File

@@ -0,0 +1,5 @@
import OverloadYield from "./OverloadYield.js";
function _awaitAsyncGenerator(e) {
return new OverloadYield(e, 0);
}
export { _awaitAsyncGenerator as default };

View File

@@ -0,0 +1,43 @@
/**
* @fileoverview A class of identifiers generator for code path segments.
*
* Each rule uses the identifier of code path segments to store additional
* information of the code path.
*
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* A generator for unique ids.
*/
class IdGenerator {
/**
* @param {string} prefix Optional. A prefix of generated ids.
*/
constructor(prefix) {
this.prefix = String(prefix);
this.n = 0;
}
/**
* Generates id.
* @returns {string} A generated id.
*/
next() {
this.n = (1 + this.n) | 0;
if (this.n < 0) {
this.n = 1;
}
return this.prefix + this.n;
}
}
module.exports = IdGenerator;

View File

@@ -0,0 +1,11 @@
import { _ as _class_apply_descriptor_update } from "./_class_apply_descriptor_update.js";
import { _ as _class_check_private_static_access } from "./_class_check_private_static_access.js";
import { _ as _class_check_private_static_field_descriptor } from "./_class_check_private_static_field_descriptor.js";
function _class_static_private_field_update(receiver, classConstructor, descriptor) {
_class_check_private_static_access(receiver, classConstructor);
_class_check_private_static_field_descriptor(descriptor, "update");
return _class_apply_descriptor_update(receiver, descriptor);
}
export { _class_static_private_field_update as _ };

View File

@@ -0,0 +1,4 @@
function _initializerWarningHelper(r, e) {
throw Error("Decorating class property failed. Please ensure that transform-class-properties is enabled and runs after the decorators transform.");
}
module.exports = _initializerWarningHelper, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,7 @@
import getPrototypeOf from "./getPrototypeOf.js";
import isNativeReflectConstruct from "./isNativeReflectConstruct.js";
import possibleConstructorReturn from "./possibleConstructorReturn.js";
function _callSuper(t, o, e) {
return o = getPrototypeOf(o), possibleConstructorReturn(t, isNativeReflectConstruct() ? Reflect.construct(o, e || [], getPrototypeOf(t).constructor) : o.apply(t, e));
}
export { _callSuper as default };

View File

@@ -0,0 +1,403 @@
# @solana/buffer-layout
`@solana/buffer-layout` is a TypeScript fork of `buffer-layout`. Same API, just adds types and TypeScript docs.
## Installation
Install with `npm install @solana/buffer-layout`.
Development and testing is done using Node.js, supporting versions 5.10
and later.
# buffer-layout
[![NPM version](https://img.shields.io/npm/v/buffer-layout.svg)](https://www.npmjs.com/package/buffer-layout "View this project on NPM")
[![Build Status](https://travis-ci.org/pabigot/buffer-layout.svg?branch=master)](https://travis-ci.org/pabigot/buffer-layout "Check build status on TravisCI")
[![Coverage Status](https://coveralls.io/repos/pabigot/buffer-layout/badge.svg?branch=master&service=github)](https://coveralls.io/github/pabigot/buffer-layout?branch=master "Check coverage status on Coveralls")
buffer-layout is a utility module implemented in pure JavaScript that
supports translations between JavaScript values and Buffers. It is made
available through [github](https://github.com/pabigot/buffer-layout) and
released under the MIT license.
Layout support is provided for these types of data:
* Signed and unsigned integral values from 1 to 6 bytes in length, in
little-endian or big-endian format;
* Signed and unsigned 64-bit integral values decoded as integral
Numbers;
* Float and double values (also little-endian or big-endian);
* Sequences of instances of an arbitrary layout, with constant or
data-dependent length;
* Structures with named fields containing arbitrary layouts;
* Unions of variant layouts where the type of data is recorded in a
prefix value, another layout element, or provided externally;
* Bit fields within 8, 16, 24, or 32-bit unsigned integers, numbering
from the least or most significant bit;
* NUL-terminated C strings;
* Blobs of fixed or variable-length raw data.
## Examples
All examples are from the `test/examples.js` unit test and assume the
following context:
const assert = require('assert');
const util = require('util');
const lo = require('buffer-layout');
The examples give only a taste of what can be done. Structures, unions,
and sequences can nest; [union
discriminators](http://pabigot.github.io/buffer-layout/module-Layout-UnionDiscriminator.html)
can be within the union or external to it; sequence and blob lengths may
be fixed or read from the buffer.
For full details see the [documentation](http://pabigot.github.io/buffer-layout/).
### Four-element array of 16-bit signed little-endian integers
The C definition:
int16_t arr[4] = { 1, -1, 3, -3 };
The buffer-layout way:
const ds = lo.seq(lo.s16(), 4);
const b = Buffer.alloc(8);
assert.equal(ds.encode([1, -1, 3, -3], b), 4 * 2);
assert.equal(Buffer.from('0100ffff0300fdff', 'hex').compare(b), 0);
assert.deepEqual(ds.decode(b), [1, -1, 3, -3]);
See [Int](http://pabigot.github.io/buffer-layout/module-Layout-Int.html)
and [Sequence](http://pabigot.github.io/buffer-layout/module-Layout-Sequence.html).
### A native C `struct` on a 32-bit little-endian machine
The C definition:
struct ds {
uint8_t v;
uint32_t u32;
} st;
The buffer-layout way:
const ds = lo.struct([lo.u8('v'),
lo.seq(lo.u8(), 3), // alignment padding
lo.u32('u32')]);
assert.equal(ds.offsetOf('u32'), 4);
const b = Buffer.alloc(8);
b.fill(0xbd);
assert.equal(ds.encode({v: 1, u32: 0x12345678}, b), 1 + 3 + 4);
assert.equal(Buffer.from('01bdbdbd78563412', 'hex').compare(b), 0);
assert.deepEqual(ds.decode(b), {v: 1, u32: 0x12345678});
Note that the C language requires padding which must be explicitly added
in the buffer-layout structure definition. Since the padding is not
accessible, the corresponding layout has no
[property](http://pabigot.github.io/buffer-layout/module-Layout-Layout.html#property).
See [Structure](http://pabigot.github.io/buffer-layout/module-Layout-Structure.html).
### A packed C `struct` on a 32-bit little-endian machine
The C definition:
struct ds {
uint8_t v;
uint32_t u32;
} __attribute__((__packed__)) st;
The buffer-layout way:
const ds = lo.struct([lo.u8('v'),
lo.u32('u32')]);
assert.equal(ds.offsetOf('u32'), 1);
const b = Buffer.alloc(5);
b.fill(0xbd);
assert.equal(ds.encode({v: 1, u32: 0x12345678}, b), 1 + 4);
assert.equal(Buffer.from('0178563412', 'hex').compare(b), 0);
assert.deepEqual(ds.decode(b), {v: 1, u32: 0x12345678});
### A tagged union of 4-byte values
Assume a 5-byte packed structure where the interpretation of the last
four bytes depends on the first byte. The C definition:
struct {
uint8_t t;
union ds {
uint8_t u8[4]; // default interpretation
int16_t s16[2]; // when t is 'h'
uint32_t u32; // when t is 'w'
float f32; // when t is 'f'
} u;
} __attribute__((__packed__)) un;
The buffer-layout way:
const t = lo.u8('t');
const un = lo.union(t, lo.seq(lo.u8(), 4, 'u8'));
const nul = un.addVariant('n'.charCodeAt(0), 'nul');
const u32 = un.addVariant('w'.charCodeAt(0), lo.u32(), 'u32');
const s16 = un.addVariant('h'.charCodeAt(0), lo.seq(lo.s16(), 2), 's16');
const f32 = un.addVariant('f'.charCodeAt(0), lo.f32(), 'f32');
const b = Buffer.alloc(un.span);
assert.deepEqual(un.decode(b), {t: 0, u8: [0, 0, 0, 0]});
assert.deepEqual(un.decode(Buffer.from('6e01020304', 'hex')),
{nul: true});
assert.deepEqual(un.decode(Buffer.from('7778563412', 'hex')),
{u32: 0x12345678});
assert.deepEqual(un.decode(Buffer.from('660000bd41', 'hex')),
{f32: 23.625});
assert.deepEqual(un.decode(Buffer.from('a5a5a5a5a5', 'hex')),
{t: 0xa5, u8: [0xa5, 0xa5, 0xa5, 0xa5]});
assert.equal(s16.encode({s16: [123, -123]}, b), 1 + 2 * 2);
assert.equal(Buffer.from('687b0085ff', 'hex').compare(b), 0);
See [Union](http://pabigot.github.io/buffer-layout/module-Layout-Union.html).
### Decoding into class instances
Using the same 5-byte packet structure but with JavaScript classes
representing the union and the variants:
function Union() { }
lo.bindConstructorLayout(Union,
lo.union(lo.u8('t'), lo.seq(lo.u8(), 4, 'u8')));
function Vn() {}
util.inherits(Vn, Union);
lo.bindConstructorLayout(Vn,
Union.layout_.addVariant('n'.charCodeAt(0), 'nul'));
function Vu32(v) { this.u32 = v; }
util.inherits(Vu32, Union);
lo.bindConstructorLayout(Vu32,
Union.layout_.addVariant('w'.charCodeAt(0), lo.u32(), 'u32'));
function Vs16(v) { this.s16 = v; }
util.inherits(Vs16, Union);
lo.bindConstructorLayout(Vs16,
Union.layout_.addVariant('h'.charCodeAt(0), lo.seq(lo.s16(), 2), 's16'));
function Vf32(v) { this.f32 = v; }
util.inherits(Vf32, Union);
lo.bindConstructorLayout(Vf32,
Union.layout_.addVariant('f'.charCodeAt(0), lo.f32(), 'f32'));
let v = Union.decode(Buffer.from('7778563412', 'hex'));
assert(v instanceof Vu32);
assert(v instanceof Union);
assert.equal(v.u32, 0x12345678);
v = Union.decode(Buffer.from('a5a5a5a5a5', 'hex'));
assert(v instanceof Union);
assert.equal(v.t, 0xa5);
assert.deepEqual(v.u8, [0xa5, 0xa5, 0xa5, 0xa5]);
const b = Buffer.alloc(Union.layout_.span);
v = new Vf32(23.625);
v.encode(b);
assert.equal(Buffer.from('660000bd41', 'hex').compare(b), 0);
b.fill(0xFF);
v = new Vn();
v.encode(b);
assert.equal(Buffer.from('6effffffff', 'hex').compare(b), 0);
Note that one variant (`'n'`) carries no data, leaving the remainder of
the buffer unchanged when stored.
See
[Layout.makeDestinationObject()](http://pabigot.github.io/buffer-layout/module-Layout-Layout.html#makeDestinationObject)
and
[bindConstructorLayout](http://pabigot.github.io/buffer-layout/module-Layout.html#.bindConstructorLayout).
### Packed bit fields on a little-endian machine
The C definition:
struct ds {
unsigned int b00l03: 3;
unsigned int flg03: 1;
unsigned int b04l18: 24;
unsigned int b1Cl04: 4;
} st;
The buffer-layout way:
const ds = lo.bits(lo.u32());
const b = Buffer.alloc(4);
ds.addField(3, 'b00l03');
ds.addBoolean('flg03');
ds.addField(24, 'b04l18');
ds.addField(4, 'b1Cl04');
b.fill(0xff);
assert.equal(ds.encode({b00l03: 3, b04l18: 24, b1Cl04: 4}, b), 4);
assert.equal(Buffer.from('8b010040', 'hex').compare(b), 0);
assert.deepEqual(ds.decode(b),
{b00l03: 3, flg03: true, b04l18: 24, b1Cl04: 4});
See [BitStructure](http://pabigot.github.io/buffer-layout/module-Layout-BitStructure.html).
### 64-bit values as Numbers
The C definition:
uint64_t v = 0x0102030405060708ULL;
The buffer-layout way:
const ds = lo.nu64be();
const b = Buffer.from('0102030405060708', 'hex');
const v = 72623859790382856;
const nv = v - 6;
assert.equal(v, nv);
assert.equal(ds.decode(b), nv);
Note that because the exact value is not less than 2^53 it cannot be
represented as a JavaScript Number, and is instead approximated by a
nearby representable integer that is equivalent within Numbers.
See [NearUInt64](http://pabigot.github.io/buffer-layout/module-Layout-NearUInt64.html).
### A NUL-terminated C string
The C definition:
const char str[] = "hi!";
The buffer-layout way:
const ds = lo.cstr();
const b = Buffer.alloc(8);
assert.equal(ds.encode('hi!', b), 3 + 1);
const slen = ds.getSpan(b);
assert.equal(slen, 4);
assert.equal(Buffer.from('68692100', 'hex').compare(b.slice(0, slen)), 0);
assert.equal(ds.decode(b), 'hi!');
See [CString](http://pabigot.github.io/buffer-layout/module-Layout-CString.html).
### A fixed-length block of data offset within a buffer
The buffer-layout way:
const ds = lo.blob(4);
const b = Buffer.from('0102030405060708', 'hex');
assert.equal(Buffer.from('03040506', 'hex').compare(ds.decode(b, 2)), 0);
See [Blob](http://pabigot.github.io/buffer-layout/module-Layout-Blob.html).
### A variable-length array of pairs of C strings
The buffer-layout way:
const pr = lo.seq(lo.cstr(), 2);
const n = lo.u8('n');
const vla = lo.seq(pr, lo.offset(n, -1), 'a');
const st = lo.struct([n, vla], 'st');
const b = Buffer.alloc(32);
const arr = [['k1', 'v1'], ['k2', 'v2'], ['k3', 'etc']];
b.fill(0);
assert.equal(st.encode({a: arr}, b),
1 + (2 * ((2 + 1) + (2 + 1)) + (2 + 1) + (3 + 1)));
const span = st.getSpan(b);
assert.equal(span, 20);
assert.equal(Buffer.from('036b31007631006b32007632006b330065746300', 'hex')
.compare(b.slice(0, span)), 0);
assert.deepEqual(st.decode(b), {n: 3, a: arr});
See [OffsetLayout](http://pabigot.github.io/buffer-layout/module-Layout-OffsetLayout.html).
### A C flexible array member with implicit length
When data is obtained over a packetized interface the length of the
packet can provide implicit limits on the last field.
The C definition:
struct ds {
uint8_t prop;
uint16_t data[];
};
The buffer-layout way:
const st = lo.struct([lo.u8('prop'),
lo.seq(lo.u16(),
lo.greedy(lo.u16().span),
'data')],
'ds');
const b = Buffer.from('21010002030405', 'hex');
assert.deepEqual(st.decode(b), {prop: 33, data: [0x0001, 0x0302, 0x0504]});
b.fill(0xFF);
assert.equal(st.encode({prop: 9, data: [5, 6]}, b), 1 + 2 * 2);
assert.equal(Buffer.from('0905000600FFFF', 'hex').compare(b), 0);
### Tagged values, or variable-length unions
Storing arbitrary data using a leading byte to identify the content then
a value that takes up only as much room as is necessary.
The example also shows how to extend the variant recognition API to
support abitrary constant without consuming space for them in the
encoded union. This could be used to make something similar to
[BSON](http://bsonspec.org/spec.html).
Here's the code that defines the union, the variants, and the
recognition of `true` and `false` values for `b` as distinct variants:
const un = lo.union(lo.u8('t'));
const u8 = un.addVariant('B'.charCodeAt(0), lo.u8(), 'u8');
const s16 = un.addVariant('h'.charCodeAt(0), lo.s16(), 's16');
const s48 = un.addVariant('Q'.charCodeAt(0), lo.s48(), 's48');
const cstr = un.addVariant('s'.charCodeAt(0), lo.cstr(), 'str');
const tr = un.addVariant('T'.charCodeAt(0), lo.const(true), 'b');
const fa = un.addVariant('F'.charCodeAt(0), lo.const(false), 'b');
const b = Buffer.alloc(1 + 6);
un.configGetSourceVariant(function(src) {
if (src.hasOwnProperty('b')) {
return src.b ? tr : fa;
}
return this.defaultGetSourceVariant(src);
});
And here are examples of encoding, checking the encoded length, and
decoding each of the alternatives:
b.fill(0xff);
assert.equal(un.encode({u8: 1}, b), 1 + 1);
assert.equal(un.getSpan(b), 2);
assert.equal(Buffer.from('4201ffffffffff', 'hex').compare(b), 0);
assert.equal(un.decode(b).u8, 1);
b.fill(0xff);
assert.equal(un.encode({s16: -32000}, b), 1 + 2);
assert.equal(un.getSpan(b), 3);
assert.equal(Buffer.from('680083ffffffff', 'hex').compare(b), 0);
assert.equal(un.decode(b).s16, -32000);
b.fill(0xff);
const v48 = Math.pow(2, 47) - 1;
assert.equal(un.encode({s48: v48}, b), 1 + 6);
assert.equal(un.getSpan(b), 7);
assert.equal(Buffer.from('51ffffffffff7f', 'hex').compare(b), 0);
assert.equal(un.decode(b).s48, v48);
b.fill(0xff);
assert.equal(un.encode({b: true}, b), 1);
assert.equal(un.getSpan(b), 1);
assert.equal(Buffer.from('54ffffffffffff', 'hex').compare(b), 0);
assert.strictEqual(un.decode(b).b, true);
b.fill(0xff);
assert.equal(un.encode({b: false}, b), 1);
assert.equal(un.getSpan(b), 1);
assert.equal(Buffer.from('46ffffffffffff', 'hex').compare(b), 0);
assert.strictEqual(un.decode(b).b, false);
**NOTE** This code tickles a long-standing [bug in
Buffer.writeInt{L,B}E](https://github.com/nodejs/node/pull/3994); if you
are using Node prior to 4.2.4 or 5.2.0 you should update.

View File

@@ -0,0 +1,140 @@
# `@humanfs/core`
by [Nicholas C. Zakas](https://humanwhocodes.com)
If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate) or [nominate me](https://stars.github.com/nominate/) for a GitHub Star.
## Description
The core functionality for humanfs that is shared across all implementations for all runtimes. The contents of this package are intentionally runtime agnostic and are not intended to be used alone.
Currently, this package simply exports the `Hfs` class, which is an abstract base class intended to be inherited from in runtime-specific hfs packages (like `@humanfs/node`).
> [!WARNING]
> This project is **experimental** and may change significantly before v1.0.0. Use at your own caution and definitely not in production!
## Installation
### Node.js
Install using your favorite package manager for Node.js:
```shell
npm install @humanfs/core
# or
pnpm install @humanfs/core
# or
yarn add @humanfs/core
# or
bun install @humanfs/core
```
Then you can import the `Hfs` and `Path` classes like this:
```js
import { Hfs, Path } from "@humanfs/core";
```
### Deno
Install using [JSR](https://jsr.io):
```shell
deno add @humanfs/core
# or
jsr add @humanfs/core
```
Then you can import the `Hfs` class like this:
```js
import { Hfs, Path } from "@humanfs/core";
```
### Browser
It's recommended to import the minified version to save bandwidth:
```js
import { Hfs, Path } from "https://cdn.skypack.dev/@humanfs/core?min";
```
However, you can also import the unminified version for debugging purposes:
```js
import { Hfs, Path } from "https://cdn.skypack.dev/@humanfs/core";
```
## Usage
### `Hfs` Class
The `Hfs` class contains all of the basic functionality for an `Hfs` instance *without* a predefined impl. This class is mostly used for creating runtime-specific impls, such as `NodeHfs` and `DenoHfs`.
You can create your own instance by providing an `impl` directly:
```js
const hfs = new Hfs({ impl: { async text() {} }});
```
The specified `impl` becomes the base impl for the instance, meaning you can always reset back to it using `resetImpl()`.
You can also inherit from `Hfs` to create your own class with a preconfigured impl, such as:
```js
class MyHfs extends Hfs {
constructor() {
super({
impl: myImpl
});
}
}
```
### `Path` Class
The `Path` class represents the path to a directory or file within a file system. It's an abstract representation that can be used even outside of traditional file systems where string paths might not make sense.
```js
const myPath = new Path(["dir", "subdir"]);
console.log(myPath.toString()); // "dir/subdir"
// add another step
myPath.push("file.txt");
console.log(myPath.toString()); // "dir/subdir/file.txt"
// get just the last step
console.log(myPath.name); // "file.txt"
// change just the last step
myPath.name = "file.json";
console.log(myPath.name); // "file.json"
console.log(myPath.toString()); // "dir/subdir/file.json"
// get the size of the path
console.log(myPath.size); // 3
// remove the last step
myPath.pop();
console.log(myPath.toString()); // "dir/subdir"
// iterate over the steps
for (const step of myPath) {
// do something
}
// create a new path from a string
const newPath = Path.fromString("/foo/bar");
```
## License
Apache 2.0

View File

@@ -0,0 +1,32 @@
<h1 align="center">
<br>
<picture>
<source media="(prefers-color-scheme: dark)" srcset=".github/logo-dark.svg">
<img width="160" alt="tsx" src=".github/logo-light.svg">
</picture>
<br><br>
<a href="https://npm.im/tsx"><img src="https://badgen.net/npm/v/tsx"></a> <a href="https://npm.im/tsx"><img src="https://badgen.net/npm/dm/tsx"></a>
</h1>
<p align="center">
TypeScript Execute (tsx): The easiest way to run TypeScript in Node.js
<br><br>
<a href="https://tsx.hirok.io">Documentation</a>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;<a href="https://tsx.hirok.io/getting-started">Getting started →</a>
</p>
<br>
<p align="center">
<a href="https://github.com/sponsors/privatenumber/sponsorships?tier_id=398771"><img width="412" src="https://raw.githubusercontent.com/privatenumber/sponsors/master/banners/assets/donate.webp"></a>
<a href="https://github.com/sponsors/privatenumber/sponsorships?tier_id=416984"><img width="412" src="https://raw.githubusercontent.com/privatenumber/sponsors/master/banners/assets/sponsor.webp"></a>
</p>
<p align="center"><sup><i>Already a sponsor?</i> Join the discussion in the <a href="https://github.com/pvtnbr/tsx">Development repo</a>!</sup></p>
## Sponsors
<p align="center">
<a href="https://github.com/sponsors/privatenumber">
<img src="https://cdn.jsdelivr.net/gh/privatenumber/sponsors/sponsorkit/sponsors.svg">
</a>
</p>

View File

@@ -0,0 +1,29 @@
import { Struct, Coercer } from '../struct.js';
/**
* Augment a `Struct` to add an additional coercion step to its input.
*
* This allows you to transform input data before validating it, to increase the
* likelihood that it passes validation—for example for default values, parsing
* different formats, etc.
*
* Note: You must use `create(value, Struct)` on the value to have the coercion
* take effect! Using simply `assert()` or `is()` will not use coercion.
*/
export declare function coerce<T, S, C>(struct: Struct<T, S>, condition: Struct<C, any>, coercer: Coercer<C>): Struct<T, S>;
/**
* Augment a struct to replace `undefined` values with a default.
*
* Note: You must use `create(value, Struct)` on the value to have the coercion
* take effect! Using simply `assert()` or `is()` will not use coercion.
*/
export declare function defaulted<T, S>(struct: Struct<T, S>, fallback: any, options?: {
strict?: boolean;
}): Struct<T, S>;
/**
* Augment a struct to trim string inputs.
*
* Note: You must use `create(value, Struct)` on the value to have the coercion
* take effect! Using simply `assert()` or `is()` will not use coercion.
*/
export declare function trimmed<T, S>(struct: Struct<T, S>): Struct<T, S>;
//# sourceMappingURL=coercions.d.ts.map

View File

@@ -0,0 +1,148 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const scope_manager_1 = require("@typescript-eslint/scope-manager");
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
const UNNECESSARY_OPERATORS = new Set(['??=', '&&=', '=', '||=']);
exports.default = (0, util_1.createRule)({
name: 'no-unnecessary-parameter-property-assignment',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow unnecessary assignment of constructor property parameter',
},
messages: {
unnecessaryAssign: 'This assignment is unnecessary since it is already assigned by a parameter property.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const reportInfoStack = [];
function isThisMemberExpression(node) {
return (node.type === utils_1.AST_NODE_TYPES.MemberExpression &&
node.object.type === utils_1.AST_NODE_TYPES.ThisExpression);
}
function getPropertyName(node) {
if (!isThisMemberExpression(node)) {
return null;
}
if (!node.computed && node.property.type === utils_1.AST_NODE_TYPES.Identifier) {
return node.property.name;
}
if (node.computed) {
return (0, util_1.getStaticStringValue)(node.property);
}
return null;
}
function findParentFunction(node) {
if (!node ||
node.type === utils_1.AST_NODE_TYPES.FunctionDeclaration ||
node.type === utils_1.AST_NODE_TYPES.FunctionExpression ||
node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression) {
return node;
}
return findParentFunction(node.parent);
}
function findParentPropertyDefinition(node) {
if (!node || node.type === utils_1.AST_NODE_TYPES.PropertyDefinition) {
return node;
}
return findParentPropertyDefinition(node.parent);
}
function isConstructorFunctionExpression(node) {
return (node?.type === utils_1.AST_NODE_TYPES.FunctionExpression &&
utils_1.ASTUtils.isConstructor(node.parent));
}
function isReferenceFromParameter(node) {
const scope = context.sourceCode.getScope(node);
const rightRef = scope.references.find(ref => ref.identifier.name === node.name);
return rightRef?.resolved?.defs.at(0)?.type === scope_manager_1.DefinitionType.Parameter;
}
function isParameterPropertyWithName(node, name) {
return (node.type === utils_1.AST_NODE_TYPES.TSParameterProperty &&
((node.parameter.type === utils_1.AST_NODE_TYPES.Identifier && // constructor (public foo) {}
node.parameter.name === name) ||
(node.parameter.type === utils_1.AST_NODE_TYPES.AssignmentPattern && // constructor (public foo = 1) {}
node.parameter.left.name === name)));
}
function getIdentifier(node) {
if (node.type === utils_1.AST_NODE_TYPES.Identifier) {
return node;
}
if (node.type === utils_1.AST_NODE_TYPES.TSAsExpression ||
node.type === utils_1.AST_NODE_TYPES.TSNonNullExpression) {
return getIdentifier(node.expression);
}
return null;
}
function isArrowIIFE(node) {
return (node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression &&
node.parent.type === utils_1.AST_NODE_TYPES.CallExpression);
}
return {
ClassBody() {
reportInfoStack.push({
assignedBeforeConstructor: new Set(),
assignedBeforeUnnecessary: new Set(),
unnecessaryAssignments: [],
});
},
'ClassBody:exit'() {
const { assignedBeforeConstructor, unnecessaryAssignments } = (0, util_1.nullThrows)(reportInfoStack.pop(), 'The top stack should exist');
unnecessaryAssignments.forEach(({ name, node }) => {
if (assignedBeforeConstructor.has(name)) {
return;
}
context.report({
node,
messageId: 'unnecessaryAssign',
});
});
},
"MethodDefinition[kind='constructor'] > FunctionExpression AssignmentExpression"(node) {
const leftName = getPropertyName(node.left);
if (!leftName) {
return;
}
let functionNode = findParentFunction(node);
if (functionNode && isArrowIIFE(functionNode)) {
functionNode = findParentFunction(functionNode.parent);
}
if (!isConstructorFunctionExpression(functionNode)) {
return;
}
const { assignedBeforeUnnecessary, unnecessaryAssignments } = (0, util_1.nullThrows)(reportInfoStack.at(reportInfoStack.length - 1), 'The top of stack should exist');
if (!UNNECESSARY_OPERATORS.has(node.operator)) {
assignedBeforeUnnecessary.add(leftName);
return;
}
const rightId = getIdentifier(node.right);
if (leftName !== rightId?.name || !isReferenceFromParameter(rightId)) {
return;
}
const hasParameterProperty = functionNode.params.some(param => isParameterPropertyWithName(param, rightId.name));
if (hasParameterProperty && !assignedBeforeUnnecessary.has(leftName)) {
unnecessaryAssignments.push({
name: leftName,
node,
});
}
},
'PropertyDefinition AssignmentExpression'(node) {
const name = getPropertyName(node.left);
if (!name) {
return;
}
const functionNode = findParentFunction(node);
if (functionNode &&
!(isArrowIIFE(functionNode) &&
findParentPropertyDefinition(node)?.value === functionNode.parent)) {
return;
}
const { assignedBeforeConstructor } = (0, util_1.nullThrows)(reportInfoStack.at(-1), 'The top stack should exist');
assignedBeforeConstructor.add(name);
},
};
},
});

View File

@@ -0,0 +1,3 @@
import * as z from "./external.cjs";
export * from "./external.cjs";
export { z };

View File

@@ -0,0 +1,8 @@
import { TSESLint } from '@typescript-eslint/utils';
import type { Selector } from './naming-convention-utils';
export type MessageIds = 'doesNotMatchFormat' | 'doesNotMatchFormatTrimmed' | 'missingAffix' | 'missingUnderscore' | 'satisfyCustom' | 'unexpectedUnderscore';
export type Options = Selector[];
declare const _default: TSESLint.RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, TSESLint.RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,192 @@
/**
* @fileoverview The types file for the hfs package.
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// HfsImpl
//------------------------------------------------------------------------------
export interface HfsImpl {
/**
* Reads the given file and returns the contents as an Uint8Array.
* @param filePath The file to read.
* @returns The contents of the file as a Uint8Array or undefined if the file is empty.
*/
bytes?(filePath: string|URL): Promise<Uint8Array|undefined>;
/**
* Writes the given data to the given file. For text, assumes UTF-8 encoding.
* @param filePath The file to write to.
* @param data The data to write.
* @returns A promise that resolves when the file is written.
* @throws {Error} If the file cannot be written.
*/
write?(filePath: string|URL, data: Uint8Array): Promise<void>;
/**
* Appends the given data to the given file. For text, assumes UTF-8 encoding.
* @param filePath The file to append to.
* @param data The data to append.
* @returns A promise that resolves when the file is written.
* @throws {Error} If the file cannot be written.
*/
append?(filePath: string|URL, data: Uint8Array): Promise<void>;
/**
* Checks if the given file exists.
* @param filePath The file to check.
* @returns True if the file exists, false if not.
* @throws {Error} If the operation fails with a code other than ENOENT.
*/
isFile?(filePath: string|URL): Promise<boolean>;
/**
* Checks if the given directory exists.
* @param dirPath The directory to check.
* @returns True if the directory exists, false if not.
* @throws {Error} If the operation fails with a code other than ENOENT.
*/
isDirectory?(dirPath: string|URL): Promise<boolean>;
/**
* Creates the given directory, including any necessary parents.
* @param dirPath The directory to create.
* @returns A promise that resolves when the directory is created.
* @throws {Error} If the directory cannot be created.
*/
createDirectory?(dirPath: string|URL): Promise<void>;
/**
* Deletes the given file or empty directory.
* @param fileOrDirPath The file or directory to delete.
* @returns A promise that resolves when the file or directory is deleted,
* true if the file or directory was deleted, false if it did not exist.
* @throws {Error} If the file or directory cannot be deleted.
*/
delete?(fileOrDirPath: string|URL): Promise<boolean>;
/**
* Deletes the given file or directory recursively.
* @param fileOrDirPath The file or directory to delete.
* @returns A promise that resolves when the file or directory is deleted,
* true if the file or directory was deleted, false if it did not exist.
* @throws {Error} If the file or directory cannot be deleted.
*/
deleteAll?(fileOrDirPath: string|URL): Promise<boolean>;
/**
* Returns a list of directory entries for the given path.
* @param dirPath The path to the directory to read.
* @returns A promise that resolves with the
* directory entries.
* @throws {TypeError} If the directory path is not a string.
* @throws {Error} If the directory cannot be read.
*/
list?(dirPath: string|URL): AsyncIterable<HfsDirectoryEntry>;
/**
* Returns the size of the given file.
* @param filePath The path to the file to check.
* @returns A promise that resolves with the size of the file in bytes or
* undefined if the file does not exist.
* @throws {Error} If the file cannot be read.
*/
size?(filePath: string|URL): Promise<number|undefined>;
/**
* Returns the last modified date of the given file or directory.
* @param fileOrDirPath The path to the file or directory to check.
* @returns A promise that resolves with the last modified date of the file or
* directory, undefined if the file does not exist.
* @throws {Error} If the file or directory cannot be read.
*/
lastModified?(fileOrDirPath: string|URL): Promise<Date|undefined>;
/**
* Copies the file from the source path to the destination path.
* @param source The source file to copy.
* @param destination The destination file to copy to.
* @returns A promise that resolves when the file is copied.
* @throws {Error} If the file cannot be copied.
*/
copy?(source: string|URL, destination: string|URL): Promise<void>;
/**
* Copies a file or directory from one location to another.
* @param source The path to the file or directory to copy.
* @param destination The path to copy the file or directory to.
* @returns A promise that resolves when the file or directory is
* copied.
* @throws {Error} If the source file or directory does not exist.
* @throws {Error} If the source cannot be read.
*/
copyAll?(source: string|URL, destination: string|URL): Promise<void>;
/**
* Moves a file from the source path to the destination path.
* @param source The location of the file to move.
* @param destination The destination of the file to move.
* @returns A promise that resolves when the file is moved.
* @throws {Error} If the source is a directory.
* @throws {Error} If the file cannot be moved.
*/
move?(source: string|URL, destination: string|URL): Promise<void>;
/**
* Moves a file or directory from one location to another.
* @param source The path to the file or directory to move.
* @param destination The path to move the file or directory to.
* @returns A promise that resolves when the file or directory is
* moved.
* @throws {Error} If the source file or directory does not exist.
* @throws {Error} If the source cannot be read.
*/
moveAll?(source: string|URL, destination: string|URL): Promise<void>;
}
//------------------------------------------------------------------------------
// HfsDirectoryEntry
//------------------------------------------------------------------------------
export interface HfsDirectoryEntry {
/**
* The name of the file or directory.
*/
name: string;
/**
* True if the entry is a directory, false if not.
*/
isDirectory: boolean;
/**
* True if the entry is a file, false if not.
*/
isFile: boolean;
/**
* True if the entry is a symbolic link, false if not.
*/
isSymlink: boolean;
}
//------------------------------------------------------------------------------
// HfsWalkEntry
//------------------------------------------------------------------------------
export interface HfsWalkEntry extends HfsDirectoryEntry {
/**
* The path of the entry relative to the directory that was walked.
*/
path: string;
/**
* The depth of the entry in the directory tree from the directory that was walked.
*/
depth: number;
}

View File

@@ -0,0 +1,67 @@
import Container from './container.js'
import Node, { NodeProps } from './node.js'
declare namespace Comment {
export interface CommentRaws extends Record<string, unknown> {
/**
* The space symbols before the node.
*/
before?: string
/**
* The space symbols between `/*` and the comments text.
*/
left?: string
/**
* The space symbols between the comments text.
*/
right?: string
}
export interface CommentProps extends NodeProps {
/** Information used to generate byte-to-byte equal node string as it was in the origin input. */
raws?: CommentRaws
/** Content of the comment. */
text: string
}
export { Comment_ as default }
}
/**
* It represents a class that handles
* [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments)
*
* ```js
* Once (root, { Comment }) {
* const note = new Comment({ text: 'Note: …' })
* root.append(note)
* }
* ```
*
* Remember that CSS comments inside selectors, at-rule parameters,
* or declaration values will be stored in the `raws` properties
* explained above.
*/
declare class Comment_ extends Node {
parent: Container | undefined
raws: Comment.CommentRaws
type: 'comment'
/**
* The comment's text.
*/
get text(): string
set text(value: string)
constructor(defaults?: Comment.CommentProps)
assign(overrides: Comment.CommentProps | object): this
clone(overrides?: Partial<Comment.CommentProps>): this
cloneAfter(overrides?: Partial<Comment.CommentProps>): this
cloneBefore(overrides?: Partial<Comment.CommentProps>): this
}
declare class Comment extends Comment_ {}
export = Comment

View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefinitionType = void 0;
var DefinitionType;
(function (DefinitionType) {
DefinitionType["CatchClause"] = "CatchClause";
DefinitionType["ClassName"] = "ClassName";
DefinitionType["FunctionName"] = "FunctionName";
DefinitionType["ImplicitGlobalVariable"] = "ImplicitGlobalVariable";
DefinitionType["ImportBinding"] = "ImportBinding";
DefinitionType["Parameter"] = "Parameter";
DefinitionType["TSEnumName"] = "TSEnumName";
DefinitionType["TSEnumMember"] = "TSEnumMemberName";
DefinitionType["TSModuleName"] = "TSModuleName";
DefinitionType["Type"] = "Type";
DefinitionType["Variable"] = "Variable";
})(DefinitionType || (exports.DefinitionType = DefinitionType = {}));

View File

@@ -0,0 +1,73 @@
/**
* @fileoverview A rule to disallow modifying variables that are declared using `const`
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const CONSTANT_BINDINGS = new Set(["const", "using", "await using"]);
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
docs: {
description:
"Disallow reassigning `const`, `using`, and `await using` variables",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-const-assign",
},
schema: [],
messages: {
const: "'{{name}}' is constant.",
},
},
create(context) {
const sourceCode = context.sourceCode;
/**
* Finds and reports references that are non initializer and writable.
* @param {Variable} variable A variable to check.
* @returns {void}
*/
function checkVariable(variable) {
astUtils
.getModifyingReferences(variable.references)
.forEach(reference => {
context.report({
node: reference.identifier,
messageId: "const",
data: { name: reference.identifier.name },
});
});
}
return {
VariableDeclaration(node) {
if (CONSTANT_BINDINGS.has(node.kind)) {
sourceCode
.getDeclaredVariables(node)
.forEach(checkVariable);
}
},
};
},
};

View File

@@ -0,0 +1,285 @@
import { balanced } from '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;
export const 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.
export const 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 = 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;
}
export function expand(str, options = {}) {
if (!str) {
return [];
}
const { max = EXPANSION_MAX, maxLength = 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 = 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,55 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}
{{
var $idx = 'i' + $lvl
, $dataNxt = $it.dataLevel = it.dataLevel + 1
, $nextData = 'data' + $dataNxt
, $currentBaseId = it.baseId
, $nonEmptySchema = {{# def.nonEmptySchema:$schema }};
}}
var {{=$errs}} = errors;
var {{=$valid}};
{{? $nonEmptySchema }}
{{# def.setCompositeRule }}
{{
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
}}
var {{=$nextValid}} = false;
for (var {{=$idx}} = 0; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) {
{{
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
var $passData = $data + '[' + $idx + ']';
$it.dataPathArr[$dataNxt] = $idx;
}}
{{# def.generateSubschemaCode }}
{{# def.optimizeValidate }}
if ({{=$nextValid}}) break;
}
{{# def.resetCompositeRule }}
{{= $closingBraces }}
if (!{{=$nextValid}}) {
{{??}}
if ({{=$data}}.length == 0) {
{{?}}
{{# def.error:'contains' }}
} else {
{{? $nonEmptySchema }}
{{# def.resetErrors }}
{{?}}
{{? it.opts.allErrors }} } {{?}}

View File

@@ -0,0 +1,497 @@
{
"typesMap": {
"jquery": {
"match": "jquery(-(\\.?\\d+)+)?(\\.intellisense)?(\\.min)?\\.js$",
"types": ["jquery"]
},
"WinJS": {
"match": "^(.*\\/winjs-[.\\d]+)\\/js\\/base\\.js$",
"exclude": [["^", 1, "/.*"]],
"types": ["winjs"]
},
"Kendo": {
"match": "^(.*\\/kendo(-ui)?)\\/kendo\\.all(\\.min)?\\.js$",
"exclude": [["^", 1, "/.*"]],
"types": ["kendo-ui"]
},
"Office Nuget": {
"match": "^(.*\\/office\\/1)\\/excel-\\d+\\.debug\\.js$",
"exclude": [["^", 1, "/.*"]],
"types": ["office"]
},
"References": {
"match": "^(.*\\/_references\\.js)$",
"exclude": [["^", 1, "$"]]
},
"Datatables.net": {
"match": "^.*\\/(jquery\\.)?dataTables(\\.all)?(\\.min)?\\.js$",
"types": ["datatables.net"]
},
"Ace": {
"match": "^(.*)\\/ace.js",
"exclude": [["^", 1, "/.*"]],
"types": ["ace"]
}
},
"simpleMap": {
"accounting": "accounting",
"ace.js": "ace",
"ag-grid": "ag-grid",
"alertify": "alertify",
"alt": "alt",
"amcharts.js": "amcharts",
"amplify": "amplifyjs",
"angular": "angular",
"angular-bootstrap-lightbox": "angular-bootstrap-lightbox",
"angular-cookie": "angular-cookie",
"angular-file-upload": "angular-file-upload",
"angularfire": "angularfire",
"angular-gettext": "angular-gettext",
"angular-google-analytics": "angular-google-analytics",
"angular-local-storage": "angular-local-storage",
"angularLocalStorage": "angularLocalStorage",
"angular-scroll": "angular-scroll",
"angular-spinner": "angular-spinner",
"angular-strap": "angular-strap",
"angulartics": "angulartics",
"angular-toastr": "angular-toastr",
"angular-translate": "angular-translate",
"angular-ui-router": "angular-ui-router",
"angular-ui-tree": "angular-ui-tree",
"angular-wizard": "angular-wizard",
"async": "async",
"atmosphere": "atmosphere",
"aws-sdk": "aws-sdk",
"aws-sdk-js": "aws-sdk",
"axios": "axios",
"backbone": "backbone",
"backbone.layoutmanager": "backbone.layoutmanager",
"backbone.paginator": "backbone.paginator",
"backbone.radio": "backbone.radio",
"backbone-associations": "backbone-associations",
"backbone-relational": "backbone-relational",
"backgrid": "backgrid",
"Bacon": "baconjs",
"benchmark": "benchmark",
"blazy": "blazy",
"bliss": "blissfuljs",
"bluebird": "bluebird",
"body-parser": "body-parser",
"bootbox": "bootbox",
"bootstrap": "bootstrap",
"bootstrap-editable": "x-editable",
"bootstrap-maxlength": "bootstrap-maxlength",
"bootstrap-notify": "bootstrap-notify",
"bootstrap-slider": "bootstrap-slider",
"bootstrap-switch": "bootstrap-switch",
"bowser": "bowser",
"breeze": "breeze",
"browserify": "browserify",
"bson": "bson",
"c3": "c3",
"canvasjs": "canvasjs",
"chai": "chai",
"chalk": "chalk",
"chance": "chance",
"chartist": "chartist",
"cheerio": "cheerio",
"chokidar": "chokidar",
"chosen.jquery": "chosen",
"chroma": "chroma-js",
"ckeditor.js": "ckeditor",
"cli-color": "cli-color",
"clipboard": "clipboard",
"codemirror": "codemirror",
"colors": "colors",
"commander": "commander",
"commonmark": "commonmark",
"compression": "compression",
"confidence": "confidence",
"connect": "connect",
"Control.FullScreen": "leaflet.fullscreen",
"cookie": "cookie",
"cookie-parser": "cookie-parser",
"cookies": "cookies",
"core": "core-js",
"core-js": "core-js",
"crossfilter": "crossfilter",
"crossroads": "crossroads",
"css": "css",
"ct-ui-router-extras": "ui-router-extras",
"d3": "d3",
"dagre-d3": "dagre-d3",
"dat.gui": "dat-gui",
"debug": "debug",
"deep-diff": "deep-diff",
"Dexie": "dexie",
"dialogs": "angular-dialog-service",
"dojo.js": "dojo",
"doT": "dot",
"dragula": "dragula",
"drop": "drop",
"dropbox": "dropboxjs",
"dropzone": "dropzone",
"Dts Name": "Dts Name",
"dust-core": "dustjs-linkedin",
"easeljs": "easeljs",
"ejs": "ejs",
"ember": "ember",
"envify": "envify",
"epiceditor": "epiceditor",
"es6-promise": "es6-promise",
"ES6-Promise": "es6-promise",
"es6-shim": "es6-shim",
"expect": "expect",
"express": "express",
"express-session": "express-session",
"ext-all.js": "extjs",
"extend": "extend",
"fabric": "fabricjs",
"faker": "faker",
"fastclick": "fastclick",
"favico": "favico.js",
"featherlight": "featherlight",
"FileSaver": "FileSaver",
"fingerprint": "fingerprintjs",
"fixed-data-table": "fixed-data-table",
"flickity.pkgd": "flickity",
"flight": "flight",
"flow": "flowjs",
"Flux": "flux",
"formly": "angular-formly",
"foundation": "foundation",
"fpsmeter": "fpsmeter",
"fuse": "fuse",
"generator": "yeoman-generator",
"gl-matrix": "gl-matrix",
"globalize": "globalize",
"graceful-fs": "graceful-fs",
"gridstack": "gridstack",
"gulp": "gulp",
"gulp-rename": "gulp-rename",
"gulp-uglify": "gulp-uglify",
"gulp-util": "gulp-util",
"hammer": "hammerjs",
"handlebars": "handlebars",
"hasher": "hasher",
"he": "he",
"hello.all": "hellojs",
"highcharts.js": "highcharts",
"highlight": "highlightjs",
"history": "history",
"History": "history",
"hopscotch": "hopscotch",
"hotkeys": "angular-hotkeys",
"html2canvas": "html2canvas",
"humane": "humane",
"i18next": "i18next",
"icheck": "icheck",
"impress": "impress",
"incremental-dom": "incremental-dom",
"Inquirer": "inquirer",
"insight": "insight",
"interact": "interactjs",
"intercom": "intercomjs",
"intro": "intro.js",
"ion.rangeSlider": "ion.rangeSlider",
"ionic": "ionic",
"is": "is_js",
"iscroll": "iscroll",
"jade": "jade",
"jasmine": "jasmine",
"joint": "jointjs",
"jquery": "jquery",
"jquery.address": "jquery.address",
"jquery.are-you-sure": "jquery.are-you-sure",
"jquery.blockUI": "jquery.blockUI",
"jquery.bootstrap.wizard": "jquery.bootstrap.wizard",
"jquery.bootstrap-touchspin": "bootstrap-touchspin",
"jquery.color": "jquery.color",
"jquery.colorbox": "jquery.colorbox",
"jquery.contextMenu": "jquery.contextMenu",
"jquery.cookie": "jquery.cookie",
"jquery.customSelect": "jquery.customSelect",
"jquery.cycle.all": "jquery.cycle",
"jquery.cycle2": "jquery.cycle2",
"jquery.dataTables": "jquery.dataTables",
"jquery.dropotron": "jquery.dropotron",
"jquery.fancybox.pack.js": "fancybox",
"jquery.fancytree-all": "jquery.fancytree",
"jquery.fileupload": "jquery.fileupload",
"jquery.flot": "flot",
"jquery.form": "jquery.form",
"jquery.gridster": "jquery.gridster",
"jquery.handsontable.full": "jquery-handsontable",
"jquery.joyride": "jquery.joyride",
"jquery.jqGrid": "jqgrid",
"jquery.mmenu": "jquery.mmenu",
"jquery.mockjax": "jquery-mockjax",
"jquery.noty": "jquery.noty",
"jquery.payment": "jquery.payment",
"jquery.pjax": "jquery.pjax",
"jquery.placeholder": "jquery.placeholder",
"jquery.qrcode": "jquery.qrcode",
"jquery.qtip": "qtip2",
"jquery.raty": "raty",
"jquery.scrollTo": "jquery.scrollTo",
"jquery.signalR": "signalr",
"jquery.simplemodal": "jquery.simplemodal",
"jquery.timeago": "jquery.timeago",
"jquery.tinyscrollbar": "jquery.tinyscrollbar",
"jquery.tipsy": "jquery.tipsy",
"jquery.tooltipster": "tooltipster",
"jquery.transit": "jquery.transit",
"jquery.uniform": "jquery.uniform",
"jquery.watch": "watch",
"jquery-sortable": "jquery-sortable",
"jquery-ui": "jqueryui",
"js.cookie": "js-cookie",
"js-data": "js-data",
"js-data-angular": "js-data-angular",
"js-data-http": "js-data-http",
"jsdom": "jsdom",
"jsnlog": "jsnlog",
"json5": "json5",
"jspdf": "jspdf",
"jsrender": "jsrender",
"js-signals": "js-signals",
"jstorage": "jstorage",
"jstree": "jstree",
"js-yaml": "js-yaml",
"jszip": "jszip",
"katex": "katex",
"kefir": "kefir",
"keymaster": "keymaster",
"keypress": "keypress",
"kinetic": "kineticjs",
"knockback": "knockback",
"knockout": "knockout",
"knockout.mapping": "knockout.mapping",
"knockout.validation": "knockout.validation",
"knockout-paging": "knockout-paging",
"knockout-pre-rendered": "knockout-pre-rendered",
"ladda": "ladda",
"later": "later",
"lazy": "lazy.js",
"Leaflet.Editable": "leaflet-editable",
"leaflet.js": "leaflet",
"less": "less",
"linq": "linq",
"loading-bar": "angular-loading-bar",
"lodash": "lodash",
"log4javascript": "log4javascript",
"loglevel": "loglevel",
"lokijs": "lokijs",
"lovefield": "lovefield",
"lunr": "lunr",
"lz-string": "lz-string",
"mailcheck": "mailcheck",
"maquette": "maquette",
"marked": "marked",
"math": "mathjs",
"MathJax.js": "mathjax",
"matter": "matter-js",
"md5": "blueimp-md5",
"md5.js": "crypto-js",
"messenger": "messenger",
"method-override": "method-override",
"minimatch": "minimatch",
"minimist": "minimist",
"mithril": "mithril",
"mobile-detect": "mobile-detect",
"mocha": "mocha",
"mock-ajax": "jasmine-ajax",
"modernizr": "modernizr",
"Modernizr": "Modernizr",
"moment": "moment",
"moment-range": "moment-range",
"moment-timezone": "moment-timezone",
"mongoose": "mongoose",
"morgan": "morgan",
"mousetrap": "mousetrap",
"ms": "ms",
"mustache": "mustache",
"native.history": "history",
"nconf": "nconf",
"ncp": "ncp",
"nedb": "nedb",
"ng-cordova": "ng-cordova",
"ngDialog": "ng-dialog",
"ng-flow-standalone": "ng-flow",
"ng-grid": "ng-grid",
"ng-i18next": "ng-i18next",
"ng-table": "ng-table",
"node_redis": "redis",
"node-clone": "clone",
"node-fs-extra": "fs-extra",
"node-glob": "glob",
"Nodemailer": "nodemailer",
"node-mime": "mime",
"node-mkdirp": "mkdirp",
"node-mongodb-native": "mongodb",
"node-mysql": "mysql",
"node-open": "open",
"node-optimist": "optimist",
"node-progress": "progress",
"node-semver": "semver",
"node-tar": "tar",
"node-uuid": "node-uuid",
"node-xml2js": "xml2js",
"nopt": "nopt",
"notify": "notify",
"nouislider": "nouislider",
"npm": "npm",
"nprogress": "nprogress",
"numbro": "numbro",
"numeral": "numeraljs",
"nunjucks": "nunjucks",
"nv.d3": "nvd3",
"object-assign": "object-assign",
"oboe-browser": "oboe",
"office": "office-js",
"offline": "offline-js",
"onsenui": "onsenui",
"OpenLayers.js": "openlayers",
"openpgp": "openpgp",
"p2": "p2",
"packery.pkgd": "packery",
"page": "page",
"pako": "pako",
"papaparse": "papaparse",
"passport": "passport",
"passport-local": "passport-local",
"path": "pathjs",
"pdfkit": "pdfkit",
"peer": "peerjs",
"peg": "pegjs",
"photoswipe": "photoswipe",
"picker.js": "pickadate",
"pikaday": "pikaday",
"pixi": "pixi.js",
"platform": "platform",
"Please": "pleasejs",
"plottable": "plottable",
"polymer": "polymer",
"postal": "postal",
"preloadjs": "preloadjs",
"progress": "progress",
"purify": "dompurify",
"purl": "purl",
"q": "q",
"qs": "qs",
"qunit": "qunit",
"ractive": "ractive",
"rangy-core": "rangy",
"raphael": "raphael",
"raven": "ravenjs",
"react": "react",
"react-bootstrap": "react-bootstrap",
"react-intl": "react-intl",
"react-redux": "react-redux",
"ReactRouter": "react-router",
"ready": "domready",
"redux": "redux",
"request": "request",
"require": "require",
"restangular": "restangular",
"reveal": "reveal",
"rickshaw": "rickshaw",
"rimraf": "rimraf",
"rivets": "rivets",
"rx": "rx",
"rx.angular": "rx-angular",
"sammy": "sammyjs",
"SAT": "sat",
"sax-js": "sax",
"screenfull": "screenfull",
"seedrandom": "seedrandom",
"select2": "select2",
"selectize": "selectize",
"serve-favicon": "serve-favicon",
"serve-static": "serve-static",
"shelljs": "shelljs",
"should": "should",
"showdown": "showdown",
"sigma": "sigmajs",
"signature_pad": "signature_pad",
"sinon": "sinon",
"sjcl": "sjcl",
"slick": "slick-carousel",
"smoothie": "smoothie",
"socket.io": "socket.io",
"socket.io-client": "socket.io-client",
"sockjs": "sockjs-client",
"sortable": "angular-ui-sortable",
"soundjs": "soundjs",
"source-map": "source-map",
"spectrum": "spectrum",
"spin": "spin",
"sprintf": "sprintf",
"stampit": "stampit",
"state-machine": "state-machine",
"Stats": "stats",
"store": "storejs",
"string": "string",
"string_score": "string_score",
"strophe": "strophe",
"stylus": "stylus",
"sugar": "sugar",
"superagent": "superagent",
"svg": "svgjs",
"svg-injector": "svg-injector",
"swfobject": "swfobject",
"swig": "swig",
"swipe": "swipe",
"swiper": "swiper",
"system.js": "systemjs",
"tether": "tether",
"three": "threejs",
"through": "through",
"through2": "through2",
"timeline": "timelinejs",
"tinycolor": "tinycolor",
"tmhDynamicLocale": "angular-dynamic-locale",
"toaster": "angularjs-toaster",
"toastr": "toastr",
"tracking": "tracking",
"trunk8": "trunk8",
"turf": "turf",
"tweenjs": "tweenjs",
"TweenMax": "gsap",
"twig": "twig",
"twix": "twix",
"typeahead.bundle": "typeahead",
"typescript": "typescript",
"ui": "winjs",
"ui-bootstrap-tpls": "angular-ui-bootstrap",
"ui-grid": "ui-grid",
"uikit": "uikit",
"underscore": "underscore",
"underscore.string": "underscore.string",
"update-notifier": "update-notifier",
"url": "jsurl",
"UUID": "uuid",
"validator": "validator",
"vega": "vega",
"vex": "vex-js",
"video": "videojs",
"vue": "vue",
"vue-router": "vue-router",
"webtorrent": "webtorrent",
"when": "when",
"winston": "winston",
"wrench-js": "wrench",
"ws": "ws",
"xlsx": "xlsx",
"xml2json": "x2js",
"xmlbuilder-js": "xmlbuilder",
"xregexp": "xregexp",
"yargs": "yargs",
"yosay": "yosay",
"yui": "yui",
"yui3": "yui",
"zepto": "zepto",
"ZeroClipboard": "zeroclipboard",
"ZSchema-browser": "z-schema"
}
}

View File

@@ -0,0 +1,65 @@
{
"name": "@eslint/config-array",
"version": "0.23.5",
"description": "General purpose glob-based configuration matching.",
"author": "Nicholas C. Zakas",
"type": "module",
"main": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
"exports": {
"require": {
"types": "./dist/cjs/index.d.cts",
"default": "./dist/cjs/index.cjs"
},
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
}
},
"files": [
"dist"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/eslint/rewrite.git",
"directory": "packages/config-array"
},
"bugs": {
"url": "https://github.com/eslint/rewrite/issues"
},
"homepage": "https://github.com/eslint/rewrite/tree/main/packages/config-array#readme",
"scripts": {
"build:dedupe-types": "node ../../tools/dedupe-types.js dist/cjs/index.cjs dist/esm/index.js",
"build:cts": "node ../../tools/build-cts.js dist/esm/index.d.ts dist/cjs/index.d.cts",
"build:std__path": "rollup -c rollup.std__path-config.js && node fix-std__path-imports",
"build": "rollup -c && npm run build:dedupe-types && tsc -p tsconfig.esm.json && npm run build:cts && npm run build:std__path",
"lint:types": "attw --pack",
"pretest": "npm run build",
"test": "npm run test:types && npm run test:unit",
"test:coverage": "npm run build && c8 npm run test:unit",
"test:jsr": "npx -y jsr@latest publish --dry-run",
"test:types": "tsc -p tests/types/tsconfig.json",
"test:unit": "mocha \"tests/**/*.test.js\""
},
"keywords": [
"configuration",
"configarray",
"config file"
],
"license": "Apache-2.0",
"dependencies": {
"@eslint/object-schema": "^3.0.5",
"debug": "^4.3.1",
"minimatch": "^10.2.4"
},
"devDependencies": {
"@jsr/std__path": "^1.0.4",
"rollup-plugin-copy": "^3.5.0"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=24"
}
}

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isAssignee = isAssignee;
const utils_1 = require("@typescript-eslint/utils");
function isAssignee(node) {
const parent = node.parent;
if (!parent) {
return false;
}
// a[i] = 1, a[i] += 1, etc.
if (parent.type === utils_1.AST_NODE_TYPES.AssignmentExpression &&
parent.left === node) {
return true;
}
// delete a[i]
if (parent.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
parent.operator === 'delete' &&
parent.argument === node) {
return true;
}
// a[i]++, --a[i], etc.
if (parent.type === utils_1.AST_NODE_TYPES.UpdateExpression &&
parent.argument === node) {
return true;
}
// [a[i]] = [0]
if (parent.type === utils_1.AST_NODE_TYPES.ArrayPattern) {
return true;
}
// [...a[i]] = [0]
if (parent.type === utils_1.AST_NODE_TYPES.RestElement) {
return true;
}
// ({ foo: a[i] }) = { foo: 0 }
if (parent.type === utils_1.AST_NODE_TYPES.Property &&
parent.value === node &&
parent.parent.type === utils_1.AST_NODE_TYPES.ObjectExpression &&
isAssignee(parent.parent)) {
return true;
}
// (a[i] as number)++, [...a[i]!] = [0], etc.
if ((parent.type === utils_1.AST_NODE_TYPES.TSNonNullExpression ||
parent.type === utils_1.AST_NODE_TYPES.TSAsExpression ||
parent.type === utils_1.AST_NODE_TYPES.TSTypeAssertion ||
parent.type === utils_1.AST_NODE_TYPES.TSSatisfiesExpression) &&
isAssignee(parent)) {
return true;
}
return false;
}

View File

@@ -0,0 +1,79 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.missing }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}
{{## def.propertyInData:
{{=$data}}{{= it.util.getProperty($property) }} !== undefined
{{? $ownProperties }}
&& Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($property)}}')
{{?}}
#}}
{{
var $schemaDeps = {}
, $propertyDeps = {}
, $ownProperties = it.opts.ownProperties;
for ($property in $schema) {
if ($property == '__proto__') continue;
var $sch = $schema[$property];
var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
$deps[$property] = $sch;
}
}}
var {{=$errs}} = errors;
{{ var $currentErrorPath = it.errorPath; }}
var missing{{=$lvl}};
{{ for (var $property in $propertyDeps) { }}
{{ $deps = $propertyDeps[$property]; }}
{{? $deps.length }}
if ({{# def.propertyInData }}
{{? $breakOnError }}
&& ({{# def.checkMissingProperty:$deps }})) {
{{# def.errorMissingProperty:'dependencies' }}
{{??}}
) {
{{~ $deps:$propertyKey }}
{{# def.allErrorsMissingProperty:'dependencies' }}
{{~}}
{{?}}
} {{# def.elseIfValid }}
{{?}}
{{ } }}
{{
it.errorPath = $currentErrorPath;
var $currentBaseId = $it.baseId;
}}
{{ for (var $property in $schemaDeps) { }}
{{ var $sch = $schemaDeps[$property]; }}
{{? {{# def.nonEmptySchema:$sch }} }}
{{=$nextValid}} = true;
if ({{# def.propertyInData }}) {
{{
$it.schema = $sch;
$it.schemaPath = $schemaPath + it.util.getProperty($property);
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
}}
{{# def.insertSubschemaCode }}
}
{{# def.ifResultValid }}
{{?}}
{{ } }}
{{? $breakOnError }}
{{= $closingBraces }}
if ({{=$errs}} == errors) {
{{?}}

View File

@@ -0,0 +1,6 @@
import type { ProjectServiceAndMetadata } from '@typescript-eslint/project-service';
import type { ASTAndDefiniteProgram, ASTAndNoProgram, ASTAndProgram } from './create-program/shared';
import type { MutableParseSettings } from './parseSettings';
export declare function useProgramFromProjectService(serviceAndSettings: ProjectServiceAndMetadata, parseSettings: Readonly<MutableParseSettings>, hasFullTypeInformation: boolean, defaultProjectMatchedFiles: Set<string>): ASTAndProgram | undefined;
export declare function useProgramFromProjectService(serviceAndSettings: ProjectServiceAndMetadata, parseSettings: Readonly<MutableParseSettings>, hasFullTypeInformation: true, defaultProjectMatchedFiles: Set<string>): ASTAndDefiniteProgram | undefined;
export declare function useProgramFromProjectService(serviceAndSettings: ProjectServiceAndMetadata, parseSettings: Readonly<MutableParseSettings>, hasFullTypeInformation: false, defaultProjectMatchedFiles: Set<string>): ASTAndNoProgram | undefined;

View File

@@ -0,0 +1,335 @@
'use strict';
// eslint-disable-next-line @typescript-eslint/unbound-method
const toStringFunction = Function.prototype.toString;
// eslint-disable-next-line @typescript-eslint/unbound-method
const toStringObject = Object.prototype.toString;
/**
* Get an empty version of the object with the same prototype it has.
*/
function getCleanClone(prototype) {
if (!prototype) {
return Object.create(null);
}
const Constructor = prototype.constructor;
if (Constructor === Object) {
return prototype === Object.prototype ? {} : Object.create(prototype);
}
if (Constructor && ~toStringFunction.call(Constructor).indexOf('[native code]')) {
try {
return new Constructor();
}
catch (_a) {
// Ignore
}
}
return Object.create(prototype);
}
/**
* Get the tag of the value passed, so that the correct copier can be used.
*/
function getTag(value) {
const stringTag = value[Symbol.toStringTag];
if (stringTag) {
return stringTag;
}
const type = toStringObject.call(value);
return type.substring(8, type.length - 1);
}
// eslint-disable-next-line @typescript-eslint/unbound-method
const { propertyIsEnumerable } = Object.prototype;
function copyOwnDescriptor(original, clone, property, state) {
const ownDescriptor = Object.getOwnPropertyDescriptor(original, property) || {
configurable: true,
enumerable: true,
value: original[property],
writable: true,
};
const descriptor = ownDescriptor.get || ownDescriptor.set
? ownDescriptor
: {
configurable: ownDescriptor.configurable,
enumerable: ownDescriptor.enumerable,
value: state.copier(ownDescriptor.value, state),
writable: ownDescriptor.writable,
};
try {
Object.defineProperty(clone, property, descriptor);
}
catch (_a) {
// The above can fail on node in extreme edge cases, so fall back to the loose assignment.
clone[property] = descriptor.get ? descriptor.get() : descriptor.value;
}
}
/**
* Strictly copy all properties contained on the object.
*/
function copyOwnPropertiesStrict(value, clone, state) {
for (const name of Object.getOwnPropertyNames(value)) {
copyOwnDescriptor(value, clone, name, state);
}
for (const symbol of Object.getOwnPropertySymbols(value)) {
copyOwnDescriptor(value, clone, symbol, state);
}
return clone;
}
/**
* Deeply copy the indexed values in the array.
*/
function copyArrayLoose(array, state) {
const clone = new state.Constructor();
// set in the cache immediately to be able to reuse the object recursively
state.cache.set(array, clone);
for (let index = 0; index < array.length; ++index) {
clone[index] = state.copier(array[index], state);
}
return clone;
}
/**
* Deeply copy the indexed values in the array, as well as any custom properties.
*/
function copyArrayStrict(array, state) {
const clone = new state.Constructor();
// set in the cache immediately to be able to reuse the object recursively
state.cache.set(array, clone);
return copyOwnPropertiesStrict(array, clone, state);
}
/**
* Copy the contents of the ArrayBuffer.
*/
function copyArrayBuffer(arrayBuffer, _state) {
return arrayBuffer.slice(0);
}
/**
* Create a new Blob with the contents of the original.
*/
function copyBlob(blob, _state) {
return blob.slice(0, blob.size, blob.type);
}
/**
* Create a new DataView with the contents of the original.
*/
function copyDataView(dataView, state) {
return new state.Constructor(copyArrayBuffer(dataView.buffer));
}
/**
* Create a new Date based on the time of the original.
*/
function copyDate(date, state) {
return new state.Constructor(date.getTime());
}
/**
* Deeply copy the keys and values of the original.
*/
function copyMapLoose(map, state) {
const clone = new state.Constructor();
// set in the cache immediately to be able to reuse the object recursively
state.cache.set(map, clone);
for (const [key, value] of map) {
clone.set(key, state.copier(value, state));
}
return clone;
}
/**
* Deeply copy the keys and values of the original, as well as any custom properties.
*/
function copyMapStrict(map, state) {
return copyOwnPropertiesStrict(map, copyMapLoose(map, state), state);
}
/**
* Deeply copy the properties (keys and symbols) and values of the original.
*/
function copyObjectLoose(object, state) {
const clone = getCleanClone(state.prototype);
// set in the cache immediately to be able to reuse the object recursively
state.cache.set(object, clone);
for (const key of Object.keys(object)) {
clone[key] = state.copier(object[key], state);
}
for (const symbol of Object.getOwnPropertySymbols(object)) {
if (propertyIsEnumerable.call(object, symbol)) {
clone[symbol] = state.copier(object[symbol], state);
}
}
return clone;
}
/**
* Deeply copy the properties (keys and symbols) and values of the original, as well
* as any hidden or non-enumerable properties.
*/
function copyObjectStrict(object, state) {
const clone = getCleanClone(state.prototype);
// set in the cache immediately to be able to reuse the object recursively
state.cache.set(object, clone);
return copyOwnPropertiesStrict(object, clone, state);
}
/**
* Create a new primitive wrapper from the value of the original.
*/
function copyPrimitiveWrapper(primitiveObject, state) {
return new state.Constructor(primitiveObject.valueOf());
}
/**
* Create a new RegExp based on the value and flags of the original.
*/
function copyRegExp(regExp, state) {
const clone = new state.Constructor(regExp.source, regExp.flags);
clone.lastIndex = regExp.lastIndex;
return clone;
}
/**
* Return the original value (an identity function).
*
* @note
* THis is used for objects that cannot be copied, such as WeakMap.
*/
function copySelf(value, _state) {
return value;
}
/**
* Deeply copy the values of the original.
*/
function copySetLoose(set, state) {
const clone = new state.Constructor();
// set in the cache immediately to be able to reuse the object recursively
state.cache.set(set, clone);
for (const value of set) {
clone.add(state.copier(value, state));
}
return clone;
}
/**
* Deeply copy the values of the original, as well as any custom properties.
*/
function copySetStrict(set, state) {
return copyOwnPropertiesStrict(set, copySetLoose(set, state), state);
}
function createDefaultCache() {
return new WeakMap();
}
function getOptions({ createCache: createCacheOverride, methods: methodsOverride, strict, }) {
const defaultMethods = {
array: strict ? copyArrayStrict : copyArrayLoose,
arrayBuffer: copyArrayBuffer,
asyncGenerator: copySelf,
blob: copyBlob,
dataView: copyDataView,
date: copyDate,
error: copySelf,
generator: copySelf,
map: strict ? copyMapStrict : copyMapLoose,
object: strict ? copyObjectStrict : copyObjectLoose,
regExp: copyRegExp,
set: strict ? copySetStrict : copySetLoose,
};
const methods = methodsOverride ? Object.assign(defaultMethods, methodsOverride) : defaultMethods;
const copiers = getTagSpecificCopiers(methods);
const createCache = createCacheOverride || createDefaultCache;
// Extra safety check to ensure that object and array copiers are always provided,
// avoiding runtime errors.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!copiers.Object || !copiers.Array) {
throw new Error('An object and array copier must be provided.');
}
return { createCache, copiers, methods, strict: Boolean(strict) };
}
/**
* Get the copiers used for each specific object tag.
*/
function getTagSpecificCopiers(methods) {
return {
Arguments: methods.object,
Array: methods.array,
ArrayBuffer: methods.arrayBuffer,
AsyncGenerator: methods.asyncGenerator,
BigInt64Array: methods.arrayBuffer,
BigUint64Array: methods.arrayBuffer,
Blob: methods.blob,
Boolean: copyPrimitiveWrapper,
DataView: methods.dataView,
Date: methods.date,
Error: methods.error,
Float32Array: methods.arrayBuffer,
Float64Array: methods.arrayBuffer,
Generator: methods.generator,
Int8Array: methods.arrayBuffer,
Int16Array: methods.arrayBuffer,
Int32Array: methods.arrayBuffer,
Map: methods.map,
Number: copyPrimitiveWrapper,
Object: methods.object,
Promise: copySelf,
RegExp: methods.regExp,
Set: methods.set,
String: copyPrimitiveWrapper,
WeakMap: copySelf,
WeakSet: copySelf,
Uint8Array: methods.arrayBuffer,
Uint8ClampedArray: methods.arrayBuffer,
Uint16Array: methods.arrayBuffer,
Uint32Array: methods.arrayBuffer,
};
}
/**
* Create a custom copier based on custom options for any of the following:
* - `createCache` method to create a cache for copied objects
* - custom copier `methods` for specific object types
* - `strict` mode to copy all properties with their descriptors
*/
function createCopier(options = {}) {
const { createCache, copiers } = getOptions(options);
const { Array: copyArray, Object: copyObject } = copiers;
function copier(value, state) {
state.prototype = state.Constructor = undefined;
if (!value || typeof value !== 'object') {
return value;
}
if (state.cache.has(value)) {
return state.cache.get(value);
}
state.prototype = Object.getPrototypeOf(value);
// Using logical AND for speed, since optional chaining transforms to
// a local variable usage.
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain
state.Constructor = state.prototype && state.prototype.constructor;
// plain objects
if (!state.Constructor || state.Constructor === Object) {
return copyObject(value, state);
}
// arrays
if (Array.isArray(value)) {
return copyArray(value, state);
}
const tagSpecificCopier = copiers[getTag(value)];
if (tagSpecificCopier) {
return tagSpecificCopier(value, state);
}
return typeof value.then === 'function' ? value : copyObject(value, state);
}
return function copy(value) {
return copier(value, {
Constructor: undefined,
cache: createCache(),
copier,
prototype: undefined,
});
};
}
/**
* Copy an value deeply as much as possible, where strict recreation of object properties
* are maintained. All properties (including non-enumerable ones) are copied with their
* original property descriptors on both objects and arrays.
*/
const copyStrict = createCopier({ strict: true });
/**
* Copy an value deeply as much as possible.
*/
const copy = createCopier();
exports.copy = copy;
exports.copyStrict = copyStrict;
exports.createCopier = createCopier;
//# sourceMappingURL=index.cjs.map

View File

@@ -0,0 +1,15 @@
export declare enum SignatureFlags {
None = 0,
HasRestParameter = 1,
HasLiteralTypes = 2,
Construct = 4,
Abstract = 8,
IsInnerCallChain = 16,
IsOuterCallChain = 32,
IsUntypedSignatureInJSFile = 64,
IsNonInferrable = 128,
IsSignatureCandidateForOverloadFailure = 256,
PropagatingFlags = 335,
CallChainFlags = 48
}
//# sourceMappingURL=signatureFlags.enum.d.ts.map

View File

@@ -0,0 +1,195 @@
import * as core from "./core.js";
import * as errors from "./errors.js";
import type * as schemas from "./schemas.js";
import * as util from "./util.js";
export type $ZodErrorClass = { new (issues: errors.$ZodIssue[]): errors.$ZodError };
/////////// METHODS ///////////
export type $Parse = <T extends schemas.$ZodType>(
schema: T,
value: unknown,
_ctx?: schemas.ParseContext<errors.$ZodIssue>,
_params?: { callee?: util.AnyFunc; Err?: $ZodErrorClass }
) => core.output<T>;
export const _parse: (_Err: $ZodErrorClass) => $Parse = (_Err) => (schema, value, _ctx, _params) => {
const ctx: schemas.ParseContextInternal = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
}
if (result.issues.length) {
const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));
util.captureStackTrace(e, _params?.callee);
throw e;
}
return result.value as core.output<typeof schema>;
};
export const parse: $Parse = /* @__PURE__*/ _parse(errors.$ZodRealError);
export type $ParseAsync = <T extends schemas.$ZodType>(
schema: T,
value: unknown,
_ctx?: schemas.ParseContext<errors.$ZodIssue>,
_params?: { callee?: util.AnyFunc; Err?: $ZodErrorClass }
) => Promise<core.output<T>>;
export const _parseAsync: (_Err: $ZodErrorClass) => $ParseAsync = (_Err) => async (schema, value, _ctx, params) => {
const ctx: schemas.ParseContextInternal = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) result = await result;
if (result.issues.length) {
const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));
util.captureStackTrace(e, params?.callee);
throw e;
}
return result.value as core.output<typeof schema>;
};
export const parseAsync: $ParseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);
export type $SafeParse = <T extends schemas.$ZodType>(
schema: T,
value: unknown,
_ctx?: schemas.ParseContext<errors.$ZodIssue>
) => util.SafeParseResult<core.output<T>>;
export const _safeParse: (_Err: $ZodErrorClass) => $SafeParse = (_Err) => (schema, value, _ctx) => {
const ctx: schemas.ParseContextInternal = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
}
return result.issues.length
? {
success: false,
error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),
}
: ({ success: true, data: result.value } as any);
};
export const safeParse: $SafeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);
export type $SafeParseAsync = <T extends schemas.$ZodType>(
schema: T,
value: unknown,
_ctx?: schemas.ParseContext<errors.$ZodIssue>
) => Promise<util.SafeParseResult<core.output<T>>>;
export const _safeParseAsync: (_Err: $ZodErrorClass) => $SafeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx: schemas.ParseContextInternal = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) result = await result;
return result.issues.length
? {
success: false,
error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),
}
: ({ success: true, data: result.value } as any);
};
export const safeParseAsync: $SafeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);
// Codec functions
export type $Encode = <T extends schemas.$ZodType>(
schema: T,
value: core.output<T>,
_ctx?: schemas.ParseContext<errors.$ZodIssue>
) => core.input<T>;
export const _encode: (_Err: $ZodErrorClass) => $Encode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" as const } : { direction: "backward" as const };
return _parse(_Err)(schema, value, ctx as any) as any;
};
export const encode: $Encode = /* @__PURE__*/ _encode(errors.$ZodRealError);
export type $Decode = <T extends schemas.$ZodType>(
schema: T,
value: core.input<T>,
_ctx?: schemas.ParseContext<errors.$ZodIssue>
) => core.output<T>;
export const _decode: (_Err: $ZodErrorClass) => $Decode = (_Err) => (schema, value, _ctx) => {
return _parse(_Err)(schema, value, _ctx);
};
export const decode: $Decode = /* @__PURE__*/ _decode(errors.$ZodRealError);
export type $EncodeAsync = <T extends schemas.$ZodType>(
schema: T,
value: core.output<T>,
_ctx?: schemas.ParseContext<errors.$ZodIssue>
) => Promise<core.input<T>>;
export const _encodeAsync: (_Err: $ZodErrorClass) => $EncodeAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" as const } : { direction: "backward" as const };
return _parseAsync(_Err)(schema, value, ctx as any) as any;
};
export const encodeAsync: $EncodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);
export type $DecodeAsync = <T extends schemas.$ZodType>(
schema: T,
value: core.input<T>,
_ctx?: schemas.ParseContext<errors.$ZodIssue>
) => Promise<core.output<T>>;
export const _decodeAsync: (_Err: $ZodErrorClass) => $DecodeAsync = (_Err) => async (schema, value, _ctx) => {
return _parseAsync(_Err)(schema, value, _ctx);
};
export const decodeAsync: $DecodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);
export type $SafeEncode = <T extends schemas.$ZodType>(
schema: T,
value: core.output<T>,
_ctx?: schemas.ParseContext<errors.$ZodIssue>
) => util.SafeParseResult<core.input<T>>;
export const _safeEncode: (_Err: $ZodErrorClass) => $SafeEncode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" as const } : { direction: "backward" as const };
return _safeParse(_Err)(schema, value, ctx as any) as any;
};
export const safeEncode: $SafeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);
export type $SafeDecode = <T extends schemas.$ZodType>(
schema: T,
value: core.input<T>,
_ctx?: schemas.ParseContext<errors.$ZodIssue>
) => util.SafeParseResult<core.output<T>>;
export const _safeDecode: (_Err: $ZodErrorClass) => $SafeDecode = (_Err) => (schema, value, _ctx) => {
return _safeParse(_Err)(schema, value, _ctx);
};
export const safeDecode: $SafeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);
export type $SafeEncodeAsync = <T extends schemas.$ZodType>(
schema: T,
value: core.output<T>,
_ctx?: schemas.ParseContext<errors.$ZodIssue>
) => Promise<util.SafeParseResult<core.input<T>>>;
export const _safeEncodeAsync: (_Err: $ZodErrorClass) => $SafeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" as const } : { direction: "backward" as const };
return _safeParseAsync(_Err)(schema, value, ctx as any) as any;
};
export const safeEncodeAsync: $SafeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);
export type $SafeDecodeAsync = <T extends schemas.$ZodType>(
schema: T,
value: core.input<T>,
_ctx?: schemas.ParseContext<errors.$ZodIssue>
) => Promise<util.SafeParseResult<core.output<T>>>;
export const _safeDecodeAsync: (_Err: $ZodErrorClass) => $SafeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
return _safeParseAsync(_Err)(schema, value, _ctx);
};
export const safeDecodeAsync: $SafeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);

View File

@@ -0,0 +1,38 @@
// Note: named reexports are used instead of `export *` because
// TypeScript itself doesn't resolve the `export *` when checking
// if a particular helper exists.
export {
__extends,
__assign,
__rest,
__decorate,
__param,
__esDecorate,
__runInitializers,
__propKey,
__setFunctionName,
__metadata,
__awaiter,
__generator,
__exportStar,
__values,
__read,
__spread,
__spreadArrays,
__spreadArray,
__await,
__asyncGenerator,
__asyncDelegator,
__asyncValues,
__makeTemplateObject,
__importStar,
__importDefault,
__classPrivateFieldGet,
__classPrivateFieldSet,
__classPrivateFieldIn,
__createBinding,
__addDisposableResource,
__disposeResources,
__rewriteRelativeImportExtension,
} from '../tslib.js';
export * as default from '../tslib.js';

View File

@@ -0,0 +1,6 @@
"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 });

View File

@@ -0,0 +1,313 @@
// Copyright 2017 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const childProcess = require('child_process');
const { isLinux, getReport } = require('./process');
const { LDD_PATH, SELF_PATH, readFile, readFileSync } = require('./filesystem');
const { interpreterPath } = require('./elf');
let cachedFamilyInterpreter;
let cachedFamilyFilesystem;
let cachedVersionFilesystem;
const command = 'getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true';
let commandOut = '';
const safeCommand = () => {
if (!commandOut) {
return new Promise((resolve) => {
childProcess.exec(command, (err, out) => {
commandOut = err ? ' ' : out;
resolve(commandOut);
});
});
}
return commandOut;
};
const safeCommandSync = () => {
if (!commandOut) {
try {
commandOut = childProcess.execSync(command, { encoding: 'utf8' });
} catch (_err) {
commandOut = ' ';
}
}
return commandOut;
};
/**
* A String constant containing the value `glibc`.
* @type {string}
* @public
*/
const GLIBC = 'glibc';
/**
* A Regexp constant to get the GLIBC Version.
* @type {string}
*/
const RE_GLIBC_VERSION = /LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i;
/**
* A String constant containing the value `musl`.
* @type {string}
* @public
*/
const MUSL = 'musl';
const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-');
const familyFromReport = () => {
const report = getReport();
if (report.header && report.header.glibcVersionRuntime) {
return GLIBC;
}
if (Array.isArray(report.sharedObjects)) {
if (report.sharedObjects.some(isFileMusl)) {
return MUSL;
}
}
return null;
};
const familyFromCommand = (out) => {
const [getconf, ldd1] = out.split(/[\r\n]+/);
if (getconf && getconf.includes(GLIBC)) {
return GLIBC;
}
if (ldd1 && ldd1.includes(MUSL)) {
return MUSL;
}
return null;
};
const familyFromInterpreterPath = (path) => {
if (path) {
if (path.includes('/ld-musl-')) {
return MUSL;
} else if (path.includes('/ld-linux-')) {
return GLIBC;
}
}
return null;
};
const getFamilyFromLddContent = (content) => {
content = content.toString();
if (content.includes('musl')) {
return MUSL;
}
if (content.includes('GNU C Library')) {
return GLIBC;
}
return null;
};
const familyFromFilesystem = async () => {
if (cachedFamilyFilesystem !== undefined) {
return cachedFamilyFilesystem;
}
cachedFamilyFilesystem = null;
try {
const lddContent = await readFile(LDD_PATH);
cachedFamilyFilesystem = getFamilyFromLddContent(lddContent);
} catch (e) {}
return cachedFamilyFilesystem;
};
const familyFromFilesystemSync = () => {
if (cachedFamilyFilesystem !== undefined) {
return cachedFamilyFilesystem;
}
cachedFamilyFilesystem = null;
try {
const lddContent = readFileSync(LDD_PATH);
cachedFamilyFilesystem = getFamilyFromLddContent(lddContent);
} catch (e) {}
return cachedFamilyFilesystem;
};
const familyFromInterpreter = async () => {
if (cachedFamilyInterpreter !== undefined) {
return cachedFamilyInterpreter;
}
cachedFamilyInterpreter = null;
try {
const selfContent = await readFile(SELF_PATH);
const path = interpreterPath(selfContent);
cachedFamilyInterpreter = familyFromInterpreterPath(path);
} catch (e) {}
return cachedFamilyInterpreter;
};
const familyFromInterpreterSync = () => {
if (cachedFamilyInterpreter !== undefined) {
return cachedFamilyInterpreter;
}
cachedFamilyInterpreter = null;
try {
const selfContent = readFileSync(SELF_PATH);
const path = interpreterPath(selfContent);
cachedFamilyInterpreter = familyFromInterpreterPath(path);
} catch (e) {}
return cachedFamilyInterpreter;
};
/**
* Resolves with the libc family when it can be determined, `null` otherwise.
* @returns {Promise<?string>}
*/
const family = async () => {
let family = null;
if (isLinux()) {
family = await familyFromInterpreter();
if (!family) {
family = await familyFromFilesystem();
if (!family) {
family = familyFromReport();
}
if (!family) {
const out = await safeCommand();
family = familyFromCommand(out);
}
}
}
return family;
};
/**
* Returns the libc family when it can be determined, `null` otherwise.
* @returns {?string}
*/
const familySync = () => {
let family = null;
if (isLinux()) {
family = familyFromInterpreterSync();
if (!family) {
family = familyFromFilesystemSync();
if (!family) {
family = familyFromReport();
}
if (!family) {
const out = safeCommandSync();
family = familyFromCommand(out);
}
}
}
return family;
};
/**
* Resolves `true` only when the platform is Linux and the libc family is not `glibc`.
* @returns {Promise<boolean>}
*/
const isNonGlibcLinux = async () => isLinux() && await family() !== GLIBC;
/**
* Returns `true` only when the platform is Linux and the libc family is not `glibc`.
* @returns {boolean}
*/
const isNonGlibcLinuxSync = () => isLinux() && familySync() !== GLIBC;
const versionFromFilesystem = async () => {
if (cachedVersionFilesystem !== undefined) {
return cachedVersionFilesystem;
}
cachedVersionFilesystem = null;
try {
const lddContent = await readFile(LDD_PATH);
const versionMatch = lddContent.match(RE_GLIBC_VERSION);
if (versionMatch) {
cachedVersionFilesystem = versionMatch[1];
}
} catch (e) {}
return cachedVersionFilesystem;
};
const versionFromFilesystemSync = () => {
if (cachedVersionFilesystem !== undefined) {
return cachedVersionFilesystem;
}
cachedVersionFilesystem = null;
try {
const lddContent = readFileSync(LDD_PATH);
const versionMatch = lddContent.match(RE_GLIBC_VERSION);
if (versionMatch) {
cachedVersionFilesystem = versionMatch[1];
}
} catch (e) {}
return cachedVersionFilesystem;
};
const versionFromReport = () => {
const report = getReport();
if (report.header && report.header.glibcVersionRuntime) {
return report.header.glibcVersionRuntime;
}
return null;
};
const versionSuffix = (s) => s.trim().split(/\s+/)[1];
const versionFromCommand = (out) => {
const [getconf, ldd1, ldd2] = out.split(/[\r\n]+/);
if (getconf && getconf.includes(GLIBC)) {
return versionSuffix(getconf);
}
if (ldd1 && ldd2 && ldd1.includes(MUSL)) {
return versionSuffix(ldd2);
}
return null;
};
/**
* Resolves with the libc version when it can be determined, `null` otherwise.
* @returns {Promise<?string>}
*/
const version = async () => {
let version = null;
if (isLinux()) {
version = await versionFromFilesystem();
if (!version) {
version = versionFromReport();
}
if (!version) {
const out = await safeCommand();
version = versionFromCommand(out);
}
}
return version;
};
/**
* Returns the libc version when it can be determined, `null` otherwise.
* @returns {?string}
*/
const versionSync = () => {
let version = null;
if (isLinux()) {
version = versionFromFilesystemSync();
if (!version) {
version = versionFromReport();
}
if (!version) {
const out = safeCommandSync();
version = versionFromCommand(out);
}
}
return version;
};
module.exports = {
GLIBC,
MUSL,
family,
familySync,
isNonGlibcLinux,
isNonGlibcLinuxSync,
version,
versionSync
};

View File

@@ -0,0 +1,585 @@
"use strict";
var x = Object.defineProperty;
var G = Object.getOwnPropertyDescriptor;
var J = Object.getOwnPropertyNames;
var U = Object.prototype.hasOwnProperty;
var q = (n) => {
throw TypeError(n);
};
var W = (n, s, t) => s in n ? x(n, s, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[s] = t;
var X = (n, s) => {
for (var t in s)
x(n, t, { get: s[t], enumerable: !0 });
}, Z = (n, s, t, e) => {
if (s && typeof s == "object" || typeof s == "function")
for (let r of J(s))
!U.call(n, r) && r !== t && x(n, r, { get: () => s[r], enumerable: !(e = G(s, r)) || e.enumerable });
return n;
};
var tt = (n) => Z(x({}, "__esModule", { value: !0 }), n);
var M = (n, s, t) => W(n, typeof s != "symbol" ? s + "" : s, t), S = (n, s, t) => s.has(n) || q("Cannot " + t);
var d = (n, s, t) => (S(n, s, "read from private field"), t ? t.call(n) : s.get(n)), L = (n, s, t) => s.has(n) ? q("Cannot add the same private member more than once") : s instanceof WeakSet ? s.add(n) : s.set(n, t), f = (n, s, t, e) => (S(n, s, "write to private field"), e ? e.call(n, t) : s.set(n, t), t);
var N = (n, s, t, e) => ({
set _(r) {
f(n, s, r, t);
},
get _() {
return d(n, s, e);
}
});
// src/index.ts
var ot = {};
X(ot, {
Bench: () => k,
Task: () => v,
hrtimeNow: () => z,
now: () => A
});
module.exports = tt(ot);
// node_modules/.pnpm/yocto-queue@1.0.0/node_modules/yocto-queue/index.js
var B = class {
constructor(s) {
M(this, "value");
M(this, "next");
this.value = s;
}
}, m, E, b, g = class {
constructor() {
L(this, m);
L(this, E);
L(this, b);
this.clear();
}
enqueue(s) {
let t = new B(s);
d(this, m) ? (d(this, E).next = t, f(this, E, t)) : (f(this, m, t), f(this, E, t)), N(this, b)._++;
}
dequeue() {
let s = d(this, m);
if (s)
return f(this, m, d(this, m).next), N(this, b)._--, s.value;
}
clear() {
f(this, m, void 0), f(this, E, void 0), f(this, b, 0);
}
get size() {
return d(this, b);
}
*[Symbol.iterator]() {
let s = d(this, m);
for (; s; )
yield s.value, s = s.next;
}
};
m = new WeakMap(), E = new WeakMap(), b = new WeakMap();
// node_modules/.pnpm/p-limit@4.0.0/node_modules/p-limit/index.js
function y(n) {
if (!((Number.isInteger(n) || n === Number.POSITIVE_INFINITY) && n > 0))
throw new TypeError("Expected `concurrency` to be a number from 1 and up");
let s = new g(), t = 0, e = () => {
t--, s.size > 0 && s.dequeue()();
}, r = async (h, p, a) => {
t++;
let l = (async () => h(...a))();
p(l);
try {
await l;
} catch (T) {
}
e();
}, i = (h, p, a) => {
s.enqueue(r.bind(void 0, h, p, a)), (async () => (await Promise.resolve(), t < n && s.size > 0 && s.dequeue()()))();
}, c = (h, ...p) => new Promise((a) => {
i(h, a, p);
});
return Object.defineProperties(c, {
activeCount: {
get: () => t
},
pendingCount: {
get: () => s.size
},
clearQueue: {
value: () => {
s.clear();
}
}
}), c;
}
// src/event.ts
function o(n, s = null) {
let t = new Event(n);
return s && Object.defineProperty(t, "task", {
value: s,
enumerable: !0,
writable: !1,
configurable: !1
}), t;
}
// src/constants.ts
var et = {
1: 12.71,
2: 4.303,
3: 3.182,
4: 2.776,
5: 2.571,
6: 2.447,
7: 2.365,
8: 2.306,
9: 2.262,
10: 2.228,
11: 2.201,
12: 2.179,
13: 2.16,
14: 2.145,
15: 2.131,
16: 2.12,
17: 2.11,
18: 2.101,
19: 2.093,
20: 2.086,
21: 2.08,
22: 2.074,
23: 2.069,
24: 2.064,
25: 2.06,
26: 2.056,
27: 2.052,
28: 2.048,
29: 2.045,
30: 2.042,
31: 2.0399,
32: 2.0378,
33: 2.0357,
34: 2.0336,
35: 2.0315,
36: 2.0294,
37: 2.0273,
38: 2.0252,
39: 2.0231,
40: 2.021,
41: 2.0198,
42: 2.0186,
43: 2.0174,
44: 2.0162,
45: 2.015,
46: 2.0138,
47: 2.0126,
48: 2.0114,
49: 2.0102,
50: 2.009,
51: 2.0081,
52: 2.0072,
53: 2.0063,
54: 2.0054,
55: 2.0045,
56: 2.0036,
57: 2.0027,
58: 2.0018,
59: 2.0009,
60: 2,
61: 1.9995,
62: 1.999,
63: 1.9985,
64: 1.998,
65: 1.9975,
66: 1.997,
67: 1.9965,
68: 1.996,
69: 1.9955,
70: 1.995,
71: 1.9945,
72: 1.994,
73: 1.9935,
74: 1.993,
75: 1.9925,
76: 1.992,
77: 1.9915,
78: 1.991,
79: 1.9905,
80: 1.99,
81: 1.9897,
82: 1.9894,
83: 1.9891,
84: 1.9888,
85: 1.9885,
86: 1.9882,
87: 1.9879,
88: 1.9876,
89: 1.9873,
90: 1.987,
91: 1.9867,
92: 1.9864,
93: 1.9861,
94: 1.9858,
95: 1.9855,
96: 1.9852,
97: 1.9849,
98: 1.9846,
99: 1.9843,
100: 1.984,
101: 1.9838,
102: 1.9836,
103: 1.9834,
104: 1.9832,
105: 1.983,
106: 1.9828,
107: 1.9826,
108: 1.9824,
109: 1.9822,
110: 1.982,
111: 1.9818,
112: 1.9816,
113: 1.9814,
114: 1.9812,
115: 1.9819,
116: 1.9808,
117: 1.9806,
118: 1.9804,
119: 1.9802,
120: 1.98,
infinity: 1.96
}, P = et;
// src/utils.ts
var st = (n) => n / 1e6, z = () => st(Number(process.hrtime.bigint())), A = () => performance.now();
function nt(n) {
return n !== null && typeof n == "object" && typeof n.then == "function";
}
var j = (n, s) => n.reduce((e, r) => e + (r - s) ** 2, 0) / (n.length - 1) || 0, rt = (async () => {
}).constructor, it = (n) => n.constructor === rt, H = async (n) => {
if (it(n.fn))
return !0;
try {
if (n.opts.beforeEach != null)
try {
await n.opts.beforeEach.call(n);
} catch (e) {
}
let s = n.fn(), t = nt(s);
if (t)
try {
await s;
} catch (e) {
}
if (n.opts.afterEach != null)
try {
await n.opts.afterEach.call(n);
} catch (e) {
}
return t;
} catch (s) {
return !1;
}
};
// src/task.ts
var v = class extends EventTarget {
constructor(t, e, r, i = {}) {
super();
/*
* the number of times the task
* function has been executed
*/
this.runs = 0;
this.bench = t, this.name = e, this.fn = r, this.opts = i;
}
async loop(t, e) {
var T;
let r = this.bench.concurrency === "task", { threshold: i } = this.bench, c = 0, h = [];
if (this.opts.beforeAll != null)
try {
await this.opts.beforeAll.call(this);
} catch (u) {
return { error: u };
}
let p = await H(this), a = async () => {
this.opts.beforeEach != null && await this.opts.beforeEach.call(this);
let u = 0;
if (p) {
let w = this.bench.now();
await this.fn.call(this), u = this.bench.now() - w;
} else {
let w = this.bench.now();
this.fn.call(this), u = this.bench.now() - w;
}
h.push(u), c += u, this.opts.afterEach != null && await this.opts.afterEach.call(this);
}, l = y(i);
try {
let u = [];
for (; (c < t || h.length + l.activeCount + l.pendingCount < e) && !((T = this.bench.signal) != null && T.aborted); )
r ? u.push(l(a)) : await a();
u.length && await Promise.all(u);
} catch (u) {
return { error: u };
}
if (this.opts.afterAll != null)
try {
await this.opts.afterAll.call(this);
} catch (u) {
return { error: u };
}
return { samples: h };
}
/**
* run the current task and write the results in `Task.result` object
*/
async run() {
var r, i;
if ((r = this.result) != null && r.error)
return this;
this.dispatchEvent(o("start", this)), await this.bench.setup(this, "run");
let { samples: t, error: e } = await this.loop(this.bench.time, this.bench.iterations);
if (this.bench.teardown(this, "run"), t) {
let c = t.reduce((O, F) => O + F, 0);
this.runs = t.length, t.sort((O, F) => O - F);
let h = c / this.runs, p = 1e3 / h, a = t.length, l = a - 1, T = t[0], u = t[l], w = c / t.length || 0, R = j(t, w), I = Math.sqrt(R), _ = I / Math.sqrt(a), K = P[String(Math.round(l) || 1)] || P.infinity, C = _ * K, V = C / w * 100, Q = t[Math.ceil(a * 0.75) - 1], Y = t[Math.ceil(a * 0.99) - 1], $ = t[Math.ceil(a * 0.995) - 1], D = t[Math.ceil(a * 0.999) - 1];
if ((i = this.bench.signal) != null && i.aborted)
return this;
this.setResult({
totalTime: c,
min: T,
max: u,
hz: p,
period: h,
samples: t,
mean: w,
variance: R,
sd: I,
sem: _,
df: l,
critical: K,
moe: C,
rme: V,
p75: Q,
p99: Y,
p995: $,
p999: D
});
}
if (e) {
if (this.setResult({ error: e }), this.bench.throws)
throw e;
this.dispatchEvent(o("error", this)), this.bench.dispatchEvent(o("error", this));
}
return this.dispatchEvent(o("cycle", this)), this.bench.dispatchEvent(o("cycle", this)), this.dispatchEvent(o("complete", this)), this;
}
/**
* warmup the current task
*/
async warmup() {
var e;
if ((e = this.result) != null && e.error)
return;
this.dispatchEvent(o("warmup", this)), await this.bench.setup(this, "warmup");
let { error: t } = await this.loop(this.bench.warmupTime, this.bench.warmupIterations);
if (this.bench.teardown(this, "warmup"), t && (this.setResult({ error: t }), this.bench.throws))
throw t;
}
addEventListener(t, e, r) {
super.addEventListener(t, e, r);
}
removeEventListener(t, e, r) {
super.removeEventListener(t, e, r);
}
/**
* change the result object values
*/
setResult(t) {
this.result = { ...this.result, ...t }, Object.freeze(this.result);
}
/**
* reset the task to make the `Task.runs` a zero-value and remove the `Task.result`
* object
*/
reset() {
this.dispatchEvent(o("reset", this)), this.runs = 0, this.result = void 0;
}
};
// src/bench.ts
var k = class extends EventTarget {
constructor(t = {}) {
var e, r, i, c, h, p, a, l;
super();
/*
* @private the task map
*/
this._tasks = /* @__PURE__ */ new Map();
this._todos = /* @__PURE__ */ new Map();
/**
* Executes tasks concurrently based on the specified concurrency mode.
*
* - When `mode` is set to `null` (default), concurrency is disabled.
* - When `mode` is set to 'task', each task's iterations (calls of a task function) run concurrently.
* - When `mode` is set to 'bench', different tasks within the bench run concurrently.
*/
this.concurrency = null;
/**
* The maximum number of concurrent tasks to run. Defaults to Infinity.
*/
this.threshold = 1 / 0;
this.warmupTime = 100;
this.warmupIterations = 5;
this.time = 500;
this.iterations = 10;
this.now = A;
this.now = (e = t.now) != null ? e : this.now, this.warmupTime = (r = t.warmupTime) != null ? r : this.warmupTime, this.warmupIterations = (i = t.warmupIterations) != null ? i : this.warmupIterations, this.time = (c = t.time) != null ? c : this.time, this.iterations = (h = t.iterations) != null ? h : this.iterations, this.signal = t.signal, this.throws = (p = t.throws) != null ? p : !1, this.setup = (a = t.setup) != null ? a : () => {
}, this.teardown = (l = t.teardown) != null ? l : () => {
}, this.signal && this.signal.addEventListener(
"abort",
() => {
this.dispatchEvent(o("abort"));
},
{ once: !0 }
);
}
runTask(t) {
var e;
return (e = this.signal) != null && e.aborted ? t : t.run();
}
/**
* run the added tasks that were registered using the
* {@link add} method.
* Note: This method does not do any warmup. Call {@link warmup} for that.
*/
async run() {
if (this.concurrency === "bench")
return this.runConcurrently(this.threshold, this.concurrency);
this.dispatchEvent(o("start"));
let t = [];
for (let e of [...this._tasks.values()])
t.push(await this.runTask(e));
return this.dispatchEvent(o("complete")), t;
}
/**
* See Bench.{@link concurrency}
*/
async runConcurrently(t = 1 / 0, e = "bench") {
if (this.threshold = t, this.concurrency = e, e === "task")
return this.run();
this.dispatchEvent(o("start"));
let r = y(t), i = [];
for (let h of [...this._tasks.values()])
i.push(r(() => this.runTask(h)));
let c = await Promise.all(i);
return this.dispatchEvent(o("complete")), c;
}
/**
* warmup the benchmark tasks.
* This is not run by default by the {@link run} method.
*/
async warmup() {
if (this.concurrency === "bench") {
await this.warmupConcurrently(this.threshold, this.concurrency);
return;
}
this.dispatchEvent(o("warmup"));
for (let [, t] of this._tasks)
await t.warmup();
}
/**
* warmup the benchmark tasks concurrently.
* This is not run by default by the {@link runConcurrently} method.
*/
async warmupConcurrently(t = 1 / 0, e = "bench") {
if (this.threshold = t, this.concurrency = e, e === "task") {
await this.warmup();
return;
}
this.dispatchEvent(o("warmup"));
let r = y(t), i = [];
for (let [, c] of this._tasks)
i.push(r(() => c.warmup()));
await Promise.all(i);
}
/**
* reset each task and remove its result
*/
reset() {
this.dispatchEvent(o("reset")), this._tasks.forEach((t) => {
t.reset();
});
}
/**
* add a benchmark task to the task map
*/
add(t, e, r = {}) {
let i = new v(this, t, e, r);
return this._tasks.set(t, i), this.dispatchEvent(o("add", i)), this;
}
/**
* add a benchmark todo to the todo map
*/
// eslint-disable-next-line @typescript-eslint/no-empty-function
todo(t, e = () => {
}, r = {}) {
let i = new v(this, t, e, r);
return this._todos.set(t, i), this.dispatchEvent(o("todo", i)), this;
}
/**
* remove a benchmark task from the task map
*/
remove(t) {
let e = this.getTask(t);
return e && (this.dispatchEvent(o("remove", e)), this._tasks.delete(t)), this;
}
addEventListener(t, e, r) {
super.addEventListener(t, e, r);
}
removeEventListener(t, e, r) {
super.removeEventListener(t, e, r);
}
/**
* table of the tasks results
*/
table(t) {
return this.tasks.map((e) => {
if (e.result) {
if (e.result.error)
throw e.result.error;
return (t == null ? void 0 : t(e)) || {
"Task Name": e.name,
"ops/sec": e.result.error ? "NaN" : parseInt(e.result.hz.toString(), 10).toLocaleString(),
"Average Time (ns)": e.result.error ? "NaN" : e.result.mean * 1e3 * 1e3,
Margin: e.result.error ? "NaN" : `\xB1${e.result.rme.toFixed(2)}%`,
Samples: e.result.error ? "NaN" : e.result.samples.length
};
}
return null;
});
}
/**
* (getter) tasks results as an array
*/
get results() {
return [...this._tasks.values()].map((t) => t.result);
}
/**
* (getter) tasks as an array
*/
get tasks() {
return [...this._tasks.values()];
}
get todos() {
return [...this._todos.values()];
}
/**
* get a task based on the task name
*/
getTask(t) {
return this._tasks.get(t);
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Bench,
Task,
hrtimeNow,
now
});