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,890 @@
// @ts-self-types="./index.d.ts"
import levn from 'levn';
/**
* @fileoverview Config Comment Parser
* @author Nicholas C. Zakas
*/
//-----------------------------------------------------------------------------
// Type Definitions
//-----------------------------------------------------------------------------
/** @import * as $eslintcore from "@eslint/core"; */
/** @typedef {$eslintcore.RuleConfig} RuleConfig */
/** @typedef {$eslintcore.RulesConfig} RulesConfig */
/** @import * as $typests from "./types.ts"; */
/** @typedef {$typests.StringConfig} StringConfig */
/** @typedef {$typests.BooleanConfig} BooleanConfig */
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
const directivesPattern = /^([a-z]+(?:-[a-z]+)*)(?:\s|$)/u;
const validSeverities = new Set([0, 1, 2, "off", "warn", "error"]);
/**
* Determines if the severity in the rule configuration is valid.
* @param {RuleConfig} ruleConfig A rule's configuration.
* @returns {boolean} `true` if the severity is valid, otherwise `false`.
*/
function isSeverityValid(ruleConfig) {
const severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
return validSeverities.has(severity);
}
/**
* Determines if all severities in the rules configuration are valid.
* @param {RulesConfig} rulesConfig The rules configuration to check.
* @returns {boolean} `true` if all severities are valid, otherwise `false`.
*/
function isEverySeverityValid(rulesConfig) {
return Object.values(rulesConfig).every(isSeverityValid);
}
/**
* Represents a directive comment.
*/
class DirectiveComment {
/**
* The label of the directive, such as "eslint", "eslint-disable", etc.
* @type {string}
*/
label = "";
/**
* The value of the directive (the string after the label).
* @type {string}
*/
value = "";
/**
* The justification of the directive (the string after the --).
* @type {string}
*/
justification = "";
/**
* Creates a new directive comment.
* @param {string} label The label of the directive.
* @param {string} value The value of the directive.
* @param {string} justification The justification of the directive.
*/
constructor(label, value, justification) {
this.label = label;
this.value = value;
this.justification = justification;
}
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Object to parse ESLint configuration comments.
*/
class ConfigCommentParser {
/**
* Parses a list of "name:string_value" or/and "name" options divided by comma or
* whitespace. Used for "global" comments.
* @param {string} string The string to parse.
* @returns {StringConfig} Result map object of names and string values, or null values if no value was provided.
*/
parseStringConfig(string) {
const items = /** @type {StringConfig} */ ({});
// Collapse whitespace around `:` and `,` to make parsing easier
const trimmedString = string
.trim()
.replace(/(?<!\s)\s*([:,])\s*/gu, "$1");
trimmedString.split(/\s|,+/u).forEach(name => {
if (!name) {
return;
}
// value defaults to null (if not provided), e.g: "foo" => ["foo", null]
const [key, value = null] = name.split(":");
items[key] = value;
});
return items;
}
/**
* Parses a JSON-like config.
* @param {string} string The string to parse.
* @returns {({ok: true, config: RulesConfig}|{ok: false, error: {message: string}})} Result map object
*/
parseJSONLikeConfig(string) {
// Parses a JSON-like comment by the same way as parsing CLI option.
try {
const items =
/** @type {RulesConfig} */ (levn.parse("Object", string)) || {};
/*
* When the configuration has any invalid severities, it should be completely
* ignored. This is because the configuration is not valid and should not be
* applied.
*
* For example, the following configuration is invalid:
*
* "no-alert: 2 no-console: 2"
*
* This results in a configuration of { "no-alert": "2 no-console: 2" }, which is
* not valid. In this case, the configuration should be ignored.
*/
if (isEverySeverityValid(items)) {
return {
ok: true,
config: items,
};
}
} catch {
// levn parsing error: ignore to parse the string by a fallback.
}
/*
* Optionator cannot parse commaless notations.
* But we are supporting that. So this is a fallback for that.
*/
const normalizedString = string
.replace(/(?<![-a-zA-Z0-9/])([-a-zA-Z0-9/]+):/gu, '"$1":')
.replace(/([\]0-9])\s+(?=")/u, "$1,");
try {
const items = JSON.parse(`{${normalizedString}}`);
return {
ok: true,
config: items,
};
} catch (ex) {
const errorMessage = ex instanceof Error ? ex.message : String(ex);
return {
ok: false,
error: {
message: `Failed to parse JSON from '${normalizedString}': ${errorMessage}`,
},
};
}
}
/**
* Parses a config of values separated by comma.
* @param {string} string The string to parse.
* @returns {BooleanConfig} Result map of values and true values
*/
parseListConfig(string) {
const items = /** @type {BooleanConfig} */ ({});
string.split(",").forEach(name => {
const trimmedName = name
.trim()
.replace(
/^(?<quote>['"]?)(?<ruleId>.*)\k<quote>$/su,
"$<ruleId>",
);
if (trimmedName) {
items[trimmedName] = true;
}
});
return items;
}
/**
* Extract the directive and the justification from a given directive comment and trim them.
* @param {string} value The comment text to extract.
* @returns {{directivePart: string, justificationPart: string}} The extracted directive and justification.
*/
#extractDirectiveComment(value) {
const match = /\s-{2,}\s/u.exec(value);
if (!match) {
return { directivePart: value.trim(), justificationPart: "" };
}
const directive = value.slice(0, match.index).trim();
const justification = value.slice(match.index + match[0].length).trim();
return { directivePart: directive, justificationPart: justification };
}
/**
* Parses a directive comment into directive text and value.
* @param {string} string The string with the directive to be parsed.
* @returns {DirectiveComment|undefined} The parsed directive or `undefined` if the directive is invalid.
*/
parseDirective(string) {
const { directivePart, justificationPart } =
this.#extractDirectiveComment(string);
const match = directivesPattern.exec(directivePart);
if (!match) {
return undefined;
}
const directiveText = match[1];
const directiveValue = directivePart.slice(
match.index + directiveText.length,
);
return new DirectiveComment(
directiveText,
directiveValue.trim(),
justificationPart,
);
}
}
/**
* @fileoverview A collection of helper classes for implementing `SourceCode`.
* @author Nicholas C. Zakas
*/
/* eslint class-methods-use-this: off -- Required to complete interface. */
//-----------------------------------------------------------------------------
// Type Definitions
//-----------------------------------------------------------------------------
/** @typedef {$eslintcore.VisitTraversalStep} VisitTraversalStep */
/** @typedef {$eslintcore.CallTraversalStep} CallTraversalStep */
/** @typedef {$eslintcore.TraversalStep} TraversalStep */
/** @typedef {$eslintcore.SourceLocation} SourceLocation */
/** @typedef {$eslintcore.SourceLocationWithOffset} SourceLocationWithOffset */
/** @typedef {$eslintcore.SourceRange} SourceRange */
/** @typedef {$eslintcore.Directive} IDirective */
/** @typedef {$eslintcore.DirectiveType} DirectiveType */
/** @typedef {$eslintcore.SourceCodeBaseTypeOptions} SourceCodeBaseTypeOptions */
/**
* @typedef {import("@eslint/core").TextSourceCode<Options>} TextSourceCode
* @template {SourceCodeBaseTypeOptions} [Options=SourceCodeBaseTypeOptions]
*/
/** @typedef {$eslintcore.RuleVisitor} RuleVisitor */
/**
* @typedef {import("./types.ts").CustomRuleVisitorWithExit<RuleVisitorType>} CustomRuleVisitorWithExit
* @template {RuleVisitor} RuleVisitorType
*/
/** @typedef {$typests.CustomRuleTypeDefinitions} CustomRuleTypeDefinitions */
/**
* @typedef {import("./types.ts").CustomRuleDefinitionType<LanguageSpecificOptions, Options>} CustomRuleDefinitionType
* @template {Omit<import("@eslint/core").RuleDefinitionTypeOptions, keyof CustomRuleTypeDefinitions>} LanguageSpecificOptions
* @template {Partial<CustomRuleTypeDefinitions>} Options
*/
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
/**
* Determines if a node has ESTree-style loc information.
* @param {object} node The node to check.
* @returns {node is {loc:SourceLocation}} `true` if the node has ESTree-style loc information, `false` if not.
*/
function hasESTreeStyleLoc(node) {
return "loc" in node;
}
/**
* Determines if a node has position-style loc information.
* @param {object} node The node to check.
* @returns {node is {position:SourceLocation}} `true` if the node has position-style range information, `false` if not.
*/
function hasPosStyleLoc(node) {
return "position" in node;
}
/**
* Determines if a node has ESTree-style range information.
* @param {object} node The node to check.
* @returns {node is {range:SourceRange}} `true` if the node has ESTree-style range information, `false` if not.
*/
function hasESTreeStyleRange(node) {
return "range" in node;
}
/**
* Determines if a node has position-style range information.
* @param {object} node The node to check.
* @returns {node is {position:SourceLocationWithOffset}} `true` if the node has position-style range information, `false` if not.
*/
function hasPosStyleRange(node) {
return "position" in node;
}
/**
* Performs binary search to find the line number containing a given target index.
* Returns the lower bound - the index of the first element greater than the target.
* **Please note that the `lineStartIndices` should be sorted in ascending order**.
* - Time Complexity: O(log n) - Significantly faster than linear search for large files.
* @param {number[]} lineStartIndices Sorted array of line start indices.
* @param {number} targetIndex The target index to find the line number for.
* @returns {number} The line number for the target index.
*/
function findLineNumberBinarySearch(lineStartIndices, targetIndex) {
let low = 0;
let high = lineStartIndices.length - 1;
while (low < high) {
const mid = ((low + high) / 2) | 0; // Use bitwise OR to floor the division.
if (targetIndex < lineStartIndices[mid]) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* A class to represent a step in the traversal process where a node is visited.
* @implements {VisitTraversalStep}
*/
class VisitNodeStep {
/**
* The type of the step.
* @type {"visit"}
* @readonly
*/
type = "visit";
/**
* The kind of the step. Represents the same data as the `type` property
* but it's a number for performance.
* @type {1}
* @readonly
*/
kind = 1;
/**
* The target of the step.
* @type {object}
*/
target;
/**
* The phase of the step.
* @type {1|2}
*/
phase;
/**
* The arguments of the step.
* @type {Array<any>}
*/
args;
/**
* Creates a new instance.
* @param {Object} options The options for the step.
* @param {object} options.target The target of the step.
* @param {1|2} options.phase The phase of the step.
* @param {Array<any>} options.args The arguments of the step.
*/
constructor({ target, phase, args }) {
this.target = target;
this.phase = phase;
this.args = args;
}
}
/**
* A class to represent a step in the traversal process where a
* method is called.
* @implements {CallTraversalStep}
*/
class CallMethodStep {
/**
* The type of the step.
* @type {"call"}
* @readonly
*/
type = "call";
/**
* The kind of the step. Represents the same data as the `type` property
* but it's a number for performance.
* @type {2}
* @readonly
*/
kind = 2;
/**
* The name of the method to call.
* @type {string}
*/
target;
/**
* The arguments to pass to the method.
* @type {Array<any>}
*/
args;
/**
* Creates a new instance.
* @param {Object} options The options for the step.
* @param {string} options.target The target of the step.
* @param {Array<any>} options.args The arguments of the step.
*/
constructor({ target, args }) {
this.target = target;
this.args = args;
}
}
/**
* A class to represent a directive comment.
* @implements {IDirective}
*/
class Directive {
/**
* The type of directive.
* @type {DirectiveType}
* @readonly
*/
type;
/**
* The node representing the directive.
* @type {unknown}
* @readonly
*/
node;
/**
* Everything after the "eslint-disable" portion of the directive,
* but before the "--" that indicates the justification.
* @type {string}
* @readonly
*/
value;
/**
* The justification for the directive.
* @type {string}
* @readonly
*/
justification;
/**
* Creates a new instance.
* @param {Object} options The options for the directive.
* @param {"disable"|"enable"|"disable-next-line"|"disable-line"} options.type The type of directive.
* @param {unknown} options.node The node representing the directive.
* @param {string} options.value The value of the directive.
* @param {string} options.justification The justification for the directive.
*/
constructor({ type, node, value, justification }) {
this.type = type;
this.node = node;
this.value = value;
this.justification = justification;
}
}
/**
* Source Code Base Object
* @template {SourceCodeBaseTypeOptions & {RootNode: object, SyntaxElementWithLoc: object}} [Options=SourceCodeBaseTypeOptions & {RootNode: object, SyntaxElementWithLoc: object}]
* @implements {TextSourceCode<Options>}
*/
class TextSourceCodeBase {
/**
* The lines of text in the source code.
* @type {Array<string>}
*/
#lines = [];
/**
* The indices of the start of each line in the source code.
* @type {Array<number>}
*/
#lineStartIndices = [0];
/**
* The pattern to match lineEndings in the source code.
* @type {RegExp}
*/
#lineEndingPattern;
/**
* The AST of the source code.
* @type {Options['RootNode']}
*/
ast;
/**
* The text of the source code.
* @type {string}
*/
text;
/**
* Creates a new instance.
* @param {Object} options The options for the instance.
* @param {string} options.text The source code text.
* @param {Options['RootNode']} options.ast The root AST node.
* @param {RegExp} [options.lineEndingPattern] The pattern to match lineEndings in the source code. Defaults to `/\r?\n/u`.
*/
constructor({ text, ast, lineEndingPattern = /\r?\n/u }) {
this.ast = ast;
this.text = text;
// Remove the global(`g`) and sticky(`y`) flags from the `lineEndingPattern` to avoid issues with lastIndex.
this.#lineEndingPattern = new RegExp(
lineEndingPattern.source,
lineEndingPattern.flags.replace(/[gy]/gu, ""),
);
}
/**
* Finds the next line in the source text and updates `#lines` and `#lineStartIndices`.
* @param {string} text The text to search for the next line.
* @returns {boolean} `true` if a next line was found, `false` otherwise.
*/
#findNextLine(text) {
const match = this.#lineEndingPattern.exec(text);
if (!match) {
return false;
}
this.#lines.push(text.slice(0, match.index));
this.#lineStartIndices.push(
(this.#lineStartIndices.at(-1) ?? 0) +
match.index +
match[0].length,
);
return true;
}
/**
* Ensures `#lines` is lazily calculated from the source text.
* @returns {void}
*/
#ensureLines() {
// If `#lines` has already been calculated, do nothing.
if (this.#lines.length === this.#lineStartIndices.length) {
return;
}
while (
this.#findNextLine(this.text.slice(this.#lineStartIndices.at(-1)))
) {
// Continue parsing until no more matches are found.
}
this.#lines.push(this.text.slice(this.#lineStartIndices.at(-1)));
Object.freeze(this.#lines);
}
/**
* Ensures `#lineStartIndices` is lazily calculated up to the specified index.
* @param {number} index The index of a character in a file.
* @returns {void}
*/
#ensureLineStartIndicesFromIndex(index) {
// If we've already parsed up to or beyond this index, do nothing.
if (index <= (this.#lineStartIndices.at(-1) ?? 0)) {
return;
}
while (
index > (this.#lineStartIndices.at(-1) ?? 0) &&
this.#findNextLine(this.text.slice(this.#lineStartIndices.at(-1)))
) {
// Continue parsing until no more matches are found.
}
}
/**
* Ensures `#lineStartIndices` is lazily calculated up to the specified loc.
* @param {Object} loc A line/column location.
* @param {number} loc.line The line number of the location. (0 or 1-indexed based on language.)
* @param {number} lineStart The line number at which the parser starts counting.
* @returns {void}
*/
#ensureLineStartIndicesFromLoc(loc, lineStart) {
// Calculate line indices up to the potentially next line, as it is needed for the followup calculation.
const nextLocLineIndex = loc.line - lineStart + 1;
const lastCalculatedLineIndex = this.#lineStartIndices.length - 1;
let additionalLinesNeeded = nextLocLineIndex - lastCalculatedLineIndex;
// If we've already parsed up to or beyond this line, do nothing.
if (additionalLinesNeeded <= 0) {
return;
}
while (
additionalLinesNeeded > 0 &&
this.#findNextLine(this.text.slice(this.#lineStartIndices.at(-1)))
) {
// Continue parsing until no more matches are found or we have enough lines.
additionalLinesNeeded -= 1;
}
}
/**
* Returns the loc information for the given node or token.
* @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the loc information for.
* @returns {SourceLocation} The loc information for the node or token.
* @throws {Error} If the node or token does not have loc information.
*/
getLoc(nodeOrToken) {
if (hasESTreeStyleLoc(nodeOrToken)) {
return nodeOrToken.loc;
}
if (hasPosStyleLoc(nodeOrToken)) {
return nodeOrToken.position;
}
throw new Error(
"Custom getLoc() method must be implemented in the subclass.",
);
}
/**
* Converts a source text index into a `{ line: number, column: number }` pair.
* @param {number} index The index of a character in a file.
* @throws {TypeError|RangeError} If non-numeric index or index out of range.
* @returns {{line: number, column: number}} A `{ line: number, column: number }` location object with 0 or 1-indexed line and 0 or 1-indexed column based on language.
* @public
*/
getLocFromIndex(index) {
if (typeof index !== "number") {
throw new TypeError("Expected `index` to be a number.");
}
if (index < 0 || index > this.text.length) {
throw new RangeError(
`Index out of range (requested index ${index}, but source text has length ${this.text.length}).`,
);
}
const {
start: { line: lineStart, column: columnStart },
end: { line: lineEnd, column: columnEnd },
} = this.getLoc(this.ast);
// If the index is at the start, return the start location of the root node.
if (index === 0) {
return {
line: lineStart,
column: columnStart,
};
}
// If the index is `this.text.length`, return the location one "spot" past the last character of the file.
if (index === this.text.length) {
return {
line: lineEnd,
column: columnEnd,
};
}
// Ensure `#lineStartIndices` are lazily calculated.
this.#ensureLineStartIndicesFromIndex(index);
/*
* To figure out which line `index` is on, determine the last place at which index could
* be inserted into `#lineStartIndices` to keep the list sorted.
*/
const lineNumber =
(index >= (this.#lineStartIndices.at(-1) ?? 0)
? this.#lineStartIndices.length
: findLineNumberBinarySearch(this.#lineStartIndices, index)) -
1 +
lineStart;
return {
line: lineNumber,
column:
index -
this.#lineStartIndices[lineNumber - lineStart] +
columnStart,
};
}
/**
* Converts a `{ line: number, column: number }` pair into a source text index.
* @param {Object} loc A line/column location.
* @param {number} loc.line The line number of the location. (0 or 1-indexed based on language.)
* @param {number} loc.column The column number of the location. (0 or 1-indexed based on language.)
* @throws {TypeError|RangeError} If `loc` is not an object with a numeric
* `line` and `column`, if the `line` is less than or equal to zero or
* the `line` or `column` is out of the expected range.
* @returns {number} The index of the line/column location in a file.
* @public
*/
getIndexFromLoc(loc) {
if (
loc === null ||
typeof loc !== "object" ||
typeof loc.line !== "number" ||
typeof loc.column !== "number"
) {
throw new TypeError(
"Expected `loc` to be an object with numeric `line` and `column` properties.",
);
}
const {
start: { line: lineStart, column: columnStart },
end: { line: lineEnd, column: columnEnd },
} = this.getLoc(this.ast);
if (loc.line < lineStart || lineEnd < loc.line) {
throw new RangeError(
`Line number out of range (line ${loc.line} requested). Valid range: ${lineStart}-${lineEnd}`,
);
}
// If the loc is at the start, return the start index of the root node.
if (loc.line === lineStart && loc.column === columnStart) {
return 0;
}
// If the loc is at the end, return the index one "spot" past the last character of the file.
if (loc.line === lineEnd && loc.column === columnEnd) {
return this.text.length;
}
// Ensure `#lineStartIndices` are lazily calculated.
this.#ensureLineStartIndicesFromLoc(loc, lineStart);
const isLastLine = loc.line === lineEnd;
const lineStartIndex = this.#lineStartIndices[loc.line - lineStart];
const lineEndIndex = isLastLine
? this.text.length
: this.#lineStartIndices[loc.line - lineStart + 1];
const positionIndex = lineStartIndex + loc.column - columnStart;
if (
loc.column < columnStart ||
(isLastLine && positionIndex > lineEndIndex) ||
(!isLastLine && positionIndex >= lineEndIndex)
) {
throw new RangeError(
`Column number out of range (column ${loc.column} requested). Valid range for line ${loc.line}: ${columnStart}-${lineEndIndex - lineStartIndex + columnStart + (isLastLine ? 0 : -1)}`,
);
}
return positionIndex;
}
/**
* Returns the range information for the given node or token.
* @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the range information for.
* @returns {SourceRange} The range information for the node or token.
* @throws {Error} If the node or token does not have range information.
*/
getRange(nodeOrToken) {
if (hasESTreeStyleRange(nodeOrToken)) {
return nodeOrToken.range;
}
if (hasPosStyleRange(nodeOrToken)) {
return [
nodeOrToken.position.start.offset,
nodeOrToken.position.end.offset,
];
}
throw new Error(
"Custom getRange() method must be implemented in the subclass.",
);
}
/* eslint-disable no-unused-vars -- Required to complete interface. */
/**
* Returns the parent of the given node.
* @param {Options['SyntaxElementWithLoc']} node The node to get the parent of.
* @returns {Options['SyntaxElementWithLoc']|undefined} The parent of the node.
* @throws {Error} If the method is not implemented in the subclass.
*/
getParent(node) {
throw new Error("Not implemented.");
}
/* eslint-enable no-unused-vars -- Required to complete interface. */
/**
* Gets all the ancestors of a given node
* @param {Options['SyntaxElementWithLoc']} node The node
* @returns {Array<Options['SyntaxElementWithLoc']>} All the ancestor nodes in the AST, not including the provided node, starting
* from the root node at index 0 and going inwards to the parent node.
* @throws {TypeError} When `node` is missing.
*/
getAncestors(node) {
if (!node) {
throw new TypeError("Missing required argument: node.");
}
const ancestorsStartingAtParent = [];
for (
let ancestor = this.getParent(node);
ancestor;
ancestor = this.getParent(ancestor)
) {
ancestorsStartingAtParent.push(ancestor);
}
return ancestorsStartingAtParent.reverse();
}
/**
* Gets the source code for the given node.
* @param {Options['SyntaxElementWithLoc']} [node] The AST node to get the text for.
* @param {number} [beforeCount] The number of characters before the node to retrieve.
* @param {number} [afterCount] The number of characters after the node to retrieve.
* @returns {string} The text representing the AST node.
* @public
*/
getText(node, beforeCount, afterCount) {
if (node) {
const range = this.getRange(node);
return this.text.slice(
Math.max(range[0] - (beforeCount || 0), 0),
range[1] + (afterCount || 0),
);
}
return this.text;
}
/**
* Gets the entire source text split into an array of lines.
* @returns {Array<string>} The source text as an array of lines.
* @public
*/
get lines() {
this.#ensureLines(); // Ensure `#lines` is lazily calculated.
return this.#lines;
}
/**
* Traverse the source code and return the steps that were taken.
* @returns {Iterable<TraversalStep>} The steps that were taken while traversing the source code.
*/
traverse() {
throw new Error("Not implemented.");
}
}
export { CallMethodStep, ConfigCommentParser, Directive, TextSourceCodeBase, VisitNodeStep };

View File

@@ -0,0 +1,58 @@
import { expectType } from "tsd";
import pretty from "../../";
import PinoPretty, {
PinoPretty as PinoPrettyNamed,
PrettyOptions,
colorizerFactory,
prettyFactory
} from "../../";
import PinoPrettyDefault from "../../";
import * as PinoPrettyStar from "../../";
import PinoPrettyCjsImport = require("../../");
import PrettyStream = PinoPretty.PrettyStream;
const PinoPrettyCjs = require("../../");
const options: PinoPretty.PrettyOptions = {
colorize: true,
crlf: false,
errorLikeObjectKeys: ["err", "error"],
errorProps: "",
hideObject: true,
levelKey: "level",
levelLabel: "foo",
messageFormat: false,
ignore: "",
levelFirst: false,
messageKey: "msg",
timestampKey: "timestamp",
minimumLevel: "trace",
translateTime: "UTC:h:MM:ss TT Z",
singleLine: false,
customPrettifiers: {
key: (value) => {
return value.toString().toUpperCase();
},
level: (level, levelKey, log, { label, labelColorized, colors }) => {
return level.toString();
},
foo: (value, key, log, { colors }) => {
return value.toString();
}
},
customLevels: 'verbose:5',
customColors: 'default:white,verbose:gray',
sync: false,
destination: 2,
append: true,
mkdir: true,
useOnlyCustomProps: false,
};
expectType<PrettyStream>(pretty()); // #326
expectType<PrettyStream>(pretty(options));
expectType<PrettyStream>(PinoPrettyNamed(options));
expectType<PrettyStream>(PinoPrettyDefault(options));
expectType<PrettyStream>(PinoPrettyStar.PinoPretty(options));
expectType<PrettyStream>(PinoPrettyCjsImport.PinoPretty(options));
expectType<any>(PinoPrettyCjs(options));

View File

@@ -0,0 +1,10 @@
function _typeof(o) {
"@babel/helpers - typeof";
return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,9 @@
import arrayLikeToArray from "./arrayLikeToArray.js";
function _maybeArrayLike(r, a, e) {
if (a && !Array.isArray(a) && "number" == typeof a.length) {
var y = a.length;
return arrayLikeToArray(a, void 0 !== e && e < y ? e : y);
}
return r(a, e);
}
export { _maybeArrayLike as default };

View File

@@ -0,0 +1,15 @@
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

View File

@@ -0,0 +1,148 @@
# Punycode.js [![punycode on npm](https://img.shields.io/npm/v/punycode)](https://www.npmjs.com/package/punycode) [![](https://data.jsdelivr.com/v1/package/npm/punycode/badge)](https://www.jsdelivr.com/package/npm/punycode)
Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891).
This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm:
* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C)
* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c)
* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c)
* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287)
* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072))
This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated).
This project provides a CommonJS module that uses ES2015+ features and JavaScript module, which work in modern Node.js versions and browsers. For the old Punycode.js version that offers the same functionality in a UMD build with support for older pre-ES2015 runtimes, including Rhino, Ringo, and Narwhal, see [v1.4.1](https://github.com/mathiasbynens/punycode.js/releases/tag/v1.4.1).
## Installation
Via [npm](https://www.npmjs.com/):
```bash
npm install punycode --save
```
In [Node.js](https://nodejs.org/):
> ⚠️ Note that userland modules don't hide core modules.
> For example, `require('punycode')` still imports the deprecated core module even if you executed `npm install punycode`.
> Use `require('punycode/')` to import userland modules rather than core modules.
```js
const punycode = require('punycode/');
```
## API
### `punycode.decode(string)`
Converts a Punycode string of ASCII symbols to a string of Unicode symbols.
```js
// decode domain name parts
punycode.decode('maana-pta'); // 'mañana'
punycode.decode('--dqo34k'); // '☃-⌘'
```
### `punycode.encode(string)`
Converts a string of Unicode symbols to a Punycode string of ASCII symbols.
```js
// encode domain name parts
punycode.encode('mañana'); // 'maana-pta'
punycode.encode('☃-⌘'); // '--dqo34k'
```
### `punycode.toUnicode(input)`
Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesnt matter if you call it on a string that has already been converted to Unicode.
```js
// decode domain names
punycode.toUnicode('xn--maana-pta.com');
// → 'mañana.com'
punycode.toUnicode('xn----dqo34k.com');
// → '☃-⌘.com'
// decode email addresses
punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq');
// → 'джумла@джpумлатест.bрфa'
```
### `punycode.toASCII(input)`
Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesnt matter if you call it with a domain thats already in ASCII.
```js
// encode domain names
punycode.toASCII('mañana.com');
// → 'xn--maana-pta.com'
punycode.toASCII('☃-⌘.com');
// → 'xn----dqo34k.com'
// encode email addresses
punycode.toASCII('джумла@джpумлатест.bрфa');
// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'
```
### `punycode.ucs2`
#### `punycode.ucs2.decode(string)`
Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16.
```js
punycode.ucs2.decode('abc');
// → [0x61, 0x62, 0x63]
// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE:
punycode.ucs2.decode('\uD834\uDF06');
// → [0x1D306]
```
#### `punycode.ucs2.encode(codePoints)`
Creates a string based on an array of numeric code point values.
```js
punycode.ucs2.encode([0x61, 0x62, 0x63]);
// → 'abc'
punycode.ucs2.encode([0x1D306]);
// → '\uD834\uDF06'
```
### `punycode.version`
A string representing the current Punycode.js version number.
## For maintainers
### How to publish a new release
1. On the `main` branch, bump the version number in `package.json`:
```sh
npm version patch -m 'Release v%s'
```
Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/).
Note that this produces a Git commit + tag.
1. Push the release commit and tag:
```sh
git push && git push --tags
```
Our CI then automatically publishes the new release to npm, under both the [`punycode`](https://www.npmjs.com/package/punycode) and [`punycode.js`](https://www.npmjs.com/package/punycode.js) names.
## Author
| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|---|
| [Mathias Bynens](https://mathiasbynens.be/) |
## License
Punycode.js is available under the [MIT](https://mths.be/mit) license.

View File

@@ -0,0 +1,288 @@
/**
* Error to represent when a method is missing on an impl.
*/
export class NoSuchMethodError extends Error {
/**
* Creates a new instance.
* @param {string} methodName The name of the method that was missing.
*/
constructor(methodName: string);
}
/**
* Error to represent when a method is not supported on an impl. This happens
* when a method on `Hfs` is called with one name and the corresponding method
* on the impl has a different name. (Example: `text()` and `bytes()`.)
*/
export class MethodNotSupportedError extends Error {
/**
* Creates a new instance.
* @param {string} methodName The name of the method that was missing.
*/
constructor(methodName: string);
}
/**
* Error to represent when an impl is already set.
*/
export class ImplAlreadySetError extends Error {
/**
* Creates a new instance.
*/
constructor();
}
/**
* A class representing a log entry.
*/
export class LogEntry {
/**
* Creates a new instance.
* @param {string} type The type of log entry.
* @param {any} [data] The data associated with the log entry.
*/
constructor(type: string, data?: any);
/**
* The type of log entry.
* @type {string}
*/
type: string;
/**
* The data associated with the log entry.
* @type {any}
*/
data: any;
/**
* The time at which the log entry was created.
* @type {number}
*/
timestamp: number;
}
/**
* A class representing a file system utility library.
* @implements {HfsImpl}
*/
export class Hfs implements HfsImpl {
/**
* Creates a new instance.
* @param {object} options The options for the instance.
* @param {HfsImpl} options.impl The implementation to use.
*/
constructor({ impl }: {
impl: HfsImpl;
});
/**
* Starts a new log with the given name.
* @param {string} name The name of the log to start;
* @returns {void}
* @throws {Error} When the log already exists.
* @throws {TypeError} When the name is not a non-empty string.
*/
logStart(name: string): void;
/**
* Ends a log with the given name and returns the entries.
* @param {string} name The name of the log to end.
* @returns {Array<LogEntry>} The entries in the log.
* @throws {Error} When the log does not exist.
*/
logEnd(name: string): Array<LogEntry>;
/**
* Determines if the current implementation is the base implementation.
* @returns {boolean} True if the current implementation is the base implementation.
*/
isBaseImpl(): boolean;
/**
* Sets the implementation for this instance.
* @param {object} impl The implementation to use.
* @returns {void}
*/
setImpl(impl: object): void;
/**
* Resets the implementation for this instance back to its original.
* @returns {void}
*/
resetImpl(): void;
/**
* Reads the given file and returns the contents as text. Assumes UTF-8 encoding.
* @param {string|URL} filePath The file to read.
* @returns {Promise<string|undefined>} The contents of the file.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
*/
text(filePath: string | URL): Promise<string | undefined>;
/**
* Reads the given file and returns the contents as JSON. Assumes UTF-8 encoding.
* @param {string|URL} filePath The file to read.
* @returns {Promise<any|undefined>} The contents of the file as JSON.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {SyntaxError} When the file contents are not valid JSON.
* @throws {TypeError} When the file path is not a non-empty string.
*/
json(filePath: string | URL): Promise<any | undefined>;
/**
* Reads the given file and returns the contents as an ArrayBuffer.
* @param {string|URL} filePath The file to read.
* @returns {Promise<ArrayBuffer|undefined>} The contents of the file as an ArrayBuffer.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
* @deprecated Use bytes() instead.
*/
arrayBuffer(filePath: string | URL): Promise<ArrayBuffer | undefined>;
/**
* Reads the given file and returns the contents as an Uint8Array.
* @param {string|URL} filePath The file to read.
* @returns {Promise<Uint8Array|undefined>} The contents of the file as an Uint8Array.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
*/
bytes(filePath: string | URL): Promise<Uint8Array | undefined>;
/**
* Writes the given data to the given file. Creates any necessary directories along the way.
* If the data is a string, UTF-8 encoding is used.
* @param {string|URL} filePath The file to write.
* @param {string|ArrayBuffer|ArrayBufferView} contents The data to write.
* @returns {Promise<void>} A promise that resolves when the file is written.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
*/
write(filePath: string | URL, contents: string | ArrayBuffer | ArrayBufferView): Promise<void>;
/**
* Appends the given data to the given file. Creates any necessary directories along the way.
* If the data is a string, UTF-8 encoding is used.
* @param {string|URL} filePath The file to append to.
* @param {string|ArrayBuffer|ArrayBufferView} contents The data to append.
* @returns {Promise<void>} A promise that resolves when the file is appended to.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
* @throws {TypeError} When the file contents are not a string or ArrayBuffer.
* @throws {Error} When the file cannot be appended to.
*/
append(filePath: string | URL, contents: string | ArrayBuffer | ArrayBufferView): Promise<void>;
/**
* Determines if the given file exists.
* @param {string|URL} filePath The file to check.
* @returns {Promise<boolean>} True if the file exists.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
*/
isFile(filePath: string | URL): Promise<boolean>;
/**
* Determines if the given directory exists.
* @param {string|URL} dirPath The directory to check.
* @returns {Promise<boolean>} True if the directory exists.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the directory path is not a non-empty string.
*/
isDirectory(dirPath: string | URL): Promise<boolean>;
/**
* Creates the given directory.
* @param {string|URL} dirPath The directory to create.
* @returns {Promise<void>} A promise that resolves when the directory is created.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the directory path is not a non-empty string.
*/
createDirectory(dirPath: string | URL): Promise<void>;
/**
* Deletes the given file or empty directory.
* @param {string|URL} filePath The file to delete.
* @returns {Promise<boolean>} A promise that resolves when the file or
* directory is deleted, true if the file or directory is deleted, false
* if the file or directory does not exist.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
*/
delete(filePath: string | URL): Promise<boolean>;
/**
* Deletes the given file or directory recursively.
* @param {string|URL} dirPath The directory to delete.
* @returns {Promise<boolean>} A promise that resolves when the file or
* directory is deleted, true if the file or directory is deleted, false
* if the file or directory does not exist.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the directory path is not a non-empty string.
*/
deleteAll(dirPath: string | URL): Promise<boolean>;
/**
* Returns a list of directory entries for the given path.
* @param {string|URL} dirPath The path to the directory to read.
* @returns {AsyncIterable<HfsDirectoryEntry>} A promise that resolves with the
* directory entries.
* @throws {TypeError} If the directory path is not a string or URL.
* @throws {Error} If the directory cannot be read.
*/
list(dirPath: string | URL): AsyncIterable<HfsDirectoryEntry>;
/**
* Walks a directory using a depth-first traversal and returns the entries
* from the traversal.
* @param {string|URL} dirPath The path to the directory to walk.
* @param {Object} [options] The options for the walk.
* @param {(entry:HfsWalkEntry) => Promise<boolean>|boolean} [options.directoryFilter] A filter function to determine
* if a directory's entries should be included in the walk.
* @param {(entry:HfsWalkEntry) => Promise<boolean>|boolean} [options.entryFilter] A filter function to determine if
* an entry should be included in the walk.
* @returns {AsyncIterable<HfsWalkEntry>} A promise that resolves with the
* directory entries.
* @throws {TypeError} If the directory path is not a string or URL.
* @throws {Error} If the directory cannot be read.
*/
walk(dirPath: string | URL, { directoryFilter, entryFilter }?: {
directoryFilter?: (entry: HfsWalkEntry) => Promise<boolean> | boolean;
entryFilter?: (entry: HfsWalkEntry) => Promise<boolean> | boolean;
}): AsyncIterable<HfsWalkEntry>;
/**
* Returns the size of the given file.
* @param {string|URL} filePath The path to the file to read.
* @returns {Promise<number>} A promise that resolves with the size of the file.
* @throws {TypeError} If the file path is not a string or URL.
* @throws {Error} If the file cannot be read.
*/
size(filePath: string | URL): Promise<number>;
/**
* Returns the last modified timestamp of the given file or directory.
* @param {string|URL} fileOrDirPath The path to the file or directory.
* @returns {Promise<Date|undefined>} A promise that resolves with the last modified date
* or undefined if the file or directory does not exist.
* @throws {TypeError} If the path is not a string or URL.
*/
lastModified(fileOrDirPath: string | URL): Promise<Date | undefined>;
/**
* Copys a file from one location to another.
* @param {string|URL} source The path to the file to copy.
* @param {string|URL} destination The path to the new file.
* @returns {Promise<void>} A promise that resolves when the file is copied.
* @throws {TypeError} If the file path is not a string or URL.
* @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 {string|URL} source The path to the file or directory to copy.
* @param {string|URL} destination The path to copy the file or directory to.
* @returns {Promise<void>} A promise that resolves when the file or directory is
* copied.
* @throws {TypeError} If the directory path is not a string or URL.
* @throws {Error} If the directory cannot be copied.
*/
copyAll(source: string | URL, destination: string | URL): Promise<void>;
/**
* Moves a file from the source path to the destination path.
* @param {string|URL} source The location of the file to move.
* @param {string|URL} destination The destination of the file to move.
* @returns {Promise<void>} A promise that resolves when the move is complete.
* @throws {TypeError} If the file or directory paths are not strings.
* @throws {Error} If the file or directory cannot be moved.
*/
move(source: string | URL, destination: string | URL): Promise<void>;
/**
* Moves a file or directory from one location to another.
* @param {string|URL} source The path to the file or directory to move.
* @param {string|URL} destination The path to move the file or directory to.
* @returns {Promise<void>} A promise that resolves when the file or directory is
* moved.
* @throws {TypeError} If the source is not a string or URL.
* @throws {TypeError} If the destination is not a string or URL.
* @throws {Error} If the file or directory cannot be moved.
*/
moveAll(source: string | URL, destination: string | URL): Promise<void>;
#private;
}
export type HfsImpl = import("@humanfs/types").HfsImpl;
export type HfsDirectoryEntry = import("@humanfs/types").HfsDirectoryEntry;
export type HfsWalkEntry = import("@humanfs/types").HfsWalkEntry;

View File

@@ -0,0 +1,88 @@
'use strict'
const bench = require('fastbench')
const pino = require('../')
const bunyan = require('bunyan')
const bole = require('bole')('bench')
const winston = require('winston')
const fs = require('node:fs')
const dest = fs.createWriteStream('/dev/null')
const plogNodeStream = pino(dest)
delete require.cache[require.resolve('../')]
const plogDest = require('../')(pino.destination('/dev/null'))
delete require.cache[require.resolve('../')]
const plogMinLength = require('../')(pino.destination({ dest: '/dev/null', sync: false, minLength: 4096 }))
delete require.cache[require.resolve('../')]
const loglevel = require('./utils/wrap-log-level')(dest)
const deep = Object.assign({}, require('../package.json'), { level: 'info' })
const max = 10
const blog = bunyan.createLogger({
name: 'myapp',
streams: [{
level: 'trace',
stream: dest
}]
})
require('bole').output({
level: 'info',
stream: dest
}).setFastTime(true)
const chill = winston.createLogger({
transports: [
new winston.transports.Stream({
stream: fs.createWriteStream('/dev/null')
})
]
})
const run = bench([
function benchBunyanDeepObj (cb) {
for (var i = 0; i < max; i++) {
blog.info(deep)
}
setImmediate(cb)
},
function benchWinstonDeepObj (cb) {
for (var i = 0; i < max; i++) {
chill.log(deep)
}
setImmediate(cb)
},
function benchBoleDeepObj (cb) {
for (var i = 0; i < max; i++) {
bole.info(deep)
}
setImmediate(cb)
},
function benchLogLevelDeepObj (cb) {
for (var i = 0; i < max; i++) {
loglevel.info(deep)
}
setImmediate(cb)
},
function benchPinoDeepObj (cb) {
for (var i = 0; i < max; i++) {
plogDest.info(deep)
}
setImmediate(cb)
},
function benchPinoMinLengthDeepObj (cb) {
for (var i = 0; i < max; i++) {
plogMinLength.info(deep)
}
setImmediate(cb)
},
function benchPinoNodeStreamDeepObj (cb) {
for (var i = 0; i < max; i++) {
plogNodeStream.info(deep)
}
setImmediate(cb)
}
], 10000)
run(run)

View File

@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const es2017_full: LibDefinition;

View File

@@ -0,0 +1,135 @@
{
"name": "uuid",
"version": "8.3.2",
"description": "RFC4122 (v1, v4, and v5) UUIDs",
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"keywords": [
"uuid",
"guid",
"rfc4122"
],
"license": "MIT",
"bin": {
"uuid": "./dist/bin/uuid"
},
"sideEffects": false,
"main": "./dist/index.js",
"exports": {
".": {
"node": {
"module": "./dist/esm-node/index.js",
"require": "./dist/index.js",
"import": "./wrapper.mjs"
},
"default": "./dist/esm-browser/index.js"
},
"./package.json": "./package.json"
},
"module": "./dist/esm-node/index.js",
"browser": {
"./dist/md5.js": "./dist/md5-browser.js",
"./dist/rng.js": "./dist/rng-browser.js",
"./dist/sha1.js": "./dist/sha1-browser.js",
"./dist/esm-node/index.js": "./dist/esm-browser/index.js"
},
"files": [
"CHANGELOG.md",
"CONTRIBUTING.md",
"LICENSE.md",
"README.md",
"dist",
"wrapper.mjs"
],
"devDependencies": {
"@babel/cli": "7.11.6",
"@babel/core": "7.11.6",
"@babel/preset-env": "7.11.5",
"@commitlint/cli": "11.0.0",
"@commitlint/config-conventional": "11.0.0",
"@rollup/plugin-node-resolve": "9.0.0",
"babel-eslint": "10.1.0",
"bundlewatch": "0.3.1",
"eslint": "7.10.0",
"eslint-config-prettier": "6.12.0",
"eslint-config-standard": "14.1.1",
"eslint-plugin-import": "2.22.1",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-prettier": "3.1.4",
"eslint-plugin-promise": "4.2.1",
"eslint-plugin-standard": "4.0.1",
"husky": "4.3.0",
"jest": "25.5.4",
"lint-staged": "10.4.0",
"npm-run-all": "4.1.5",
"optional-dev-dependency": "2.0.1",
"prettier": "2.1.2",
"random-seed": "0.3.0",
"rollup": "2.28.2",
"rollup-plugin-terser": "7.0.2",
"runmd": "1.3.2",
"standard-version": "9.0.0"
},
"optionalDevDependencies": {
"@wdio/browserstack-service": "6.4.0",
"@wdio/cli": "6.4.0",
"@wdio/jasmine-framework": "6.4.0",
"@wdio/local-runner": "6.4.0",
"@wdio/spec-reporter": "6.4.0",
"@wdio/static-server-service": "6.4.0",
"@wdio/sync": "6.4.0"
},
"scripts": {
"examples:browser:webpack:build": "cd examples/browser-webpack && npm install && npm run build",
"examples:browser:rollup:build": "cd examples/browser-rollup && npm install && npm run build",
"examples:node:commonjs:test": "cd examples/node-commonjs && npm install && npm test",
"examples:node:esmodules:test": "cd examples/node-esmodules && npm install && npm test",
"lint": "npm run eslint:check && npm run prettier:check",
"eslint:check": "eslint src/ test/ examples/ *.js",
"eslint:fix": "eslint --fix src/ test/ examples/ *.js",
"pretest": "[ -n $CI ] || npm run build",
"test": "BABEL_ENV=commonjs node --throw-deprecation node_modules/.bin/jest test/unit/",
"pretest:browser": "optional-dev-dependency && npm run build && npm-run-all --parallel examples:browser:**",
"test:browser": "wdio run ./wdio.conf.js",
"pretest:node": "npm run build",
"test:node": "npm-run-all --parallel examples:node:**",
"test:pack": "./scripts/testpack.sh",
"pretest:benchmark": "npm run build",
"test:benchmark": "cd examples/benchmark && npm install && npm test",
"prettier:check": "prettier --ignore-path .prettierignore --check '**/*.{js,jsx,json,md}'",
"prettier:fix": "prettier --ignore-path .prettierignore --write '**/*.{js,jsx,json,md}'",
"bundlewatch": "npm run pretest:browser && bundlewatch --config bundlewatch.config.json",
"md": "runmd --watch --output=README.md README_js.md",
"docs": "( node --version | grep -q 'v12' ) && ( npm run build && runmd --output=README.md README_js.md )",
"docs:diff": "npm run docs && git diff --quiet README.md",
"build": "./scripts/build.sh",
"prepack": "npm run build",
"release": "standard-version --no-verify"
},
"repository": {
"type": "git",
"url": "https://github.com/uuidjs/uuid.git"
},
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,jsx,json,md}": [
"prettier --write"
],
"*.{js,jsx}": [
"eslint --fix"
]
},
"standard-version": {
"scripts": {
"postchangelog": "prettier --write CHANGELOG.md"
}
}
}

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Feross Aboukhadijeh, and other contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,275 @@
# ObjectSchema Package
## Overview
A JavaScript object merge/validation utility where you can define a different merge and validation strategy for each key. This is helpful when you need to validate complex data structures and then merge them in a way that is more complex than `Object.assign()`. This is used in the [`@eslint/config-array`](https://npmjs.com/package/@eslint/config-array) package but can also be used on its own.
## Installation
For Node.js and compatible runtimes:
```shell
npm install @eslint/object-schema
# or
yarn add @eslint/object-schema
# or
pnpm install @eslint/object-schema
# or
bun add @eslint/object-schema
```
For Deno:
```shell
deno add @eslint/object-schema
```
## Usage
Import the `ObjectSchema` constructor:
```js
// using ESM
import { ObjectSchema } from "@eslint/object-schema";
// using CommonJS
const { ObjectSchema } = require("@eslint/object-schema");
const schema = new ObjectSchema({
// define a definition for the "downloads" key
downloads: {
required: true,
merge(value1 = 0, value2) {
return value1 + value2;
},
validate(value) {
if (typeof value !== "number") {
throw new Error("Expected downloads to be a number.");
}
},
},
// define a strategy for the "versions" key
versions: {
required: true,
merge(value1 = [], value2) {
return value1.concat(value2);
},
validate(value) {
if (!Array.isArray(value)) {
throw new Error("Expected versions to be an array.");
}
},
},
});
const record1 = {
downloads: 25,
versions: ["v1.0.0", "v1.1.0", "v1.2.0"],
};
const record2 = {
downloads: 125,
versions: ["v2.0.0", "v2.1.0", "v3.0.0"],
};
// make sure the records are valid
schema.validate(record1);
schema.validate(record2);
// merge together (schema.merge() accepts any number of objects)
const result = schema.merge(record1, record2);
// result looks like this:
// {
// downloads: 150,
// versions: ["v1.0.0", "v1.1.0", "v1.2.0", "v2.0.0", "v2.1.0", "v3.0.0"],
// }
```
## Tips and Tricks
### Named merge strategies
Instead of specifying a `merge()` method, you can specify one of the following strings to use a default merge strategy:
- `"assign"` - use `Object.assign()` to merge the two values into one object.
- `"overwrite"` - the second value always replaces the first.
- `"replace"` - the second value replaces the first if the second is not `undefined`.
For example:
```js
const schema = new ObjectSchema({
name: {
merge: "replace",
validate() {},
},
});
```
### Named validation strategies
Instead of specifying a `validate()` method, you can specify one of the following strings to use a default validation strategy:
- `"array"` - value must be an array.
- `"boolean"` - value must be a boolean.
- `"number"` - value must be a number.
- `"object"` - value must be a non-null object, including arrays and non-plain objects.
- `"object?"` - value must be an object or null, including arrays and non-plain objects.
- `"string"` - value must be a string.
- `"string!"` - value must be a non-empty string.
For example:
```js
const schema = new ObjectSchema({
name: {
merge: "replace",
validate: "string",
},
});
```
### Built-in strategy classes
The package also exports the built-in merge and validation strategies as two classes with static methods:
- `MergeStrategy` - built-in merge functions (`assign`, `overwrite`, `replace`).
- `ValidationStrategy` - built-in validation functions (`array`, `boolean`, `number`, `object`, `object?`, `string`, `string!`).
These are the same strategies used when you specify a strategy by name (for example, `merge: "replace"`). You can reference the functions directly if you prefer passing a function instead of a string:
```js
import {
ObjectSchema,
MergeStrategy,
ValidationStrategy,
} from "@eslint/object-schema";
const schema = new ObjectSchema({
name: {
required: true,
merge: MergeStrategy.replace,
validate: ValidationStrategy["string!"],
},
options: {
required: false,
merge: MergeStrategy.assign,
validate: ValidationStrategy["object?"],
},
});
```
Note: Because `object?` and `string!` aren't valid identifiers, you must access them using bracket notation (for example, `ValidationStrategy["object?"]`).
### Subschemas
If you are defining a key that is, itself, an object, you can simplify the process by using a subschema. Instead of defining `merge()` and `validate()`, set a `schema` property that contains a schema definition, like this:
```js
const schema = new ObjectSchema({
name: {
schema: {
first: {
merge: "replace",
validate: "string",
},
last: {
merge: "replace",
validate: "string",
},
},
},
});
schema.validate({
name: {
first: "n",
last: "z",
},
});
```
### Remove Keys During Merge
If the merge strategy for a key returns `undefined`, then the key will not appear in the final object. For example:
```js
const schema = new ObjectSchema({
date: {
merge() {
return undefined;
},
validate(value) {
if (isNaN(Date.parse(value))) {
throw new Error("Invalid date.");
}
},
},
});
const object1 = { date: "5/5/2005" };
const object2 = { date: "6/6/2006" };
const result = schema.merge(object1, object2);
console.log("date" in result); // false
```
### Requiring Another Key Be Present
If you'd like the presence of one key to require the presence of another key, you can use the `requires` property to specify an array of other properties that any key requires. For example:
```js
const schema = new ObjectSchema({
date: {
merge() {
return undefined;
},
validate(value) {
if (isNaN(Date.parse(value))) {
throw new Error("Invalid date.");
}
},
},
time: {
requires: ["date"],
merge(first, second) {
return second;
},
validate(value) {
// ...
},
},
});
// throws error: Key "time" requires keys "date".
schema.validate({
time: "13:45",
});
```
In this example, even though `date` is an optional key, it is required to be present whenever `time` is present.
## License
Apache 2.0
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/d472863/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/2d6c3b6/logo.png" alt="Liftoff" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://opensource.sap.com"><img src="https://avatars.githubusercontent.com/u/2531208" alt="SAP" height="32"></a> <a href="https://www.crawljobs.com/"><img src="https://images.opencollective.com/crawljobs-poland/fa43a17/logo.png" alt="CrawlJobs" height="32"></a> <a href="#"><img src="https://images.opencollective.com/aeriusventilations-org/avatar.png" alt="aeriusventilation's Org" height="32"></a> <a href="https://depot.dev"><img src="https://images.opencollective.com/depot/39125a1/logo.png" alt="Depot" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="TestMu AI Open Source Office (Formerly LambdaTest)" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->

View File

@@ -0,0 +1,74 @@
{
"name": "esbuild",
"version": "0.28.2",
"description": "An extremely fast JavaScript and CSS bundler and minifier.",
"repository": {
"type": "git",
"url": "git+https://github.com/evanw/esbuild.git"
},
"scripts": {
"postinstall": "node install.js"
},
"main": "lib/main.js",
"types": "lib/main.d.ts",
"engines": {
"node": ">=18"
},
"bin": {
"esbuild": "bin/esbuild"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.2",
"@esbuild/android-arm": "0.28.2",
"@esbuild/android-arm64": "0.28.2",
"@esbuild/android-x64": "0.28.2",
"@esbuild/darwin-arm64": "0.28.2",
"@esbuild/darwin-x64": "0.28.2",
"@esbuild/freebsd-arm64": "0.28.2",
"@esbuild/freebsd-x64": "0.28.2",
"@esbuild/linux-arm": "0.28.2",
"@esbuild/linux-arm64": "0.28.2",
"@esbuild/linux-ia32": "0.28.2",
"@esbuild/linux-loong64": "0.28.2",
"@esbuild/linux-mips64el": "0.28.2",
"@esbuild/linux-ppc64": "0.28.2",
"@esbuild/linux-riscv64": "0.28.2",
"@esbuild/linux-s390x": "0.28.2",
"@esbuild/linux-x64": "0.28.2",
"@esbuild/netbsd-arm64": "0.28.2",
"@esbuild/netbsd-x64": "0.28.2",
"@esbuild/openbsd-arm64": "0.28.2",
"@esbuild/openbsd-x64": "0.28.2",
"@esbuild/openharmony-arm64": "0.28.2",
"@esbuild/sunos-x64": "0.28.2",
"@esbuild/win32-arm64": "0.28.2",
"@esbuild/win32-ia32": "0.28.2",
"@esbuild/win32-x64": "0.28.2"
},
"license": "MIT",
"esbuild.binaryHashes": {
"@esbuild/aix-ppc64/bin/esbuild": "6de148b932fc5d3b28a97f9f0bc4de8e2b47db478b8ad679e0eaa6b96e00420d",
"@esbuild/android-arm64/bin/esbuild": "84efbbd2cbf21bbfec2aaf304bee79cb2a4a05fe2ea7b861a87f7b8f213ac27d",
"@esbuild/darwin-arm64/bin/esbuild": "10b6243df618d374bb2d5c9cfbe7052e1405f6aa4e53a6164f11a91b9f2e1384",
"@esbuild/darwin-x64/bin/esbuild": "7fe5c9c905fff0a05d92db98929434ab4d3b6dd92d7a7688922db74380c75df3",
"@esbuild/freebsd-arm64/bin/esbuild": "6aba108a68b93064e491bfb1ecfa28843b4d4e504dff0627f53f68f6bb015c01",
"@esbuild/freebsd-x64/bin/esbuild": "8a237e222bee0e50556e7b00d83ec2ff43721bf72f19811a5f0ee56f1d40177c",
"@esbuild/linux-arm/bin/esbuild": "d88f751b22095b2f3b42c8c2e8a3f36fabc1705438c5d6e78366b681f8b4e7a5",
"@esbuild/linux-arm64/bin/esbuild": "90bd269553d258e80b19e3ccab4f98f0831f87442a2f056510ce24fd1b425fc2",
"@esbuild/linux-ia32/bin/esbuild": "b1e2d87d79f9a2baa0d3043cdf0dc6716f9f2eea66c58f47588641fd6019f36f",
"@esbuild/linux-loong64/bin/esbuild": "55a66f9854d6798f36b2b5471db74f2e552481887ea14d8bda1634a512383a43",
"@esbuild/linux-mips64el/bin/esbuild": "6bf7921a3af4a801051e056d85c360fe24bb446f488ef3da25f0b8e5cf973db1",
"@esbuild/linux-ppc64/bin/esbuild": "c30df60d09bb0ba4853d7b06e244ce966890d61ce60cadd9b22335f6379c316a",
"@esbuild/linux-riscv64/bin/esbuild": "36bdcdc8230eef385838cdfeb0d9a1565cbe4b9ace30097a511d77e894de36a1",
"@esbuild/linux-s390x/bin/esbuild": "bbbc1f92a76a5ca6e2976065222e42b02797363a1f119490dda315f74047741f",
"@esbuild/linux-x64/bin/esbuild": "e1698a3d5c6c0798fee4fd3b5cc816651f460c63d390a7a26ea4beb0b1884100",
"@esbuild/netbsd-arm64/bin/esbuild": "62548519d7ae875d060aa8c94bfb8ed38ef191671a5173d9f626bdb6b7516970",
"@esbuild/netbsd-x64/bin/esbuild": "f9d0e59d2b404559e3a0c958164d96960ebf0e04583b878b1d64d8f1c3698fcc",
"@esbuild/openbsd-arm64/bin/esbuild": "e10c45a0b62456632da41df058d7626b2e7cfe710780a2dc7f9f84681753f3aa",
"@esbuild/openbsd-x64/bin/esbuild": "720bbe607736716f2ecd37962436c5589d801966e868a2ae4e0e7e62d1e4e887",
"@esbuild/sunos-x64/bin/esbuild": "01a3bd9183631ca749f34d15601ea21ba6834614184c5c859f99d54bd683203d",
"@esbuild/win32-arm64/esbuild.exe": "530fb3933af14eefe85dfd06502f826e6ef60fdf4e75228ea67c696db312ecb1",
"@esbuild/win32-ia32/esbuild.exe": "b2e62af5c17e00939583be0a0762fdc469f352869a617edc91371b00454c76f0",
"@esbuild/win32-x64/esbuild.exe": "c7bee37877d0aa6a046e52783fa0a2cf1a9ce5579d68bb3083bda99d4bff18ef"
}
}

View File

@@ -0,0 +1,25 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.decorators = void 0;
const base_config_1 = require("./base-config");
exports.decorators = {
libs: [],
variables: [
['ClassMemberDecoratorContext', base_config_1.TYPE],
['DecoratorContext', base_config_1.TYPE],
['DecoratorMetadataObject', base_config_1.TYPE],
['DecoratorMetadata', base_config_1.TYPE],
['ClassDecoratorContext', base_config_1.TYPE],
['ClassMethodDecoratorContext', base_config_1.TYPE],
['ClassGetterDecoratorContext', base_config_1.TYPE],
['ClassSetterDecoratorContext', base_config_1.TYPE],
['ClassAccessorDecoratorContext', base_config_1.TYPE],
['ClassAccessorDecoratorTarget', base_config_1.TYPE],
['ClassAccessorDecoratorResult', base_config_1.TYPE],
['ClassFieldDecoratorContext', base_config_1.TYPE],
],
};

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 typescript-eslint and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,6 @@
export { VitestNodeSnapshotEnvironment as VitestSnapshotEnvironment } from './chunks/node.COQbm6gK.js';
import '@vitest/snapshot/environment';
import './chunks/utils.BX5Fg8C4.js';
import '@vitest/utils/timers';
console.warn("Importing from \"vitest/snapshot\" is deprecated since Vitest 4.1. Please use \"vitest/runtime\" instead.");

View File

@@ -0,0 +1,25 @@
(MIT License)
Copyright (c) 2013 [Ramesh Nair](http://www.hiddentao.com/)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1 @@
{"version":3,"file":"jsxEmit.enum.d.ts","sourceRoot":"","sources":["../../src/enums/jsxEmit.enum.ts"],"names":[],"mappings":"AAEA,oBAAY,OAAO;IACf,IAAI,IAAI;IACR,QAAQ,IAAI;IACZ,WAAW,IAAI;IACf,KAAK,IAAI;IACT,QAAQ,IAAI;IACZ,WAAW,IAAI;CAClB"}

View File

@@ -0,0 +1,57 @@
{
"reg": {
"name": "reg",
"browser": "IE 10.0.0 (Windows 7 0.0.0)",
"suite": "escape-short",
"hz": 581239.0461276657,
"success": true,
"fastest": false,
"rme": 0.024732909178170403,
"rhz": 0.44122546422972886,
"sampleSize": 170
},
"fn if": {
"name": "fn if",
"browser": "IE 10.0.0 (Windows 7 0.0.0)",
"suite": "escape-short",
"hz": 555729.4222633594,
"success": true,
"fastest": false,
"rme": 0.027909801235014572,
"rhz": 0.42186080573536117,
"sampleSize": 169
},
"fn if reverse": {
"name": "fn if reverse",
"browser": "IE 10.0.0 (Windows 7 0.0.0)",
"suite": "escape-short",
"hz": 501086.63136037166,
"success": true,
"fastest": false,
"rme": 0.01642873238900235,
"rhz": 0.38038081408028707,
"sampleSize": 169
},
"escape31": {
"name": "escape31",
"browser": "IE 10.0.0 (Windows 7 0.0.0)",
"suite": "escape-short",
"hz": 596529.88438048,
"success": true,
"fastest": false,
"rme": 0.02664240853437143,
"rhz": 0.4528329211814042,
"sampleSize": 169
},
"native": {
"name": "native",
"browser": "IE 10.0.0 (Windows 7 0.0.0)",
"suite": "escape-short",
"hz": 1317328.8788813811,
"success": true,
"fastest": true,
"rme": 0.02441843017891321,
"rhz": 1,
"sampleSize": 174
}
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"blake2s.js","sourceRoot":"","sources":["../src/blake2s.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,GAAG,IAAI,KAAK,EAAE,GAAG,IAAI,KAAK,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACrC,OAAO,EAAE,OAAO,IAAI,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,aAAa,CAAC;AACrF,+DAA+D;AAC/D,MAAM,CAAC,MAAM,MAAM,GAAgB,SAAS,CAAC;AAC7C,+DAA+D;AAC/D,MAAM,CAAC,MAAM,GAAG,GAAiB,KAAK,CAAC;AACvC,+DAA+D;AAC/D,MAAM,CAAC,MAAM,GAAG,GAAiB,KAAK,CAAC;AACvC,+DAA+D;AAC/D,MAAM,CAAC,MAAM,QAAQ,GAAsB,UAAU,CAAC;AACtD,+DAA+D;AAC/D,MAAM,CAAC,MAAM,OAAO,GAAe,GAAG,CAAC;AACvC,+DAA+D;AAC/D,MAAM,CAAC,MAAM,OAAO,GAAe,GAAG,CAAC"}

View File

@@ -0,0 +1,10 @@
"use strict";
function _class_private_field_loose_base(receiver, privateKey) {
if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
throw new TypeError("attempted to use private field on non-instance");
}
return receiver;
}
exports._ = _class_private_field_loose_base;

View File

@@ -0,0 +1,572 @@
/* @minVersion 7.20.0 */
/**
Enums are used in this file, but not assigned to vars to avoid non-hoistable values
CONSTRUCTOR = 0;
PUBLIC = 1;
PRIVATE = 2;
FIELD = 0;
ACCESSOR = 1;
METHOD = 2;
GETTER = 3;
SETTER = 4;
STATIC = 5;
CLASS = 10; // only used in assertValidReturnValue
*/
function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
function createAddInitializerMethod(initializers, decoratorFinishedRef) {
return function addInitializer(initializer) {
assertNotFinished(decoratorFinishedRef, "addInitializer");
assertCallable(initializer, "An initializer");
initializers.push(initializer);
};
}
function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
var kindStr;
switch (kind) {
case 1 /* ACCESSOR */:
kindStr = "accessor";
break;
case 2 /* METHOD */:
kindStr = "method";
break;
case 3 /* GETTER */:
kindStr = "getter";
break;
case 4 /* SETTER */:
kindStr = "setter";
break;
default:
kindStr = "field";
}
var ctx = { kind: kindStr, name: isPrivate ? "#" + name : name, static: isStatic, private: isPrivate, metadata: metadata };
var decoratorFinishedRef = { v: false };
ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
var get, set;
if (kind === 0 /* FIELD */) {
if (isPrivate) {
get = desc.get;
set = desc.set;
} else {
get = function() {
return this[name];
};
set = function(v) {
this[name] = v;
};
}
} else if (kind === 2 /* METHOD */) {
get = function() {
return desc.value;
};
} else {
// replace with values that will go through the final getter and setter
if (kind === 1 /* ACCESSOR */ || kind === 3 /* GETTER */) {
get = function() {
return desc.get.call(this);
};
}
if (kind === 1 /* ACCESSOR */ || kind === 4 /* SETTER */) {
set = function(v) {
desc.set.call(this, v);
};
}
}
if (get) {
var originalGet = get;
get = function(target) {
if (arguments.length === 0) {
target = this;
}
return originalGet.call(target);
};
}
if (set) {
var originalSet = set;
set = function(target, value) {
if (arguments.length === 1) {
value = target;
target = this;
}
return originalSet.call(target, value);
};
}
if (isPrivate) {
ctx.access = get && set ? { get: get, set: set } : get ? { get: get } : { set: set };
} else {
var has = function(target) {
return name in target;
};
ctx.access = get && set ? { has: has, get: get, set: set } : get ? { has: has, get: get } : { has: has, set: set };
}
var newValue = dec(value, ctx);
decoratorFinishedRef.v = true;
return newValue;
}
function assertNotFinished(decoratorFinishedRef, fnName) {
if (decoratorFinishedRef.v) {
throw new Error("attempted to call " + fnName + " after decoration was finished");
}
}
function assertCallable(fn, hint) {
if (typeof fn !== "function") {
throw new TypeError(hint + " must be a function");
}
}
function assertValidReturnValue(kind, value) {
var type = typeof value;
if (kind === 1 /* ACCESSOR */) {
if (type !== "object" || value === null) {
throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
}
if (value.get !== undefined) {
assertCallable(value.get, "accessor.get");
}
if (value.set !== undefined) {
assertCallable(value.set, "accessor.set");
}
if (value.init !== undefined) {
assertCallable(value.init, "accessor.init");
}
} else if (type !== "function") {
var hint;
if (kind === 0 /* FIELD */) {
hint = "field";
} else if (kind === 10 /* CLASS */) {
hint = "class";
} else {
hint = "method";
}
throw new TypeError(hint + " decorators must return a function or void 0");
}
}
function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
var decs = decInfo[0];
var desc, init, value;
if (isPrivate) {
if (kind === 0 /* FIELD */ || kind === 1 /* ACCESSOR */) {
desc = { get: decInfo[3], set: decInfo[4] };
} else if (kind === 3 /* GETTER */) {
desc = { get: decInfo[3] };
} else if (kind === 4 /* SETTER */) {
desc = { set: decInfo[3] };
} else {
desc = { value: decInfo[3] };
}
} else if (kind !== 0 /* FIELD */) {
desc = Object.getOwnPropertyDescriptor(base, name);
}
if (kind === 1 /* ACCESSOR */) {
value = { get: desc.get, set: desc.set };
} else if (kind === 2 /* METHOD */) {
value = desc.value;
} else if (kind === 3 /* GETTER */) {
value = desc.get;
} else if (kind === 4 /* SETTER */) {
value = desc.set;
}
var newValue, get, set;
if (typeof decs === "function") {
newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
if (newValue !== void 0) {
assertValidReturnValue(kind, newValue);
if (kind === 0 /* FIELD */) {
init = newValue;
} else if (kind === 1 /* ACCESSOR */) {
init = newValue.init;
get = newValue.get || value.get;
set = newValue.set || value.set;
value = { get: get, set: set };
} else {
value = newValue;
}
}
} else {
for (var i = decs.length - 1; i >= 0; i--) {
var dec = decs[i];
newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
if (newValue !== void 0) {
assertValidReturnValue(kind, newValue);
var newInit;
if (kind === 0 /* FIELD */) {
newInit = newValue;
} else if (kind === 1 /* ACCESSOR */) {
newInit = newValue.init;
get = newValue.get || value.get;
set = newValue.set || value.set;
value = { get: get, set: set };
} else {
value = newValue;
}
if (newInit !== void 0) {
if (init === void 0) {
init = newInit;
} else if (typeof init === "function") {
init = [init, newInit];
} else {
init.push(newInit);
}
}
}
}
}
if (kind === 0 /* FIELD */ || kind === 1 /* ACCESSOR */) {
if (init === void 0) {
// If the initializer was void 0, sub in a dummy initializer
init = function(instance, init) {
return init;
};
} else if (typeof init !== "function") {
var ownInitializers = init;
init = function(instance, init) {
var value = init;
for (var i = 0; i < ownInitializers.length; i++) value = ownInitializers[i].call(instance, value);
return value;
};
} else {
var originalInitializer = init;
init = function(instance, init) {
return originalInitializer.call(instance, init);
};
}
ret.push(init);
}
if (kind !== 0 /* FIELD */) {
if (kind === 1 /* ACCESSOR */) {
desc.get = value.get;
desc.set = value.set;
} else if (kind === 2 /* METHOD */) {
desc.value = value;
} else if (kind === 3 /* GETTER */) {
desc.get = value;
} else if (kind === 4 /* SETTER */) {
desc.set = value;
}
if (isPrivate) {
if (kind === 1 /* ACCESSOR */) {
ret.push(function(instance, args) {
return value.get.call(instance, args);
});
ret.push(function(instance, args) {
return value.set.call(instance, args);
});
} else if (kind === 2 /* METHOD */) {
ret.push(value);
} else {
ret.push(function(instance, args) {
return value.call(instance, args);
});
}
} else {
Object.defineProperty(base, name, desc);
}
}
}
function applyMemberDecs(Class, decInfos, metadata) {
var ret = [];
var protoInitializers;
var staticInitializers;
var existingProtoNonFields = new Map();
var existingStaticNonFields = new Map();
for (var i = 0; i < decInfos.length; i++) {
var decInfo = decInfos[i];
// skip computed property names
if (!Array.isArray(decInfo)) continue;
var kind = decInfo[1];
var name = decInfo[2];
var isPrivate = decInfo.length > 3;
var isStatic = kind >= 5; /* STATIC */
var base;
var initializers;
if (isStatic) {
base = Class;
kind = kind - 5 /* STATIC */;
// initialize staticInitializers when we see a non-field static member
staticInitializers = staticInitializers || [];
initializers = staticInitializers;
} else {
base = Class.prototype;
// initialize protoInitializers when we see a non-field member
protoInitializers = protoInitializers || [];
initializers = protoInitializers;
}
if (kind !== 0 /* FIELD */ && !isPrivate) {
var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
var existingKind = existingNonFields.get(name) || 0;
if (existingKind === true || (existingKind === 3 /* GETTER */ && kind !== 4) /* SETTER */ || (existingKind === 4 /* SETTER */ && kind !== 3) /* GETTER */) {
throw new Error(
"Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "
+ name
);
} else if (!existingKind && kind > 2 /* METHOD */) {
existingNonFields.set(name, kind);
} else {
existingNonFields.set(name, true);
}
}
applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
}
pushInitializers(ret, protoInitializers);
pushInitializers(ret, staticInitializers);
return ret;
}
function pushInitializers(ret, initializers) {
if (initializers) {
ret.push(function(instance) {
for (var i = 0; i < initializers.length; i++) initializers[i].call(instance);
return instance;
});
}
}
function applyClassDecs(targetClass, classDecs, metadata) {
if (classDecs.length > 0) {
var initializers = [];
var newClass = targetClass;
var name = targetClass.name;
for (var i = classDecs.length - 1; i >= 0; i--) {
var decoratorFinishedRef = { v: false };
var nextNewClass = classDecs[i](newClass, { kind: "class", name: name, addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef), metadata });
decoratorFinishedRef.v = true;
if (nextNewClass !== undefined) {
assertValidReturnValue(10, /* CLASS */ nextNewClass);
newClass = nextNewClass;
}
}
return [defineMetadata(newClass, metadata), function() {
for (var i = 0; i < initializers.length; i++) initializers[i].call(newClass);
}];
}
// The transformer will not emit assignment when there are no class decorators,
// so we don't have to return an empty array here.
}
function defineMetadata(Class, metadata) {
return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), { configurable: true, enumerable: true, value: metadata });
}
/**
Basic usage:
applyDecs(
Class,
[
// member decorators
[
dec, // dec or array of decs
0, // kind of value being decorated
'prop', // name of public prop on class containing the value being decorated,
'#p', // the name of the private property (if is private, void 0 otherwise),
]
],
[
// class decorators
dec1, dec2
]
)
```
Fully transpiled example:
```js
@dec
class Class {
@dec
a = 123;
@dec
#a = 123;
@dec
@dec2
accessor b = 123;
@dec
accessor #b = 123;
@dec
c() { console.log('c'); }
@dec
#c() { console.log('privC'); }
@dec
get d() { console.log('d'); }
@dec
get #d() { console.log('privD'); }
@dec
set e(v) { console.log('e'); }
@dec
set #e(v) { console.log('privE'); }
}
// becomes
let initializeInstance;
let initializeClass;
let initA;
let initPrivA;
let initB;
let initPrivB, getPrivB, setPrivB;
let privC;
let privD;
let privE;
let Class;
class _Class {
static {
let ret = applyDecs(
this,
[
[dec, 0, 'a'],
[dec, 0, 'a', (i) => i.#a, (i, v) => i.#a = v],
[[dec, dec2], 1, 'b'],
[dec, 1, 'b', (i) => i.#privBData, (i, v) => i.#privBData = v],
[dec, 2, 'c'],
[dec, 2, 'c', () => console.log('privC')],
[dec, 3, 'd'],
[dec, 3, 'd', () => console.log('privD')],
[dec, 4, 'e'],
[dec, 4, 'e', () => console.log('privE')],
],
[
dec
]
)
initA = ret[0];
initPrivA = ret[1];
initB = ret[2];
initPrivB = ret[3];
getPrivB = ret[4];
setPrivB = ret[5];
privC = ret[6];
privD = ret[7];
privE = ret[8];
initializeInstance = ret[9];
Class = ret[10]
initializeClass = ret[11];
}
a = (initializeInstance(this), initA(this, 123));
#a = initPrivA(this, 123);
#bData = initB(this, 123);
get b() { return this.#bData }
set b(v) { this.#bData = v }
#privBData = initPrivB(this, 123);
get #b() { return getPrivB(this); }
set #b(v) { setPrivB(this, v); }
c() { console.log('c'); }
#c(...args) { return privC(this, ...args) }
get d() { console.log('d'); }
get #d() { return privD(this); }
set e(v) { console.log('e'); }
set #e(v) { privE(this, v); }
}
initializeClass(Class);
*/
_apply_decs_2203_r = function(targetClass, memberDecs, classDecs, parentClass) {
if (parentClass !== void 0) {
var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
}
var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
var e = applyMemberDecs(targetClass, memberDecs, metadata);
if (!classDecs.length) defineMetadata(targetClass, metadata);
return {
e: e,
// Lazily apply class decorations so that member init locals can be properly bound.
get c() {
return applyClassDecs(targetClass, classDecs, metadata);
}
};
};
return _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass);
}
export { _apply_decs_2203_r as _ };

View File

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

View File

@@ -0,0 +1,33 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/////////////////////////////
/// Window Async Iterable APIs
/////////////////////////////
interface FileSystemDirectoryHandle {
[Symbol.asyncIterator](): AsyncIterableIterator<[string, FileSystemHandle]>;
entries(): AsyncIterableIterator<[string, FileSystemHandle]>;
keys(): AsyncIterableIterator<string>;
values(): AsyncIterableIterator<FileSystemHandle>;
}
interface ReadableStream<R = any> {
[Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): AsyncIterableIterator<R>;
values(options?: ReadableStreamIteratorOptions): AsyncIterableIterator<R>;
}

View File

@@ -0,0 +1,29 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
declare namespace Intl {
/**
* The `Intl.getCanonicalLocales()` method returns an array containing
* the canonical locale names. Duplicates will be omitted and elements
* will be validated as structurally valid language tags.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/getCanonicalLocales)
*
* @param locale A list of String values for which to get the canonical locale names
* @returns An array containing the canonical and validated locale names.
*/
function getCanonicalLocales(locale?: string | readonly string[]): string[];
}

View File

@@ -0,0 +1 @@
var m=Object.defineProperty;var a=(r,t)=>m(r,"name",{value:t,configurable:!0});import{r as o}from"./get-pipe-path-_tAJyU_v.mjs";import{r as n}from"./register-C9AniqUt.mjs";let e;const s=a((r,t)=>(e||(e=n({namespace:Date.now().toString()})),e.require(r,t)),"tsxRequire"),i=a((r,t,c)=>(e||(e=n({namespace:Date.now().toString()})),e.resolve(r,t,c)),"resolve");i.paths=o.resolve.paths,s.resolve=i,s.main=o.main,s.extensions=o.extensions,s.cache=o.cache;export{s as t};

View File

@@ -0,0 +1,147 @@
var assert = require('assert');
var stringTest = "Aa1 Bb2 Cc3 \u0000\u001F\u0020\uFFFF☃\"\\\/\f\n\r\t\b. Quisque id mi. Fusce egestas elit eget lorem. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Vivamus euismod mauris. Nam eget dui.";
var stringResult = JSON.stringify(stringTest);
var strReg = /[\u0000-\u001f"\\]/g;
function strReplace(str) {
var code = str.charCodeAt(0);
switch (code) {
case 34: return '\\"';
case 92: return '\\\\';
case 12: return "\\f";
case 10: return "\\n";
case 13: return "\\r";
case 9: return "\\t";
case 8: return "\\b";
default:
if (code > 15) {
return "\\u00" + code.toString(16);
} else {
return "\\u000" + code.toString(16);
}
}
}
function strEscapeIf(str){
var length = str.length;
var buffer = '';
var code = 0;
var i = 0;
for (; i < length; i++) {
code = str.charCodeAt(i);
if (code === 34) buffer += '\\"';
else if (code === 92) buffer += '\\\\';
else if (code > 31) buffer += str[i];
else if (code > 15) buffer += "\\u00" + code.toString(16);
else if (code === 12) buffer += "\\f";
else if (code === 10) buffer += "\\n";
else if (code === 13) buffer += "\\r";
else if (code === 9) buffer += "\\t";
else if (code === 8) buffer += "\\b";
else buffer += "\\u000" + code.toString(16);
}
return buffer;
}
function strEscapeIfReverse(str){
var buffer = '';
var code = 0;
var i = str.length - 1;
for (; i >= 0; i--) {
code = str.charCodeAt(i);
if (code === 34) buffer = '\\"' + buffer;
else if (code === 92) buffer = '\\\\' + buffer;
else if (code > 31) buffer = str[i] + buffer;
else if (code > 15) buffer = "\\u00" + code.toString(16) + buffer;
else if (code === 12) buffer = "\\f" + buffer;
else if (code === 10) buffer = "\\n" + buffer;
else if (code === 13) buffer = "\\r" + buffer;
else if (code === 9) buffer = "\\t" + buffer;
else if (code === 8) buffer = "\\b" + buffer;
else buffer = "\\u000" + code.toString(16) + buffer;
}
return buffer;
}
var escape31 = {
'31': "\\u001f",
'30': "\\u001e",
'29': "\\u001d",
'28': "\\u001c",
'27': "\\u001b",
'26': "\\u001a",
'25': "\\u0019",
'24': "\\u0018",
'23': "\\u0017",
'22': "\\u0016",
'21': "\\u0015",
'20': "\\u0014",
'19': "\\u0013",
'18': "\\u0012",
'17': "\\u0011",
'16': "\\u0010",
'15': "\\u000f",
'14': "\\u000e",
'13': "\\r",
'12': "\\f",
'11': "\\u000b",
'10': "\\n",
'9': "\\t",
'8': "\\b",
'7': "\\u0007",
'6': "\\u0006",
'5': "\\u0005",
'4': "\\u0004",
'3': "\\u0003",
'2': "\\u0002",
'1': "\\u0001",
'0': "\\u0000"
};
function stringEscapeObj(str) {
var i = 0;
var max = str.length;
var buffer = '';
var code = 0;
for (; i < max; i++) {
code = str.charCodeAt(i);
if (code <= 31) buffer += escape31[code];
else if (code === 34) buffer += '\\"';
else if (code === 92) buffer += '\\\\';
else buffer += str[i];
}
return buffer;
}
suite("escape-long", function() {
var minSamples = 120;
benchmark("reg", function() {
assert.equal('"'+stringTest.replace(strReg, strReplace)+'"', stringResult);
}, { minSamples: minSamples });
benchmark("fn if", function() {
assert.equal('"'+strEscapeIf(stringTest)+'"', stringResult);
}, { minSamples: minSamples });
benchmark("fn if reverse", function() {
assert.equal('"'+strEscapeIfReverse(stringTest)+'"', stringResult);
}, { minSamples: minSamples });
benchmark("escape31", function() {
assert.equal('"'+stringEscapeObj(stringTest)+'"', stringResult);
}, { minSamples: minSamples });
benchmark("native", function() {
assert.equal(JSON.stringify(stringTest), stringResult);
}, { minSamples: minSamples })
});

View File

@@ -0,0 +1,243 @@
/**
* Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
* For design rationale of types / exports, see weierstrass module documentation.
* Untwisted Edwards curves exist, but they aren't used in real-world protocols.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { type FHash, type Hex } from '../utils.ts';
import { type AffinePoint, type BasicCurve, type CurveLengths, type CurvePoint, type CurvePointCons } from './curve.ts';
import { type IField, type NLength } from './modular.ts';
export type UVRatio = (u: bigint, v: bigint) => {
isValid: boolean;
value: bigint;
};
/** Instance of Extended Point with coordinates in X, Y, Z, T. */
export interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {
/** extended X coordinate. Different from affine x. */
readonly X: bigint;
/** extended Y coordinate. Different from affine y. */
readonly Y: bigint;
/** extended Z coordinate */
readonly Z: bigint;
/** extended T coordinate */
readonly T: bigint;
/** @deprecated use `toBytes` */
toRawBytes(): Uint8Array;
/** @deprecated use `p.precompute(windowSize)` */
_setWindowSize(windowSize: number): void;
/** @deprecated use .X */
readonly ex: bigint;
/** @deprecated use .Y */
readonly ey: bigint;
/** @deprecated use .Z */
readonly ez: bigint;
/** @deprecated use .T */
readonly et: bigint;
}
/** Static methods of Extended Point with coordinates in X, Y, Z, T. */
export interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {
new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;
CURVE(): EdwardsOpts;
fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;
fromHex(hex: Hex, zip215?: boolean): EdwardsPoint;
/** @deprecated use `import { pippenger } from '@noble/curves/abstract/curve.js';` */
msm(points: EdwardsPoint[], scalars: bigint[]): EdwardsPoint;
}
/** @deprecated use EdwardsPoint */
export type ExtPointType = EdwardsPoint;
/** @deprecated use EdwardsPointCons */
export type ExtPointConstructor = EdwardsPointCons;
/**
* Twisted Edwards curve options.
*
* * a: formula param
* * d: formula param
* * p: prime characteristic (order) of finite field, in which arithmetics is done
* * n: order of prime subgroup a.k.a total amount of valid curve points
* * h: cofactor. h*n is group order; n is subgroup order
* * Gx: x coordinate of generator point a.k.a. base point
* * Gy: y coordinate of generator point
*/
export type EdwardsOpts = Readonly<{
p: bigint;
n: bigint;
h: bigint;
a: bigint;
d: bigint;
Gx: bigint;
Gy: bigint;
}>;
/**
* Extra curve options for Twisted Edwards.
*
* * Fp: redefined Field over curve.p
* * Fn: redefined Field over curve.n
* * uvRatio: helper function for decompression, calculating √(u/v)
*/
export type EdwardsExtraOpts = Partial<{
Fp: IField<bigint>;
Fn: IField<bigint>;
FpFnLE: boolean;
uvRatio: (u: bigint, v: bigint) => {
isValid: boolean;
value: bigint;
};
}>;
/**
* EdDSA (Edwards Digital Signature algorithm) options.
*
* * hash: hash function used to hash secret keys and messages
* * adjustScalarBytes: clears bits to get valid field element
* * domain: Used for hashing
* * mapToCurve: for hash-to-curve standard
* * prehash: RFC 8032 pre-hashing of messages to sign() / verify()
* * randomBytes: function generating random bytes, used for randomSecretKey
*/
export type EdDSAOpts = Partial<{
adjustScalarBytes: (bytes: Uint8Array) => Uint8Array;
domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;
mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;
prehash: FHash;
randomBytes: (bytesLength?: number) => Uint8Array;
}>;
/**
* EdDSA (Edwards Digital Signature algorithm) interface.
*
* Allows to create and verify signatures, create public and secret keys.
*/
export interface EdDSA {
keygen: (seed?: Uint8Array) => {
secretKey: Uint8Array;
publicKey: Uint8Array;
};
getPublicKey: (secretKey: Hex) => Uint8Array;
sign: (message: Hex, secretKey: Hex, options?: {
context?: Hex;
}) => Uint8Array;
verify: (sig: Hex, message: Hex, publicKey: Hex, options?: {
context?: Hex;
zip215: boolean;
}) => boolean;
Point: EdwardsPointCons;
utils: {
randomSecretKey: (seed?: Uint8Array) => Uint8Array;
isValidSecretKey: (secretKey: Uint8Array) => boolean;
isValidPublicKey: (publicKey: Uint8Array, zip215?: boolean) => boolean;
/**
* Converts ed public key to x public key.
*
* There is NO `fromMontgomery`:
* - There are 2 valid ed25519 points for every x25519, with flipped coordinate
* - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*
* accepts inputs on the quadratic twist, which can't be moved to ed25519
*
* @example
* ```js
* const someonesPub = ed25519.getPublicKey(ed25519.utils.randomSecretKey());
* const aPriv = x25519.utils.randomSecretKey();
* x25519.getSharedSecret(aPriv, ed25519.utils.toMontgomery(someonesPub))
* ```
*/
toMontgomery: (publicKey: Uint8Array) => Uint8Array;
/**
* Converts ed secret key to x secret key.
* @example
* ```js
* const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());
* const aPriv = ed25519.utils.randomSecretKey();
* x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(aPriv), someonesPub)
* ```
*/
toMontgomerySecret: (privateKey: Uint8Array) => Uint8Array;
getExtendedPublicKey: (key: Hex) => {
head: Uint8Array;
prefix: Uint8Array;
scalar: bigint;
point: EdwardsPoint;
pointBytes: Uint8Array;
};
/** @deprecated use `randomSecretKey` */
randomPrivateKey: (seed?: Uint8Array) => Uint8Array;
/** @deprecated use `point.precompute()` */
precompute: (windowSize?: number, point?: EdwardsPoint) => EdwardsPoint;
};
lengths: CurveLengths;
}
export declare function edwards(params: EdwardsOpts, extraOpts?: EdwardsExtraOpts): EdwardsPointCons;
/**
* Base class for prime-order points like Ristretto255 and Decaf448.
* These points eliminate cofactor issues by representing equivalence classes
* of Edwards curve points.
*/
export declare abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>> implements CurvePoint<bigint, T> {
static BASE: PrimeEdwardsPoint<any>;
static ZERO: PrimeEdwardsPoint<any>;
static Fp: IField<bigint>;
static Fn: IField<bigint>;
protected readonly ep: EdwardsPoint;
constructor(ep: EdwardsPoint);
abstract toBytes(): Uint8Array;
abstract equals(other: T): boolean;
static fromBytes(_bytes: Uint8Array): any;
static fromHex(_hex: Hex): any;
get x(): bigint;
get y(): bigint;
clearCofactor(): T;
assertValidity(): void;
toAffine(invertedZ?: bigint): AffinePoint<bigint>;
toHex(): string;
toString(): string;
isTorsionFree(): boolean;
isSmallOrder(): boolean;
add(other: T): T;
subtract(other: T): T;
multiply(scalar: bigint): T;
multiplyUnsafe(scalar: bigint): T;
double(): T;
negate(): T;
precompute(windowSize?: number, isLazy?: boolean): T;
abstract is0(): boolean;
protected abstract assertSame(other: T): void;
protected abstract init(ep: EdwardsPoint): T;
/** @deprecated use `toBytes` */
toRawBytes(): Uint8Array;
}
/**
* Initializes EdDSA signatures over given Edwards curve.
*/
export declare function eddsa(Point: EdwardsPointCons, cHash: FHash, eddsaOpts?: EdDSAOpts): EdDSA;
export type CurveType = BasicCurve<bigint> & {
a: bigint;
d: bigint;
/** @deprecated the property will be removed in next release */
hash: FHash;
randomBytes?: (bytesLength?: number) => Uint8Array;
adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array;
domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;
uvRatio?: UVRatio;
prehash?: FHash;
mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>;
};
export type CurveTypeWithLength = Readonly<CurveType & Partial<NLength>>;
export type CurveFn = {
/** @deprecated the property will be removed in next release */
CURVE: CurveType;
keygen: EdDSA['keygen'];
getPublicKey: EdDSA['getPublicKey'];
sign: EdDSA['sign'];
verify: EdDSA['verify'];
Point: EdwardsPointCons;
/** @deprecated use `Point` */
ExtendedPoint: EdwardsPointCons;
utils: EdDSA['utils'];
lengths: CurveLengths;
};
export type EdComposed = {
CURVE: EdwardsOpts;
curveOpts: EdwardsExtraOpts;
hash: FHash;
eddsaOpts: EdDSAOpts;
};
export declare function twistedEdwards(c: CurveTypeWithLength): CurveFn;
//# sourceMappingURL=edwards.d.ts.map

View File

@@ -0,0 +1,8 @@
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
exports.SourceNode = require('./lib/source-node').SourceNode;

View File

@@ -0,0 +1,15 @@
{
"name": "benchmarks",
"version": "1.0.0",
"scripts": {
"valid": "node valid.js",
"ignore": "node ignore.js",
"no_proto": "node no__proto__.js",
"remove": "node remove.js",
"throw": "node throw.js",
"all": "node --version && npm run valid && npm run ignore && npm run no_proto && npm run remove && npm run throw"
},
"dependencies": {
"benchmark": "^2.1.4"
}
}

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FunctionScope = void 0;
const types_1 = require("@typescript-eslint/types");
const ScopeBase_1 = require("./ScopeBase");
const ScopeType_1 = require("./ScopeType");
class FunctionScope extends ScopeBase_1.ScopeBase {
constructor(scopeManager, upperScope, block, isMethodDefinition) {
super(scopeManager, ScopeType_1.ScopeType.function, upperScope, block, isMethodDefinition);
// section 9.2.13, FunctionDeclarationInstantiation.
// NOTE Arrow functions never have an arguments objects.
if (this.block.type !== types_1.AST_NODE_TYPES.ArrowFunctionExpression) {
this.defineVariable('arguments', this.set, this.variables, null, null);
}
}
// References in default parameters isn't resolved to variables which are in their function body.
// const x = 1
// function f(a = x) { // This `x` is resolved to the `x` in the outer scope.
// const x = 2
// console.log(a)
// }
isValidResolution(ref, variable) {
// If `options.globalReturn` is true, `this.block` becomes a Program node.
if (this.block.type === types_1.AST_NODE_TYPES.Program) {
return true;
}
const bodyStart = this.block.body?.range[0] ?? -1;
// It's invalid resolution in the following case:
return !(variable.scope === this &&
ref.identifier.range[0] < bodyStart && // the reference is in the parameter part.
variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body.
);
}
}
exports.FunctionScope = FunctionScope;

View File

@@ -0,0 +1,129 @@
import { URL } from 'node:url'
import Dispatcher from './dispatcher'
import buildConnector from './connector'
import TClientStats from './client-stats'
type ClientConnectOptions<TOpaque = null> = Omit<Dispatcher.ConnectOptions<TOpaque>, 'origin'>
/**
* A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default.
*/
export class Client extends Dispatcher {
constructor (url: string | URL, options?: Client.Options)
/** Property to get and set the pipelining factor. */
pipelining: number
/** `true` after `client.close()` has been called. */
closed: boolean
/** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */
destroyed: boolean
/** Aggregate stats for a Client. */
readonly stats: TClientStats
// Override dispatcher APIs.
override connect<TOpaque = null> (
options: ClientConnectOptions<TOpaque>
): Promise<Dispatcher.ConnectData<TOpaque>>
override connect<TOpaque = null> (
options: ClientConnectOptions<TOpaque>,
callback: (err: Error | null, data: Dispatcher.ConnectData<TOpaque>) => void
): void
}
export declare namespace Client {
export interface Options {
/** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */
maxHeaderSize?: number;
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */
headersTimeout?: number;
/** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */
socketTimeout?: never;
/** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */
requestTimeout?: never;
/** The timeout for establishing a socket connection, in milliseconds. Use `0` to disable it entirely. Default: `10e3` milliseconds (10s). */
connectTimeout?: number;
/** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */
bodyTimeout?: number;
/** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */
idleTimeout?: never;
/** @deprecated unsupported keepAlive, use pipelining=0 instead */
keepAlive?: never;
/** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */
keepAliveTimeout?: number;
/** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */
maxKeepAliveTimeout?: never;
/** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */
keepAliveMaxTimeout?: number;
/** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */
keepAliveTimeoutThreshold?: number;
/** An IPC endpoint, either a Unix domain socket or Windows named pipe. Default: `null`. */
socketPath?: string;
/** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */
pipelining?: number;
/** @deprecated use the connect option instead */
tls?: never;
/** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */
strictContentLength?: boolean;
/** Maximum number of TLS cached sessions used by the built-in connector. Use `0` to disable TLS session caching. Default: `100`. */
maxCachedSessions?: number;
/** Connector options passed to `buildConnector`, or a custom connector function. Default: `null`. */
connect?: Partial<buildConnector.BuildOptions> | buildConnector.connector;
/** The maximum number of requests to send over a single connection before it is reset. Use `0` to disable this limit. Default: `null`. */
maxRequestsPerClient?: number;
/** Local IP address the socket should connect from. */
localAddress?: string;
/** Max response body size in bytes, -1 is disabled */
maxResponseSize?: number;
/** WebSocket-specific options */
webSocket?: Client.WebSocketOptions;
/** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */
autoSelectFamily?: boolean;
/** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */
autoSelectFamilyAttemptTimeout?: number;
/**
* @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation.
* @default true
*/
allowH2?: boolean;
/**
* @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame.
* @default 100
*/
maxConcurrentStreams?: number;
/**
* @description Sets the HTTP/2 stream-level flow-control window size (SETTINGS_INITIAL_WINDOW_SIZE).
* @default 262144
*/
initialWindowSize?: number;
/**
* @description Sets the HTTP/2 connection-level flow-control window size (ClientHttp2Session.setLocalWindowSize).
* @default 524288
*/
connectionWindowSize?: number;
/**
* @description Time interval between PING frames dispatch
* @default 60000
*/
pingInterval?: number;
}
export interface SocketInfo {
localAddress?: string
localPort?: number
remoteAddress?: string
remotePort?: number
remoteFamily?: string
timeout?: number
bytesWritten?: number
bytesRead?: number
}
export interface WebSocketOptions {
/**
* Maximum allowed payload size in bytes for WebSocket messages.
* Applied to uncompressed messages, compressed frame payloads, and decompressed (permessage-deflate) messages.
* Set to 0 to disable the limit.
* @default 134217728 (128 MB)
*/
maxPayloadSize?: number;
}
}
export default Client