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,227 @@
/**
* @fileoverview Disallow trailing spaces at the end of lines.
* @author Nodeca Team <https://github.com/nodeca>
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------
/**
* @import { SourceLocation, SourceRange } from "@eslint/core";
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "no-trailing-spaces",
url: "https://eslint.style/rules/no-trailing-spaces",
},
},
],
},
type: "layout",
docs: {
description: "Disallow trailing whitespace at the end of lines",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-trailing-spaces",
},
fixable: "whitespace",
schema: [
{
type: "object",
properties: {
skipBlankLines: {
type: "boolean",
default: false,
},
ignoreComments: {
type: "boolean",
default: false,
},
},
additionalProperties: false,
},
],
messages: {
trailingSpace: "Trailing spaces not allowed.",
},
},
create(context) {
const sourceCode = context.sourceCode;
const BLANK_CLASS =
"[ \t\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u3000]",
SKIP_BLANK = `^${BLANK_CLASS}*$`,
NONBLANK = `${BLANK_CLASS}+$`;
const options = context.options[0] || {},
skipBlankLines = options.skipBlankLines || false,
ignoreComments = options.ignoreComments || false;
/**
* Report the error message
* @param {ASTNode} node node to report
* @param {SourceLocation} location range information
* @param {SourceRange} fixRange Range based on the whole program
* @returns {void}
*/
function report(node, location, fixRange) {
/*
* Passing node is a bit dirty, because message data will contain big
* text in `source`. But... who cares :) ?
* One more kludge will not make worse the bloody wizardry of this
* plugin.
*/
context.report({
node,
loc: location,
messageId: "trailingSpace",
fix(fixer) {
return fixer.removeRange(fixRange);
},
});
}
/**
* Given a list of comment nodes, return the line numbers for those comments.
* @param {Array} comments An array of comment nodes.
* @returns {number[]} An array of line numbers containing comments.
*/
function getCommentLineNumbers(comments) {
const lines = new Set();
comments.forEach(comment => {
const endLine =
comment.type === "Block"
? comment.loc.end.line - 1
: comment.loc.end.line;
for (let i = comment.loc.start.line; i <= endLine; i++) {
lines.add(i);
}
});
return lines;
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
Program: function checkTrailingSpaces(node) {
/*
* Let's hack. Since Espree does not return whitespace nodes,
* fetch the source code and do matching via regexps.
*/
const re = new RegExp(NONBLANK, "u"),
skipMatch = new RegExp(SKIP_BLANK, "u"),
lines = sourceCode.lines,
linebreaks = sourceCode
.getText()
.match(astUtils.createGlobalLinebreakMatcher()),
comments = sourceCode.getAllComments(),
commentLineNumbers = getCommentLineNumbers(comments);
let totalLength = 0;
for (let i = 0, ii = lines.length; i < ii; i++) {
const lineNumber = i + 1;
/*
* Always add linebreak length to line length to accommodate for line break (\n or \r\n)
* Because during the fix time they also reserve one spot in the array.
* Usually linebreak length is 2 for \r\n (CRLF) and 1 for \n (LF)
*/
const linebreakLength =
linebreaks && linebreaks[i] ? linebreaks[i].length : 1;
const lineLength = lines[i].length + linebreakLength;
const matches = re.exec(lines[i]);
if (matches) {
const location = {
start: {
line: lineNumber,
column: matches.index,
},
end: {
line: lineNumber,
column: lineLength - linebreakLength,
},
};
const rangeStart = totalLength + location.start.column;
const rangeEnd = totalLength + location.end.column;
const containingNode =
sourceCode.getNodeByRangeIndex(rangeStart);
if (
containingNode &&
containingNode.type === "TemplateElement" &&
rangeStart > containingNode.parent.range[0] &&
rangeEnd < containingNode.parent.range[1]
) {
totalLength += lineLength;
continue;
}
/*
* If the line has only whitespace, and skipBlankLines
* is true, don't report it
*/
if (skipBlankLines && skipMatch.test(lines[i])) {
totalLength += lineLength;
continue;
}
const fixRange = [rangeStart, rangeEnd];
if (
!ignoreComments ||
!commentLineNumbers.has(lineNumber)
) {
report(node, location, fixRange);
}
}
totalLength += lineLength;
}
},
};
},
};

View File

@@ -0,0 +1,9 @@
import defaultErrorMap from "./locales/en.js";
let overrideErrorMap = defaultErrorMap;
export { defaultErrorMap };
export function setErrorMap(map) {
overrideErrorMap = map;
}
export function getErrorMap() {
return overrideErrorMap;
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,sEAAsE;AAUtE,qFAAqF;AACrF,wBAAgB,OAAO,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,IAAI,UAAU,CAEnD;AAED,6CAA6C;AAC7C,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAEvC;AAED,uCAAuC;AACvC,wBAAgB,MAAM,CAAC,CAAC,EAAE,UAAU,GAAG,SAAS,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,CAI5E;AAED,gCAAgC;AAChC,wBAAgB,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,IAAI,CAKpC;AAED,gEAAgE;AAChE,wBAAgB,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE,aAAa,UAAO,GAAG,IAAI,CAGjE;AAED,kDAAkD;AAClD,wBAAgB,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,GAAG,IAAI,CAMrD;AAED,uEAAuE;AAEvE,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,iBAAiB,GAAG,UAAU,GACjE,WAAW,GAAG,UAAU,GAAG,WAAW,GAAG,UAAU,CAAC;AAEtD,iCAAiC;AACjC,wBAAgB,EAAE,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU,CAE9C;AAED,kCAAkC;AAClC,wBAAgB,GAAG,CAAC,GAAG,EAAE,UAAU,GAAG,WAAW,CAEhD;AAED,gEAAgE;AAChE,wBAAgB,KAAK,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,CAInD;AAED,oEAAoE;AACpE,wBAAgB,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,QAAQ,CAEpD;AAED,mEAAmE;AACnE,wBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAExD;AAED,iEAAiE;AACjE,wBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAExD;AAED,4EAA4E;AAC5E,eAAO,MAAM,IAAI,EAAE,OACkD,CAAC;AAEtE,yCAAyC;AACzC,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAO7C;AACD,0DAA0D;AAC1D,eAAO,MAAM,SAAS,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAET,CAAC;AAE/B,kBAAkB;AAClB,eAAO,MAAM,YAAY,EAAE,OAAO,SAAqB,CAAC;AACxD,yCAAyC;AACzC,wBAAgB,UAAU,CAAC,GAAG,EAAE,WAAW,GAAG,WAAW,CAKxD;AAED,eAAO,MAAM,UAAU,EAAE,CAAC,CAAC,EAAE,WAAW,KAAK,WAE/B,CAAC;AAYf;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAUpD;AAWD;;;GAGG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAkBlD;AAED;;;;GAIG;AACH,eAAO,MAAM,QAAQ,QAAa,OAAO,CAAC,IAAI,CAAO,CAAC;AAEtD,kEAAkE;AAClE,wBAAsB,SAAS,CAC7B,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,IAAI,GACtB,OAAO,CAAC,IAAI,CAAC,CAUf;AAMD;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAGnD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAErD;AAED,8EAA8E;AAC9E,MAAM,MAAM,KAAK,GAAG,MAAM,GAAG,UAAU,CAAC;AACxC;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,KAAK,GAAG,UAAU,CAI/C;AAED,iEAAiE;AACjE,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,UAAU,CAAC;AAC3C;;;GAGG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,QAAQ,GAAG,UAAU,CAI1D;AAED,2CAA2C;AAC3C,wBAAgB,WAAW,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,GAAG,UAAU,CAc/D;AAED,KAAK,QAAQ,GAAG,EAAE,CAAC;AACnB,wBAAgB,SAAS,CAAC,EAAE,SAAS,QAAQ,EAAE,EAAE,SAAS,QAAQ,EAChE,QAAQ,EAAE,EAAE,EACZ,IAAI,CAAC,EAAE,EAAE,GACR,EAAE,GAAG,EAAE,CAKT;AAED,sBAAsB;AACtB,MAAM,MAAM,KAAK,GAAG;IAClB,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CAAC;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,GAAG,CAAC;CACb,CAAC;AAEF,sDAAsD;AACtD,8BAAsB,IAAI,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC;IAC1C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,GAAG,IAAI;IAEjC,QAAQ,CAAC,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,IAAI;IAC1C,QAAQ,CAAC,MAAM,IAAI,UAAU;IAC7B;;;;OAIG;IACH,QAAQ,CAAC,OAAO,IAAI,IAAI;IACxB;;;;;;OAMG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC;IAE9B,QAAQ,CAAC,KAAK,IAAI,CAAC;CACpB;AAED;;;;;GAKG;AACH,MAAM,MAAM,OAAO,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,GAAG;IACjD,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAAC;IAC/B,OAAO,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU,CAAC;CACtC,CAAC;AAEF,oBAAoB;AACpB,MAAM,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC;AACpD,gCAAgC;AAChC,MAAM,MAAM,MAAM,GAAG,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC;AACxD,sBAAsB;AACtB,MAAM,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,WAAW,CAAC,CAAC;AAErD,8DAA8D;AAC9D,wBAAgB,YAAY,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EAC5C,QAAQ,EAAE,MAAM,IAAI,CAAC,CAAC,CAAC,GACtB;IACD,CAAC,GAAG,EAAE,KAAK,GAAG,UAAU,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC;CACnB,CAOA;AAED,wBAAgB,eAAe,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,EACjE,QAAQ,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,GAC9B;IACD,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC;IACnC,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;CAC3B,CAOA;AAED,wBAAgB,WAAW,CAAC,CAAC,SAAS,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,EAChE,QAAQ,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,GACjC;IACD,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC;IACnC,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAC9B,CAOA;AACD,eAAO,MAAM,eAAe,EAAE,OAAO,YAA2B,CAAC;AACjE,eAAO,MAAM,uBAAuB,EAAE,OAAO,eAAiC,CAAC;AAC/E,eAAO,MAAM,0BAA0B,EAAE,OAAO,WAAyB,CAAC;AAE1E,sFAAsF;AACtF,wBAAgB,WAAW,CAAC,WAAW,SAAK,GAAG,UAAU,CASxD"}

View File

@@ -0,0 +1,6 @@
import regenerator from "./regenerator.js";
import regeneratorAsyncIterator from "./regeneratorAsyncIterator.js";
function _regeneratorAsyncGen(r, e, t, o, n) {
return new regeneratorAsyncIterator(regenerator().w(r, e, t, o), n || Promise);
}
export { _regeneratorAsyncGen as default };

View File

@@ -0,0 +1,12 @@
'use strict'
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('node:os').hostname = function () { return 'abcdefghijklmnopqr' }
const pino = require('../../..')
const logger = pino(pino.destination({ sync: false }))
for (var i = 0; i < 1000; i++) {
logger.info('hello world')
}

View File

@@ -0,0 +1,6 @@
"use strict";
function _class_private_method_set() {
throw new TypeError("attempted to reassign private method");
}
exports._ = _class_private_method_set;

View File

@@ -0,0 +1,6 @@
function _type_of(obj) {
"@swc/helpers - typeof";
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
export { _type_of as _ };

View File

@@ -0,0 +1,275 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const adjacent_overload_signatures_1 = __importDefault(require("./adjacent-overload-signatures"));
const array_type_1 = __importDefault(require("./array-type"));
const await_thenable_1 = __importDefault(require("./await-thenable"));
const ban_ts_comment_1 = __importDefault(require("./ban-ts-comment"));
const ban_tslint_comment_1 = __importDefault(require("./ban-tslint-comment"));
const class_literal_property_style_1 = __importDefault(require("./class-literal-property-style"));
const class_methods_use_this_1 = __importDefault(require("./class-methods-use-this"));
const consistent_generic_constructors_1 = __importDefault(require("./consistent-generic-constructors"));
const consistent_indexed_object_style_1 = __importDefault(require("./consistent-indexed-object-style"));
const consistent_return_1 = __importDefault(require("./consistent-return"));
const consistent_type_assertions_1 = __importDefault(require("./consistent-type-assertions"));
const consistent_type_definitions_1 = __importDefault(require("./consistent-type-definitions"));
const consistent_type_exports_1 = __importDefault(require("./consistent-type-exports"));
const consistent_type_imports_1 = __importDefault(require("./consistent-type-imports"));
const default_param_last_1 = __importDefault(require("./default-param-last"));
const dot_notation_1 = __importDefault(require("./dot-notation"));
const explicit_function_return_type_1 = __importDefault(require("./explicit-function-return-type"));
const explicit_member_accessibility_1 = __importDefault(require("./explicit-member-accessibility"));
const explicit_module_boundary_types_1 = __importDefault(require("./explicit-module-boundary-types"));
const init_declarations_1 = __importDefault(require("./init-declarations"));
const max_params_1 = __importDefault(require("./max-params"));
const member_ordering_1 = __importDefault(require("./member-ordering"));
const method_signature_style_1 = __importDefault(require("./method-signature-style"));
const naming_convention_1 = __importDefault(require("./naming-convention"));
const no_array_constructor_1 = __importDefault(require("./no-array-constructor"));
const no_array_delete_1 = __importDefault(require("./no-array-delete"));
const no_base_to_string_1 = __importDefault(require("./no-base-to-string"));
const no_confusing_non_null_assertion_1 = __importDefault(require("./no-confusing-non-null-assertion"));
const no_confusing_void_expression_1 = __importDefault(require("./no-confusing-void-expression"));
const no_deprecated_1 = __importDefault(require("./no-deprecated"));
const no_dupe_class_members_1 = __importDefault(require("./no-dupe-class-members"));
const no_duplicate_enum_values_1 = __importDefault(require("./no-duplicate-enum-values"));
const no_duplicate_type_constituents_1 = __importDefault(require("./no-duplicate-type-constituents"));
const no_dynamic_delete_1 = __importDefault(require("./no-dynamic-delete"));
const no_empty_function_1 = __importDefault(require("./no-empty-function"));
const no_empty_interface_1 = __importDefault(require("./no-empty-interface"));
const no_empty_object_type_1 = __importDefault(require("./no-empty-object-type"));
const no_explicit_any_1 = __importDefault(require("./no-explicit-any"));
const no_extra_non_null_assertion_1 = __importDefault(require("./no-extra-non-null-assertion"));
const no_extraneous_class_1 = __importDefault(require("./no-extraneous-class"));
const no_floating_promises_1 = __importDefault(require("./no-floating-promises"));
const no_for_in_array_1 = __importDefault(require("./no-for-in-array"));
const no_implied_eval_1 = __importDefault(require("./no-implied-eval"));
const no_import_type_side_effects_1 = __importDefault(require("./no-import-type-side-effects"));
const no_inferrable_types_1 = __importDefault(require("./no-inferrable-types"));
const no_invalid_this_1 = __importDefault(require("./no-invalid-this"));
const no_invalid_void_type_1 = __importDefault(require("./no-invalid-void-type"));
const no_loop_func_1 = __importDefault(require("./no-loop-func"));
const no_loss_of_precision_1 = __importDefault(require("./no-loss-of-precision"));
const no_magic_numbers_1 = __importDefault(require("./no-magic-numbers"));
const no_meaningless_void_operator_1 = __importDefault(require("./no-meaningless-void-operator"));
const no_misused_new_1 = __importDefault(require("./no-misused-new"));
const no_misused_promises_1 = __importDefault(require("./no-misused-promises"));
const no_misused_spread_1 = __importDefault(require("./no-misused-spread"));
const no_mixed_enums_1 = __importDefault(require("./no-mixed-enums"));
const no_namespace_1 = __importDefault(require("./no-namespace"));
const no_non_null_asserted_nullish_coalescing_1 = __importDefault(require("./no-non-null-asserted-nullish-coalescing"));
const no_non_null_asserted_optional_chain_1 = __importDefault(require("./no-non-null-asserted-optional-chain"));
const no_non_null_assertion_1 = __importDefault(require("./no-non-null-assertion"));
const no_redeclare_1 = __importDefault(require("./no-redeclare"));
const no_redundant_type_constituents_1 = __importDefault(require("./no-redundant-type-constituents"));
const no_require_imports_1 = __importDefault(require("./no-require-imports"));
const no_restricted_imports_1 = __importDefault(require("./no-restricted-imports"));
const no_restricted_types_1 = __importDefault(require("./no-restricted-types"));
const no_shadow_1 = __importDefault(require("./no-shadow"));
const no_this_alias_1 = __importDefault(require("./no-this-alias"));
const no_type_alias_1 = __importDefault(require("./no-type-alias"));
const no_unnecessary_boolean_literal_compare_1 = __importDefault(require("./no-unnecessary-boolean-literal-compare"));
const no_unnecessary_condition_1 = __importDefault(require("./no-unnecessary-condition"));
const no_unnecessary_parameter_property_assignment_1 = __importDefault(require("./no-unnecessary-parameter-property-assignment"));
const no_unnecessary_qualifier_1 = __importDefault(require("./no-unnecessary-qualifier"));
const no_unnecessary_template_expression_1 = __importDefault(require("./no-unnecessary-template-expression"));
const no_unnecessary_type_arguments_1 = __importDefault(require("./no-unnecessary-type-arguments"));
const no_unnecessary_type_assertion_1 = __importDefault(require("./no-unnecessary-type-assertion"));
const no_unnecessary_type_constraint_1 = __importDefault(require("./no-unnecessary-type-constraint"));
const no_unnecessary_type_conversion_1 = __importDefault(require("./no-unnecessary-type-conversion"));
const no_unnecessary_type_parameters_1 = __importDefault(require("./no-unnecessary-type-parameters"));
const no_unsafe_argument_1 = __importDefault(require("./no-unsafe-argument"));
const no_unsafe_assignment_1 = __importDefault(require("./no-unsafe-assignment"));
const no_unsafe_call_1 = __importDefault(require("./no-unsafe-call"));
const no_unsafe_declaration_merging_1 = __importDefault(require("./no-unsafe-declaration-merging"));
const no_unsafe_enum_comparison_1 = __importDefault(require("./no-unsafe-enum-comparison"));
const no_unsafe_function_type_1 = __importDefault(require("./no-unsafe-function-type"));
const no_unsafe_member_access_1 = __importDefault(require("./no-unsafe-member-access"));
const no_unsafe_return_1 = __importDefault(require("./no-unsafe-return"));
const no_unsafe_type_assertion_1 = __importDefault(require("./no-unsafe-type-assertion"));
const no_unsafe_unary_minus_1 = __importDefault(require("./no-unsafe-unary-minus"));
const no_unused_expressions_1 = __importDefault(require("./no-unused-expressions"));
const no_unused_private_class_members_1 = __importDefault(require("./no-unused-private-class-members"));
const no_unused_vars_1 = __importDefault(require("./no-unused-vars"));
const no_use_before_define_1 = __importDefault(require("./no-use-before-define"));
const no_useless_constructor_1 = __importDefault(require("./no-useless-constructor"));
const no_useless_default_assignment_1 = __importDefault(require("./no-useless-default-assignment"));
const no_useless_empty_export_1 = __importDefault(require("./no-useless-empty-export"));
const no_var_requires_1 = __importDefault(require("./no-var-requires"));
const no_wrapper_object_types_1 = __importDefault(require("./no-wrapper-object-types"));
const non_nullable_type_assertion_style_1 = __importDefault(require("./non-nullable-type-assertion-style"));
const only_throw_error_1 = __importDefault(require("./only-throw-error"));
const parameter_properties_1 = __importDefault(require("./parameter-properties"));
const prefer_as_const_1 = __importDefault(require("./prefer-as-const"));
const prefer_destructuring_1 = __importDefault(require("./prefer-destructuring"));
const prefer_enum_initializers_1 = __importDefault(require("./prefer-enum-initializers"));
const prefer_find_1 = __importDefault(require("./prefer-find"));
const prefer_for_of_1 = __importDefault(require("./prefer-for-of"));
const prefer_function_type_1 = __importDefault(require("./prefer-function-type"));
const prefer_includes_1 = __importDefault(require("./prefer-includes"));
const prefer_literal_enum_member_1 = __importDefault(require("./prefer-literal-enum-member"));
const prefer_namespace_keyword_1 = __importDefault(require("./prefer-namespace-keyword"));
const prefer_nullish_coalescing_1 = __importDefault(require("./prefer-nullish-coalescing"));
const prefer_optional_chain_1 = __importDefault(require("./prefer-optional-chain"));
const prefer_promise_reject_errors_1 = __importDefault(require("./prefer-promise-reject-errors"));
const prefer_readonly_1 = __importDefault(require("./prefer-readonly"));
const prefer_readonly_parameter_types_1 = __importDefault(require("./prefer-readonly-parameter-types"));
const prefer_reduce_type_parameter_1 = __importDefault(require("./prefer-reduce-type-parameter"));
const prefer_regexp_exec_1 = __importDefault(require("./prefer-regexp-exec"));
const prefer_return_this_type_1 = __importDefault(require("./prefer-return-this-type"));
const prefer_string_starts_ends_with_1 = __importDefault(require("./prefer-string-starts-ends-with"));
const prefer_ts_expect_error_1 = __importDefault(require("./prefer-ts-expect-error"));
const promise_function_async_1 = __importDefault(require("./promise-function-async"));
const related_getter_setter_pairs_1 = __importDefault(require("./related-getter-setter-pairs"));
const require_array_sort_compare_1 = __importDefault(require("./require-array-sort-compare"));
const require_await_1 = __importDefault(require("./require-await"));
const restrict_plus_operands_1 = __importDefault(require("./restrict-plus-operands"));
const restrict_template_expressions_1 = __importDefault(require("./restrict-template-expressions"));
const return_await_1 = __importDefault(require("./return-await"));
const sort_type_constituents_1 = __importDefault(require("./sort-type-constituents"));
const strict_boolean_expressions_1 = __importDefault(require("./strict-boolean-expressions"));
const strict_void_return_1 = __importDefault(require("./strict-void-return"));
const switch_exhaustiveness_check_1 = __importDefault(require("./switch-exhaustiveness-check"));
const triple_slash_reference_1 = __importDefault(require("./triple-slash-reference"));
const typedef_1 = __importDefault(require("./typedef"));
const unbound_method_1 = __importDefault(require("./unbound-method"));
const unified_signatures_1 = __importDefault(require("./unified-signatures"));
const use_unknown_in_catch_callback_variable_1 = __importDefault(require("./use-unknown-in-catch-callback-variable"));
const rules = {
'adjacent-overload-signatures': adjacent_overload_signatures_1.default,
'array-type': array_type_1.default,
'await-thenable': await_thenable_1.default,
'ban-ts-comment': ban_ts_comment_1.default,
'ban-tslint-comment': ban_tslint_comment_1.default,
'class-literal-property-style': class_literal_property_style_1.default,
'class-methods-use-this': class_methods_use_this_1.default,
'consistent-generic-constructors': consistent_generic_constructors_1.default,
'consistent-indexed-object-style': consistent_indexed_object_style_1.default,
'consistent-return': consistent_return_1.default,
'consistent-type-assertions': consistent_type_assertions_1.default,
'consistent-type-definitions': consistent_type_definitions_1.default,
'consistent-type-exports': consistent_type_exports_1.default,
'consistent-type-imports': consistent_type_imports_1.default,
'default-param-last': default_param_last_1.default,
'dot-notation': dot_notation_1.default,
'explicit-function-return-type': explicit_function_return_type_1.default,
'explicit-member-accessibility': explicit_member_accessibility_1.default,
'explicit-module-boundary-types': explicit_module_boundary_types_1.default,
'init-declarations': init_declarations_1.default,
'max-params': max_params_1.default,
'member-ordering': member_ordering_1.default,
'method-signature-style': method_signature_style_1.default,
'naming-convention': naming_convention_1.default,
'no-array-constructor': no_array_constructor_1.default,
'no-array-delete': no_array_delete_1.default,
'no-base-to-string': no_base_to_string_1.default,
'no-confusing-non-null-assertion': no_confusing_non_null_assertion_1.default,
'no-confusing-void-expression': no_confusing_void_expression_1.default,
'no-deprecated': no_deprecated_1.default,
'no-dupe-class-members': no_dupe_class_members_1.default,
'no-duplicate-enum-values': no_duplicate_enum_values_1.default,
'no-duplicate-type-constituents': no_duplicate_type_constituents_1.default,
'no-dynamic-delete': no_dynamic_delete_1.default,
'no-empty-function': no_empty_function_1.default,
'no-empty-interface': no_empty_interface_1.default,
'no-empty-object-type': no_empty_object_type_1.default,
'no-explicit-any': no_explicit_any_1.default,
'no-extra-non-null-assertion': no_extra_non_null_assertion_1.default,
'no-extraneous-class': no_extraneous_class_1.default,
'no-floating-promises': no_floating_promises_1.default,
'no-for-in-array': no_for_in_array_1.default,
'no-implied-eval': no_implied_eval_1.default,
'no-import-type-side-effects': no_import_type_side_effects_1.default,
'no-inferrable-types': no_inferrable_types_1.default,
'no-invalid-this': no_invalid_this_1.default,
'no-invalid-void-type': no_invalid_void_type_1.default,
'no-loop-func': no_loop_func_1.default,
'no-loss-of-precision': no_loss_of_precision_1.default,
'no-magic-numbers': no_magic_numbers_1.default,
'no-meaningless-void-operator': no_meaningless_void_operator_1.default,
'no-misused-new': no_misused_new_1.default,
'no-misused-promises': no_misused_promises_1.default,
'no-misused-spread': no_misused_spread_1.default,
'no-mixed-enums': no_mixed_enums_1.default,
'no-namespace': no_namespace_1.default,
'no-non-null-asserted-nullish-coalescing': no_non_null_asserted_nullish_coalescing_1.default,
'no-non-null-asserted-optional-chain': no_non_null_asserted_optional_chain_1.default,
'no-non-null-assertion': no_non_null_assertion_1.default,
'no-redeclare': no_redeclare_1.default,
'no-redundant-type-constituents': no_redundant_type_constituents_1.default,
'no-require-imports': no_require_imports_1.default,
'no-restricted-imports': no_restricted_imports_1.default,
'no-restricted-types': no_restricted_types_1.default,
'no-shadow': no_shadow_1.default,
'no-this-alias': no_this_alias_1.default,
'no-type-alias': no_type_alias_1.default,
'no-unnecessary-boolean-literal-compare': no_unnecessary_boolean_literal_compare_1.default,
'no-unnecessary-condition': no_unnecessary_condition_1.default,
'no-unnecessary-parameter-property-assignment': no_unnecessary_parameter_property_assignment_1.default,
'no-unnecessary-qualifier': no_unnecessary_qualifier_1.default,
'no-unnecessary-template-expression': no_unnecessary_template_expression_1.default,
'no-unnecessary-type-arguments': no_unnecessary_type_arguments_1.default,
'no-unnecessary-type-assertion': no_unnecessary_type_assertion_1.default,
'no-unnecessary-type-constraint': no_unnecessary_type_constraint_1.default,
'no-unnecessary-type-conversion': no_unnecessary_type_conversion_1.default,
'no-unnecessary-type-parameters': no_unnecessary_type_parameters_1.default,
'no-unsafe-argument': no_unsafe_argument_1.default,
'no-unsafe-assignment': no_unsafe_assignment_1.default,
'no-unsafe-call': no_unsafe_call_1.default,
'no-unsafe-declaration-merging': no_unsafe_declaration_merging_1.default,
'no-unsafe-enum-comparison': no_unsafe_enum_comparison_1.default,
'no-unsafe-function-type': no_unsafe_function_type_1.default,
'no-unsafe-member-access': no_unsafe_member_access_1.default,
'no-unsafe-return': no_unsafe_return_1.default,
'no-unsafe-type-assertion': no_unsafe_type_assertion_1.default,
'no-unsafe-unary-minus': no_unsafe_unary_minus_1.default,
'no-unused-expressions': no_unused_expressions_1.default,
'no-unused-private-class-members': no_unused_private_class_members_1.default,
'no-unused-vars': no_unused_vars_1.default,
'no-use-before-define': no_use_before_define_1.default,
'no-useless-constructor': no_useless_constructor_1.default,
'no-useless-default-assignment': no_useless_default_assignment_1.default,
'no-useless-empty-export': no_useless_empty_export_1.default,
'no-var-requires': no_var_requires_1.default,
'no-wrapper-object-types': no_wrapper_object_types_1.default,
'non-nullable-type-assertion-style': non_nullable_type_assertion_style_1.default,
'only-throw-error': only_throw_error_1.default,
'parameter-properties': parameter_properties_1.default,
'prefer-as-const': prefer_as_const_1.default,
'prefer-destructuring': prefer_destructuring_1.default,
'prefer-enum-initializers': prefer_enum_initializers_1.default,
'prefer-find': prefer_find_1.default,
'prefer-for-of': prefer_for_of_1.default,
'prefer-function-type': prefer_function_type_1.default,
'prefer-includes': prefer_includes_1.default,
'prefer-literal-enum-member': prefer_literal_enum_member_1.default,
'prefer-namespace-keyword': prefer_namespace_keyword_1.default,
'prefer-nullish-coalescing': prefer_nullish_coalescing_1.default,
'prefer-optional-chain': prefer_optional_chain_1.default,
'prefer-promise-reject-errors': prefer_promise_reject_errors_1.default,
'prefer-readonly': prefer_readonly_1.default,
'prefer-readonly-parameter-types': prefer_readonly_parameter_types_1.default,
'prefer-reduce-type-parameter': prefer_reduce_type_parameter_1.default,
'prefer-regexp-exec': prefer_regexp_exec_1.default,
'prefer-return-this-type': prefer_return_this_type_1.default,
'prefer-string-starts-ends-with': prefer_string_starts_ends_with_1.default,
'prefer-ts-expect-error': prefer_ts_expect_error_1.default,
'promise-function-async': promise_function_async_1.default,
'related-getter-setter-pairs': related_getter_setter_pairs_1.default,
'require-array-sort-compare': require_array_sort_compare_1.default,
'require-await': require_await_1.default,
'restrict-plus-operands': restrict_plus_operands_1.default,
'restrict-template-expressions': restrict_template_expressions_1.default,
'return-await': return_await_1.default,
'sort-type-constituents': sort_type_constituents_1.default,
'strict-boolean-expressions': strict_boolean_expressions_1.default,
'strict-void-return': strict_void_return_1.default,
'switch-exhaustiveness-check': switch_exhaustiveness_check_1.default,
'triple-slash-reference': triple_slash_reference_1.default,
typedef: typedef_1.default,
'unbound-method': unbound_method_1.default,
'unified-signatures': unified_signatures_1.default,
'use-unknown-in-catch-callback-variable': use_unknown_in_catch_callback_variable_1.default,
};
module.exports = rules;

View File

@@ -0,0 +1,132 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'non-nullable-type-assertion-style',
meta: {
type: 'suggestion',
docs: {
description: 'Enforce non-null assertions over explicit type assertions',
recommended: 'stylistic',
requiresTypeChecking: true,
},
fixable: 'code',
messages: {
preferNonNullAssertion: 'Use a ! assertion to more succinctly remove null and undefined from the type.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const services = (0, util_1.getParserServices)(context);
const getTypesIfNotLoose = (node) => {
const type = services.getTypeAtLocation(node);
if (tsutils.isTypeFlagSet(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
return undefined;
}
return tsutils.unionConstituents(type);
};
const couldBeNullish = (type) => {
if (tsutils.isTypeFlagSet(type, ts.TypeFlags.TypeParameter)) {
const constraint = type.getConstraint();
return constraint == null || couldBeNullish(constraint);
}
if (tsutils.isUnionType(type)) {
for (const part of type.types) {
if (couldBeNullish(part)) {
return true;
}
}
return false;
}
return tsutils.isTypeFlagSet(type, ts.TypeFlags.Null | ts.TypeFlags.Undefined);
};
const sameTypeWithoutNullish = (assertedTypes, originalTypes) => {
const nonNullishOriginalTypes = originalTypes.filter(type => !tsutils.isTypeFlagSet(type, ts.TypeFlags.Null | ts.TypeFlags.Undefined));
if (nonNullishOriginalTypes.length === originalTypes.length) {
return false;
}
for (const assertedType of assertedTypes) {
if (couldBeNullish(assertedType) ||
!nonNullishOriginalTypes.includes(assertedType)) {
return false;
}
}
for (const originalType of nonNullishOriginalTypes) {
if (!assertedTypes.includes(originalType)) {
return false;
}
}
return true;
};
const isConstAssertion = (node) => {
return (node.typeAnnotation.type === utils_1.AST_NODE_TYPES.TSTypeReference &&
node.typeAnnotation.typeName.type === utils_1.AST_NODE_TYPES.Identifier &&
node.typeAnnotation.typeName.name === 'const');
};
return {
'TSAsExpression, TSTypeAssertion'(node) {
if (isConstAssertion(node)) {
return;
}
const originalTypes = getTypesIfNotLoose(node.expression);
if (!originalTypes) {
return;
}
const assertedTypes = getTypesIfNotLoose(node.typeAnnotation);
if (!assertedTypes) {
return;
}
if (sameTypeWithoutNullish(assertedTypes, originalTypes)) {
const expressionSourceCode = context.sourceCode.getText(node.expression);
const higherPrecedenceThanUnary = (0, util_1.getOperatorPrecedence)(services.esTreeNodeToTSNodeMap.get(node.expression).kind, ts.SyntaxKind.Unknown) > util_1.OperatorPrecedence.Unary;
context.report({
node,
messageId: 'preferNonNullAssertion',
fix(fixer) {
return fixer.replaceText(node, higherPrecedenceThanUnary
? `${expressionSourceCode}!`
: `(${expressionSourceCode})!`);
},
});
}
},
};
},
});

View File

@@ -0,0 +1,16 @@
import type { ParserServicesWithTypeInformation, TSESTree } from '@typescript-eslint/utils';
import * as ts from 'typescript';
/**
* Inspect a call expression to see if it's a call to an assertion function.
* If it is, return the node of the argument that is asserted.
*/
export declare function findTruthinessAssertedArgument(services: ParserServicesWithTypeInformation, node: TSESTree.CallExpression): TSESTree.Expression | undefined;
/**
* Inspect a call expression to see if it's a call to an assertion function.
* If it is, return the node of the argument that is asserted and other useful info.
*/
export declare function findTypeGuardAssertedArgument(services: ParserServicesWithTypeInformation, node: TSESTree.CallExpression): {
argument: TSESTree.Expression;
asserts: boolean;
type: ts.Type;
} | undefined;

View File

@@ -0,0 +1,49 @@
import type { $ZodRegistry } from "./registries.js";
import type * as schemas from "./schemas.js";
import { type Processor, type RegistryToJSONSchemaParams, type ToJSONSchemaParams, type ZodStandardJSONSchemaPayload } from "./to-json-schema.js";
export declare const stringProcessor: Processor<schemas.$ZodString>;
export declare const numberProcessor: Processor<schemas.$ZodNumber>;
export declare const booleanProcessor: Processor<schemas.$ZodBoolean>;
export declare const bigintProcessor: Processor<schemas.$ZodBigInt>;
export declare const symbolProcessor: Processor<schemas.$ZodSymbol>;
export declare const nullProcessor: Processor<schemas.$ZodNull>;
export declare const undefinedProcessor: Processor<schemas.$ZodUndefined>;
export declare const voidProcessor: Processor<schemas.$ZodVoid>;
export declare const neverProcessor: Processor<schemas.$ZodNever>;
export declare const anyProcessor: Processor<schemas.$ZodAny>;
export declare const unknownProcessor: Processor<schemas.$ZodUnknown>;
export declare const dateProcessor: Processor<schemas.$ZodDate>;
export declare const enumProcessor: Processor<schemas.$ZodEnum>;
export declare const literalProcessor: Processor<schemas.$ZodLiteral>;
export declare const nanProcessor: Processor<schemas.$ZodNaN>;
export declare const templateLiteralProcessor: Processor<schemas.$ZodTemplateLiteral>;
export declare const fileProcessor: Processor<schemas.$ZodFile>;
export declare const successProcessor: Processor<schemas.$ZodSuccess>;
export declare const customProcessor: Processor<schemas.$ZodCustom>;
export declare const functionProcessor: Processor<schemas.$ZodFunction>;
export declare const transformProcessor: Processor<schemas.$ZodTransform>;
export declare const mapProcessor: Processor<schemas.$ZodMap>;
export declare const setProcessor: Processor<schemas.$ZodSet>;
export declare const arrayProcessor: Processor<schemas.$ZodArray>;
export declare const objectProcessor: Processor<schemas.$ZodObject>;
export declare const unionProcessor: Processor<schemas.$ZodUnion>;
export declare const intersectionProcessor: Processor<schemas.$ZodIntersection>;
export declare const tupleProcessor: Processor<schemas.$ZodTuple>;
export declare const recordProcessor: Processor<schemas.$ZodRecord>;
export declare const nullableProcessor: Processor<schemas.$ZodNullable>;
export declare const nonoptionalProcessor: Processor<schemas.$ZodNonOptional>;
export declare const defaultProcessor: Processor<schemas.$ZodDefault>;
export declare const prefaultProcessor: Processor<schemas.$ZodPrefault>;
export declare const catchProcessor: Processor<schemas.$ZodCatch>;
export declare const pipeProcessor: Processor<schemas.$ZodPipe>;
export declare const readonlyProcessor: Processor<schemas.$ZodReadonly>;
export declare const promiseProcessor: Processor<schemas.$ZodPromise>;
export declare const optionalProcessor: Processor<schemas.$ZodOptional>;
export declare const lazyProcessor: Processor<schemas.$ZodLazy>;
export declare const allProcessors: Record<string, Processor<any>>;
export declare function toJSONSchema<T extends schemas.$ZodType>(schema: T, params?: ToJSONSchemaParams): ZodStandardJSONSchemaPayload<T>;
export declare function toJSONSchema(registry: $ZodRegistry<{
id?: string | undefined;
}>, params?: RegistryToJSONSchemaParams): {
schemas: Record<string, ZodStandardJSONSchemaPayload<schemas.$ZodType>>;
};

View File

@@ -0,0 +1,164 @@
import type { Primitive } from "./helpers/typeAliases.cjs";
import { util, type ZodParsedType } from "./helpers/util.cjs";
import type { TypeOf, ZodType } from "./index.cjs";
type allKeys<T> = T extends any ? keyof T : never;
export type inferFlattenedErrors<T extends ZodType<any, any, any>, U = string> = typeToFlattenedError<TypeOf<T>, U>;
export type typeToFlattenedError<T, U = string> = {
formErrors: U[];
fieldErrors: {
[P in allKeys<T>]?: U[];
};
};
export declare const ZodIssueCode: {
custom: "custom";
invalid_type: "invalid_type";
too_big: "too_big";
too_small: "too_small";
not_multiple_of: "not_multiple_of";
unrecognized_keys: "unrecognized_keys";
invalid_union: "invalid_union";
invalid_literal: "invalid_literal";
invalid_union_discriminator: "invalid_union_discriminator";
invalid_enum_value: "invalid_enum_value";
invalid_arguments: "invalid_arguments";
invalid_return_type: "invalid_return_type";
invalid_date: "invalid_date";
invalid_string: "invalid_string";
invalid_intersection_types: "invalid_intersection_types";
not_finite: "not_finite";
};
export type ZodIssueCode = keyof typeof ZodIssueCode;
export type ZodIssueBase = {
path: (string | number)[];
message?: string | undefined;
};
export interface ZodInvalidTypeIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_type;
expected: ZodParsedType;
received: ZodParsedType;
}
export interface ZodInvalidLiteralIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_literal;
expected: unknown;
received: unknown;
}
export interface ZodUnrecognizedKeysIssue extends ZodIssueBase {
code: typeof ZodIssueCode.unrecognized_keys;
keys: string[];
}
export interface ZodInvalidUnionIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_union;
unionErrors: ZodError[];
}
export interface ZodInvalidUnionDiscriminatorIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_union_discriminator;
options: Primitive[];
}
export interface ZodInvalidEnumValueIssue extends ZodIssueBase {
received: string | number;
code: typeof ZodIssueCode.invalid_enum_value;
options: (string | number)[];
}
export interface ZodInvalidArgumentsIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_arguments;
argumentsError: ZodError;
}
export interface ZodInvalidReturnTypeIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_return_type;
returnTypeError: ZodError;
}
export interface ZodInvalidDateIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_date;
}
export type StringValidation = "email" | "url" | "emoji" | "uuid" | "nanoid" | "regex" | "cuid" | "cuid2" | "ulid" | "datetime" | "date" | "time" | "duration" | "ip" | "cidr" | "base64" | "jwt" | "base64url" | {
includes: string;
position?: number | undefined;
} | {
startsWith: string;
} | {
endsWith: string;
};
export interface ZodInvalidStringIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_string;
validation: StringValidation;
}
export interface ZodTooSmallIssue extends ZodIssueBase {
code: typeof ZodIssueCode.too_small;
minimum: number | bigint;
inclusive: boolean;
exact?: boolean;
type: "array" | "string" | "number" | "set" | "date" | "bigint";
}
export interface ZodTooBigIssue extends ZodIssueBase {
code: typeof ZodIssueCode.too_big;
maximum: number | bigint;
inclusive: boolean;
exact?: boolean;
type: "array" | "string" | "number" | "set" | "date" | "bigint";
}
export interface ZodInvalidIntersectionTypesIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_intersection_types;
}
export interface ZodNotMultipleOfIssue extends ZodIssueBase {
code: typeof ZodIssueCode.not_multiple_of;
multipleOf: number | bigint;
}
export interface ZodNotFiniteIssue extends ZodIssueBase {
code: typeof ZodIssueCode.not_finite;
}
export interface ZodCustomIssue extends ZodIssueBase {
code: typeof ZodIssueCode.custom;
params?: {
[k: string]: any;
};
}
export type DenormalizedError = {
[k: string]: DenormalizedError | string[];
};
export type ZodIssueOptionalMessage = ZodInvalidTypeIssue | ZodInvalidLiteralIssue | ZodUnrecognizedKeysIssue | ZodInvalidUnionIssue | ZodInvalidUnionDiscriminatorIssue | ZodInvalidEnumValueIssue | ZodInvalidArgumentsIssue | ZodInvalidReturnTypeIssue | ZodInvalidDateIssue | ZodInvalidStringIssue | ZodTooSmallIssue | ZodTooBigIssue | ZodInvalidIntersectionTypesIssue | ZodNotMultipleOfIssue | ZodNotFiniteIssue | ZodCustomIssue;
export type ZodIssue = ZodIssueOptionalMessage & {
fatal?: boolean | undefined;
message: string;
};
export declare const quotelessJson: (obj: any) => string;
type recursiveZodFormattedError<T> = T extends [any, ...any[]] ? {
[K in keyof T]?: ZodFormattedError<T[K]>;
} : T extends any[] ? {
[k: number]: ZodFormattedError<T[number]>;
} : T extends object ? {
[K in keyof T]?: ZodFormattedError<T[K]>;
} : unknown;
export type ZodFormattedError<T, U = string> = {
_errors: U[];
} & recursiveZodFormattedError<NonNullable<T>>;
export type inferFormattedError<T extends ZodType<any, any, any>, U = string> = ZodFormattedError<TypeOf<T>, U>;
export declare class ZodError<T = any> extends Error {
issues: ZodIssue[];
get errors(): ZodIssue[];
constructor(issues: ZodIssue[]);
format(): ZodFormattedError<T>;
format<U>(mapper: (issue: ZodIssue) => U): ZodFormattedError<T, U>;
static create: (issues: ZodIssue[]) => ZodError<any>;
static assert(value: unknown): asserts value is ZodError;
toString(): string;
get message(): string;
get isEmpty(): boolean;
addIssue: (sub: ZodIssue) => void;
addIssues: (subs?: ZodIssue[]) => void;
flatten(): typeToFlattenedError<T>;
flatten<U>(mapper?: (issue: ZodIssue) => U): typeToFlattenedError<T, U>;
get formErrors(): typeToFlattenedError<T, string>;
}
type stripPath<T extends object> = T extends any ? util.OmitKeys<T, "path"> : never;
export type IssueData = stripPath<ZodIssueOptionalMessage> & {
path?: (string | number)[];
fatal?: boolean | undefined;
};
export type ErrorMapCtx = {
defaultError: string;
data: any;
};
export type ZodErrorMap = (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => {
message: string;
};
export {};

View File

@@ -0,0 +1,37 @@
/*! *****************************************************************************
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"/>
interface String {
/** Removes the trailing white space and line terminator characters from a string. */
trimEnd(): string;
/** Removes the leading white space and line terminator characters from a string. */
trimStart(): string;
/**
* Removes the leading white space and line terminator characters from a string.
* @deprecated A legacy feature for browser compatibility. Use `trimStart` instead
*/
trimLeft(): string;
/**
* Removes the trailing white space and line terminator characters from a string.
* @deprecated A legacy feature for browser compatibility. Use `trimEnd` instead
*/
trimRight(): string;
}

View File

@@ -0,0 +1,11 @@
"use strict";
module.exports = function (it) {
const { path, message } = it;
return `
Failed to read JSON file at ${path}:
${message}
`.trimStart();
};

View File

@@ -0,0 +1,243 @@
/**
* bn254, previously known as alt_bn_128, when it had 128-bit security.
Barbulescu-Duquesne 2017 shown it's weaker: just about 100 bits,
so the naming has been adjusted to its prime bit count:
https://hal.science/hal-01534101/file/main.pdf.
Compatible with EIP-196 and EIP-197.
There are huge compatibility issues in the ecosystem:
1. Different libraries call it in different ways: "bn254", "bn256", "alt_bn128", "bn128".
2. libff has bn128, but it's a different curve with different G2:
https://github.com/scipr-lab/libff/blob/a44f482e18b8ac04d034c193bd9d7df7817ad73f/libff/algebra/curves/bn128/bn128_init.cpp#L166-L169
3. halo2curves bn256 is also incompatible and returns different outputs
We don't implement Point methods toHex / toBytes.
To work around this limitation, has to initialize points on their own from BigInts.
Reason it's not implemented is because [there is no standard](https://github.com/privacy-scaling-explorations/halo2curves/issues/109).
Points of divergence:
- Endianness: LE vs BE (byte-swapped)
- Flags as first hex bits (similar to BLS) vs no-flags
- Imaginary part last in G2 vs first (c0, c1 vs c1, c0)
The goal of our implementation is to support "Ethereum" variant of the curve,
because it at least has specs:
- EIP196 (https://eips.ethereum.org/EIPS/eip-196) describes bn254 ECADD and ECMUL opcodes for EVM
- EIP197 (https://eips.ethereum.org/EIPS/eip-197) describes bn254 pairings
- It's hard: EIPs don't have proper tests. EIP-197 returns boolean output instead of Fp12
- The existing implementations are bad. Some are deprecated:
- https://github.com/paritytech/bn (old version)
- https://github.com/ewasm/ethereum-bn128.rs (uses paritytech/bn)
- https://github.com/zcash-hackworks/bn
- https://github.com/arkworks-rs/curves/blob/master/bn254/src/lib.rs
- Python implementations use different towers and produce different Fp12 outputs:
- https://github.com/ethereum/py_pairing
- https://github.com/ethereum/execution-specs/blob/master/src/ethereum/crypto/alt_bn128.py
- Points are encoded differently in different implementations
### Params
Seed (X): 4965661367192848881
Fr: (36x⁴+36x³+18x²+6x+1)
Fp: (36x⁴+36x³+24x²+6x+1)
(E / Fp ): Y² = X³+3
(Et / Fp²): Y² = X³+3/(u+9) (D-type twist)
Ate loop size: 6x+2
### Towers
- Fp²[u] = Fp/u²+1
- Fp⁶[v] = Fp²/v³-9-u
- Fp¹²[w] = Fp⁶/w²-v
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import {
bls,
type CurveFn as BLSCurveFn,
type PostPrecomputeFn,
type PostPrecomputePointAddFn,
} from './abstract/bls.ts';
import { Field, type IField } from './abstract/modular.ts';
import type { Fp, Fp12, Fp2, Fp6 } from './abstract/tower.ts';
import { psiFrobenius, tower12 } from './abstract/tower.ts';
import { type CurveFn, weierstrass, type WeierstrassOpts } from './abstract/weierstrass.ts';
import { bitLen, notImplemented } from './utils.ts';
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
const _6n = BigInt(6);
const BN_X = BigInt('4965661367192848881');
const BN_X_LEN = bitLen(BN_X);
const SIX_X_SQUARED = _6n * BN_X ** _2n;
const bn254_G1_CURVE: WeierstrassOpts<bigint> = {
p: BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47'),
n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'),
h: _1n,
a: _0n,
b: _3n,
Gx: _1n,
Gy: BigInt(2),
};
// r == n
// Finite field over r. It's for convenience and is not used in the code below.
export const bn254_Fr: IField<bigint> = Field(bn254_G1_CURVE.n);
// Fp2.div(Fp2.mul(Fp2.ONE, _3n), Fp2.NONRESIDUE)
const Fp2B = {
c0: BigInt('19485874751759354771024239261021720505790618469301721065564631296452457478373'),
c1: BigInt('266929791119991161246907387137283842545076965332900288569378510910307636690'),
};
const { Fp, Fp2, Fp6, Fp12 } = tower12({
ORDER: bn254_G1_CURVE.p,
X_LEN: BN_X_LEN,
FP2_NONRESIDUE: [BigInt(9), _1n],
Fp2mulByB: (num) => Fp2.mul(num, Fp2B),
Fp12finalExponentiate: (num) => {
const powMinusX = (num: Fp12) => Fp12.conjugate(Fp12._cyclotomicExp(num, BN_X));
const r0 = Fp12.mul(Fp12.conjugate(num), Fp12.inv(num));
const r = Fp12.mul(Fp12.frobeniusMap(r0, 2), r0);
const y1 = Fp12._cyclotomicSquare(powMinusX(r));
const y2 = Fp12.mul(Fp12._cyclotomicSquare(y1), y1);
const y4 = powMinusX(y2);
const y6 = powMinusX(Fp12._cyclotomicSquare(y4));
const y8 = Fp12.mul(Fp12.mul(Fp12.conjugate(y6), y4), Fp12.conjugate(y2));
const y9 = Fp12.mul(y8, y1);
return Fp12.mul(
Fp12.frobeniusMap(Fp12.mul(Fp12.conjugate(r), y9), 3),
Fp12.mul(
Fp12.frobeniusMap(y8, 2),
Fp12.mul(Fp12.frobeniusMap(y9, 1), Fp12.mul(Fp12.mul(y8, y4), r))
)
);
},
});
// END OF CURVE FIELDS
const { G2psi, psi } = psiFrobenius(Fp, Fp2, Fp2.NONRESIDUE);
/*
No hashToCurve for now (and signatures):
- RFC 9380 doesn't mention bn254 and doesn't provide test vectors
- Overall seems like nobody is using BLS signatures on top of bn254
- Seems like it can utilize SVDW, which is not implemented yet
*/
const htfDefaults = Object.freeze({
// DST: a domain separation tag defined in section 2.2.5
DST: 'BN254G2_XMD:SHA-256_SVDW_RO_',
encodeDST: 'BN254G2_XMD:SHA-256_SVDW_RO_',
p: Fp.ORDER,
m: 2,
k: 128,
expand: 'xmd',
hash: sha256,
});
export const _postPrecompute: PostPrecomputeFn = (
Rx: Fp2,
Ry: Fp2,
Rz: Fp2,
Qx: Fp2,
Qy: Fp2,
pointAdd: PostPrecomputePointAddFn
) => {
const q = psi(Qx, Qy);
({ Rx, Ry, Rz } = pointAdd(Rx, Ry, Rz, q[0], q[1]));
const q2 = psi(q[0], q[1]);
pointAdd(Rx, Ry, Rz, q2[0], Fp2.neg(q2[1]));
};
// cofactor: (36 * X^4) + (36 * X^3) + (30 * X^2) + 6*X + 1
const bn254_G2_CURVE: WeierstrassOpts<Fp2> = {
p: Fp2.ORDER,
n: bn254_G1_CURVE.n,
h: BigInt('0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d'),
a: Fp2.ZERO,
b: Fp2B,
Gx: Fp2.fromBigTuple([
BigInt('10857046999023057135944570762232829481370756359578518086990519993285655852781'),
BigInt('11559732032986387107991004021392285783925812861821192530917403151452391805634'),
]),
Gy: Fp2.fromBigTuple([
BigInt('8495653923123431417604973247489272438418190587263600148770280649306958101930'),
BigInt('4082367875863433681332203403145435568316851327593401208105741076214120093531'),
]),
};
/**
* bn254 (a.k.a. alt_bn128) pairing-friendly curve.
* Contains G1 / G2 operations and pairings.
*/
export const bn254: BLSCurveFn = bls({
// Fields
fields: { Fp, Fp2, Fp6, Fp12, Fr: bn254_Fr },
G1: {
...bn254_G1_CURVE,
Fp,
htfDefaults: { ...htfDefaults, m: 1, DST: 'BN254G2_XMD:SHA-256_SVDW_RO_' },
wrapPrivateKey: true,
allowInfinityPoint: true,
mapToCurve: notImplemented,
fromBytes: notImplemented,
toBytes: notImplemented,
ShortSignature: {
fromBytes: notImplemented,
fromHex: notImplemented,
toBytes: notImplemented,
toRawBytes: notImplemented,
toHex: notImplemented,
},
},
G2: {
...bn254_G2_CURVE,
Fp: Fp2,
hEff: BigInt('21888242871839275222246405745257275088844257914179612981679871602714643921549'),
htfDefaults: { ...htfDefaults },
wrapPrivateKey: true,
allowInfinityPoint: true,
isTorsionFree: (c, P) => P.multiplyUnsafe(SIX_X_SQUARED).equals(G2psi(c, P)), // [p]P = [6X^2]P
mapToCurve: notImplemented,
fromBytes: notImplemented,
toBytes: notImplemented,
Signature: {
fromBytes: notImplemented,
fromHex: notImplemented,
toBytes: notImplemented,
toRawBytes: notImplemented,
toHex: notImplemented,
},
},
params: {
ateLoopSize: BN_X * _6n + _2n,
r: bn254_Fr.ORDER,
xNegative: false,
twistType: 'divisive',
},
htfDefaults,
hash: sha256,
postPrecompute: _postPrecompute,
});
/**
* bn254 weierstrass curve with ECDSA.
* This is very rare and probably not used anywhere.
* Instead, you should use G1 / G2, defined above.
* @deprecated
*/
export const bn254_weierstrass: CurveFn = weierstrass({
a: BigInt(0),
b: BigInt(3),
Fp,
n: BigInt('21888242871839275222246405745257275088548364400416034343698204186575808495617'),
Gx: BigInt(1),
Gy: BigInt(2),
h: BigInt(1),
hash: sha256,
});

View File

@@ -0,0 +1,46 @@
"use strict";
function _async_iterator(iterable) {
var method, async, sync, retry = 2;
for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) {
if (async && null != (method = iterable[async])) return method.call(iterable);
if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable));
async = "@@asyncIterator", sync = "@@iterator";
}
throw new TypeError("Object is not async iterable");
}
function AsyncFromSyncIterator(s) {
function AsyncFromSyncIteratorContinuation(r) {
if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object."));
var done = r.done;
return Promise.resolve(r.value).then(function(value) {
return { value: value, done: done };
});
}
return AsyncFromSyncIterator = function(s) {
this.s = s, this.n = s.next;
},
AsyncFromSyncIterator.prototype = {
s: null,
n: null,
next: function() {
return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
},
return: function(value) {
var ret = this.s.return;
return void 0 === ret ? Promise.resolve({ value: value, done: !0 }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments));
},
throw: function(value) {
var thr = this.s.return;
return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments));
}
},
new AsyncFromSyncIterator(s);
}
exports._ = _async_iterator;

View File

@@ -0,0 +1 @@
{"version":3,"file":"readonly-uint8array.d.ts","sourceRoot":"","sources":["../../src/readonly-uint8array.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,kBAAmB,SAAQ,IAAI,CAAC,UAAU,EAAE,2BAA2B,CAAC;IACrF,QAAQ,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;CAChC;AAED,KAAK,2BAA2B,GAAG,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,KAAK,GAAG,MAAM,CAAC"}

View File

@@ -0,0 +1,39 @@
// @flow
export interface Targets {
android?: number;
chrome?: number;
edge?: number;
firefox?: number;
ie?: number;
ios_saf?: number;
opera?: number;
safari?: number;
samsung?: number;
}
declare export var Features: {|
Nesting: 1,
NotSelectorList: 2,
DirSelector: 4,
LangSelectorList: 8,
IsSelector: 16,
TextDecorationThicknessPercent: 32,
MediaIntervalSyntax: 64,
MediaRangeSyntax: 128,
CustomMediaQueries: 256,
ClampFunction: 512,
ColorFunction: 1024,
OklabColors: 2048,
LabColors: 4096,
P3Colors: 8192,
HexAlphaColors: 16384,
SpaceSeparatedColorNotation: 32768,
FontFamilySystemUi: 65536,
DoublePositionGradients: 131072,
VendorPrefixes: 262144,
LogicalProperties: 524288,
LightDark: 1048576,
Selectors: 31,
MediaQueries: 448,
Colors: 1113088,
|};

View File

@@ -0,0 +1,496 @@
/**
* @fileoverview Rule to enforce return statements in callbacks of array's methods
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
const { isAnySegmentReachable } = require("./utils/code-path-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;
const TARGET_METHODS =
/^(?:every|filter|find(?:Last)?(?:Index)?|flatMap|forEach|map|reduce(?:Right)?|some|sort|toSorted)$/u;
/**
* Checks a given node is a member access which has the specified name's
* property.
* @param {ASTNode} node A node to check.
* @returns {boolean} `true` if the node is a member access which has
* the specified name's property. The node may be a `(Chain|Member)Expression` node.
*/
function isTargetMethod(node) {
return astUtils.isSpecificMemberAccess(node, null, TARGET_METHODS);
}
/**
* Returns a human-legible description of an array method
* @param {string} arrayMethodName A method name to fully qualify
* @returns {string} the method name prefixed with `Array.` if it is a class method,
* or else `Array.prototype.` if it is an instance method.
*/
function fullMethodName(arrayMethodName) {
if (["from", "fromAsync", "of", "isArray"].includes(arrayMethodName)) {
return "Array.".concat(arrayMethodName);
}
return "Array.prototype.".concat(arrayMethodName);
}
/**
* Checks whether or not a given node is a function expression which is the
* callback of an array method, returning the method name.
* Generators are excluded. Async functions are allowed only for `Array.fromAsync`.
* @param {ASTNode} node A node to check. This is one of
* FunctionExpression or ArrowFunctionExpression.
* @returns {string} The method name if the node is a callback method,
* null otherwise.
*/
function getArrayMethodName(node) {
// Generators are not checked for any methods.
if (node.generator) {
return null;
}
let currentNode = node;
while (currentNode) {
const parent = currentNode.parent;
switch (parent.type) {
/*
* Looks up the destination. e.g.,
* foo.every(nativeFoo || function foo() { ... });
*/
case "LogicalExpression":
case "ConditionalExpression":
case "ChainExpression":
currentNode = parent;
break;
/*
* If the upper function is IIFE, checks the destination of the return value.
* e.g.
* foo.every((function() {
* // setup...
* return function callback() { ... };
* })());
*/
case "ReturnStatement": {
const func = astUtils.getUpperFunction(parent);
if (func === null || !astUtils.isCallee(func)) {
return null;
}
currentNode = func.parent;
break;
}
/*
* e.g.
* Array.from([], function() {});
* list.every(function() {});
*/
case "CallExpression":
if (!node.async) {
if (astUtils.isArrayFromMethod(parent.callee)) {
if (
parent.arguments.length >= 2 &&
parent.arguments[1] === currentNode
) {
return "from";
}
}
if (isTargetMethod(parent.callee)) {
if (
parent.arguments.length >= 1 &&
parent.arguments[0] === currentNode
) {
return astUtils.getStaticPropertyName(
parent.callee,
);
}
}
}
if (astUtils.isArrayFromAsyncMethod(parent.callee)) {
if (
parent.arguments.length >= 2 &&
parent.arguments[1] === currentNode
) {
return "fromAsync";
}
}
return null;
// Otherwise this node is not target.
default:
return null;
}
}
/* c8 ignore next */
return null;
}
/**
* Checks if the given node is a void expression.
* @param {ASTNode} node The node to check.
* @returns {boolean} - `true` if the node is a void expression
*/
function isExpressionVoid(node) {
return node.type === "UnaryExpression" && node.operator === "void";
}
/**
* Fixes the linting error by prepending "void " to the given node
* @param {Object} sourceCode context given by context.sourceCode
* @param {ASTNode} node The node to fix.
* @param {Object} fixer The fixer object provided by ESLint.
* @returns {Array<Object>} - An array of fix objects to apply to the node.
*/
function voidPrependFixer(sourceCode, node, fixer) {
const requiresParens =
// prepending `void ` will fail if the node has a lower precedence than void
astUtils.getPrecedence(node) <
astUtils.getPrecedence({
type: "UnaryExpression",
operator: "void",
}) &&
// check if there are parentheses around the node to avoid redundant parentheses
!astUtils.isParenthesised(sourceCode, node);
// avoid parentheses issues
const returnOrArrowToken = sourceCode.getTokenBefore(
node,
node.parent.type === "ArrowFunctionExpression"
? astUtils.isArrowToken
: // isReturnToken
token => token.type === "Keyword" && token.value === "return",
);
const firstToken = sourceCode.getTokenAfter(returnOrArrowToken);
const prependSpace =
// is return token, as => allows void to be adjacent
returnOrArrowToken.value === "return" &&
// If two tokens (return and "(") are adjacent
returnOrArrowToken.range[1] === firstToken.range[0];
return [
fixer.insertTextBefore(
firstToken,
`${prependSpace ? " " : ""}void ${requiresParens ? "(" : ""}`,
),
fixer.insertTextAfter(node, requiresParens ? ")" : ""),
];
}
/**
* Fixes the linting error by `wrapping {}` around the given node's body.
* @param {Object} sourceCode context given by context.sourceCode
* @param {ASTNode} node The node to fix.
* @param {Object} fixer The fixer object provided by ESLint.
* @returns {Array<Object>} - An array of fix objects to apply to the node.
*/
function curlyWrapFixer(sourceCode, node, fixer) {
const arrowToken = sourceCode.getTokenBefore(
node.body,
astUtils.isArrowToken,
);
const firstToken = sourceCode.getTokenAfter(arrowToken);
const lastToken = sourceCode.getLastToken(node);
return [
fixer.insertTextBefore(firstToken, "{"),
fixer.insertTextAfter(lastToken, "}"),
];
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
defaultOptions: [
{
allowImplicit: false,
checkForEach: false,
allowVoid: false,
},
],
docs: {
description:
"Enforce `return` statements in callbacks of array methods",
recommended: false,
url: "https://eslint.org/docs/latest/rules/array-callback-return",
},
hasSuggestions: true,
schema: [
{
type: "object",
properties: {
allowImplicit: {
type: "boolean",
},
checkForEach: {
type: "boolean",
},
allowVoid: {
type: "boolean",
},
},
additionalProperties: false,
},
],
messages: {
expectedAtEnd:
"{{arrayMethodName}}() expects a value to be returned at the end of {{name}}.",
expectedInside:
"{{arrayMethodName}}() expects a return value from {{name}}.",
expectedReturnValue:
"{{arrayMethodName}}() expects a return value from {{name}}.",
expectedNoReturnValue:
"{{arrayMethodName}}() expects no useless return value from {{name}}.",
wrapBraces: "Wrap the expression in `{}`.",
prependVoid: "Prepend `void` to the expression.",
},
},
create(context) {
const [options] = context.options;
const sourceCode = context.sourceCode;
let funcInfo = {
arrayMethodName: null,
upper: null,
codePath: null,
hasReturn: false,
shouldCheck: false,
node: null,
};
/**
* Checks whether or not the last code path segment is reachable.
* Then reports this function if the segment is reachable.
*
* If the last code path segment is reachable, there are paths which are not
* returned or thrown.
* @param {ASTNode} node A node to check.
* @returns {void}
*/
function checkLastSegment(node) {
if (!funcInfo.shouldCheck) {
return;
}
const messageAndSuggestions = { messageId: "", suggest: [] };
if (funcInfo.arrayMethodName === "forEach") {
if (
options.checkForEach &&
node.type === "ArrowFunctionExpression" &&
node.expression
) {
if (options.allowVoid) {
if (isExpressionVoid(node.body)) {
return;
}
messageAndSuggestions.messageId =
"expectedNoReturnValue";
messageAndSuggestions.suggest = [
{
messageId: "wrapBraces",
fix(fixer) {
return curlyWrapFixer(
sourceCode,
node,
fixer,
);
},
},
{
messageId: "prependVoid",
fix(fixer) {
return voidPrependFixer(
sourceCode,
node.body,
fixer,
);
},
},
];
} else {
messageAndSuggestions.messageId =
"expectedNoReturnValue";
messageAndSuggestions.suggest = [
{
messageId: "wrapBraces",
fix(fixer) {
return curlyWrapFixer(
sourceCode,
node,
fixer,
);
},
},
];
}
}
} else {
if (
node.body.type === "BlockStatement" &&
isAnySegmentReachable(funcInfo.currentSegments)
) {
messageAndSuggestions.messageId = funcInfo.hasReturn
? "expectedAtEnd"
: "expectedInside";
}
}
if (messageAndSuggestions.messageId) {
const name = astUtils.getFunctionNameWithKind(node);
context.report({
node,
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
messageId: messageAndSuggestions.messageId,
data: {
name,
arrayMethodName: fullMethodName(
funcInfo.arrayMethodName,
),
},
suggest:
messageAndSuggestions.suggest.length !== 0
? messageAndSuggestions.suggest
: null,
});
}
}
return {
// Stacks this function's information.
onCodePathStart(codePath, node) {
let methodName = null;
if (TARGET_NODE_TYPE.test(node.type)) {
methodName = getArrayMethodName(node);
}
funcInfo = {
arrayMethodName: methodName,
upper: funcInfo,
codePath,
hasReturn: false,
shouldCheck: !!methodName,
node,
currentSegments: new Set(),
};
},
// Pops this function's information.
onCodePathEnd() {
funcInfo = funcInfo.upper;
},
onUnreachableCodePathSegmentStart(segment) {
funcInfo.currentSegments.add(segment);
},
onUnreachableCodePathSegmentEnd(segment) {
funcInfo.currentSegments.delete(segment);
},
onCodePathSegmentStart(segment) {
funcInfo.currentSegments.add(segment);
},
onCodePathSegmentEnd(segment) {
funcInfo.currentSegments.delete(segment);
},
// Checks the return statement is valid.
ReturnStatement(node) {
if (!funcInfo.shouldCheck) {
return;
}
funcInfo.hasReturn = true;
const messageAndSuggestions = { messageId: "", suggest: [] };
if (funcInfo.arrayMethodName === "forEach") {
// if checkForEach: true, returning a value at any path inside a forEach is not allowed
if (options.checkForEach && node.argument) {
if (options.allowVoid) {
if (isExpressionVoid(node.argument)) {
return;
}
messageAndSuggestions.messageId =
"expectedNoReturnValue";
messageAndSuggestions.suggest = [
{
messageId: "prependVoid",
fix(fixer) {
return voidPrependFixer(
sourceCode,
node.argument,
fixer,
);
},
},
];
} else {
messageAndSuggestions.messageId =
"expectedNoReturnValue";
}
}
} else {
// if allowImplicit: false, should also check node.argument
if (!options.allowImplicit && !node.argument) {
messageAndSuggestions.messageId = "expectedReturnValue";
}
}
if (messageAndSuggestions.messageId) {
context.report({
node,
messageId: messageAndSuggestions.messageId,
data: {
name: astUtils.getFunctionNameWithKind(
funcInfo.node,
),
arrayMethodName: fullMethodName(
funcInfo.arrayMethodName,
),
},
suggest:
messageAndSuggestions.suggest.length !== 0
? messageAndSuggestions.suggest
: null,
});
}
},
// Reports a given function if the last path is reachable.
"FunctionExpression:exit": checkLastSegment,
"ArrowFunctionExpression:exit": checkLastSegment,
};
},
};

View File

@@ -0,0 +1,322 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const util_1 = require("../util");
var ComparisonType;
(function (ComparisonType) {
/** Do no assignment comparison */
ComparisonType[ComparisonType["None"] = 0] = "None";
/** Use the receiver's type for comparison */
ComparisonType[ComparisonType["Basic"] = 1] = "Basic";
/** Use the sender's contextual type for comparison */
ComparisonType[ComparisonType["Contextual"] = 2] = "Contextual";
})(ComparisonType || (ComparisonType = {}));
exports.default = (0, util_1.createRule)({
name: 'no-unsafe-assignment',
meta: {
type: 'problem',
docs: {
description: 'Disallow assigning a value with type `any` to variables and properties',
recommended: 'recommended',
requiresTypeChecking: true,
},
messages: {
anyAssignment: 'Unsafe assignment of an {{sender}} value.',
anyAssignmentThis: [
'Unsafe assignment of an {{sender}} value. `this` is typed as `any`.',
'You can try to fix this by turning on the `noImplicitThis` compiler option, or adding a `this` parameter to the function.',
].join('\n'),
unsafeArrayPattern: 'Unsafe array destructuring of an {{sender}} array value.',
unsafeArrayPatternFromTuple: 'Unsafe array destructuring of a tuple element with an {{sender}} value.',
unsafeArraySpread: 'Unsafe spread of an {{sender}} value in an array.',
unsafeAssignment: 'Unsafe assignment of type {{sender}} to a variable of type {{receiver}}.',
unsafeObjectPattern: 'Unsafe object destructuring of a property with an {{sender}} value.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const services = (0, util_1.getParserServices)(context);
const checker = services.program.getTypeChecker();
const compilerOptions = services.program.getCompilerOptions();
const isNoImplicitThis = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'noImplicitThis');
// returns true if the assignment reported
function checkArrayDestructureHelper(receiverNode, senderNode) {
if (receiverNode.type !== utils_1.AST_NODE_TYPES.ArrayPattern) {
return false;
}
const senderTsNode = services.esTreeNodeToTSNodeMap.get(senderNode);
const senderType = services.getTypeAtLocation(senderNode);
return checkArrayDestructure(receiverNode, senderType, senderTsNode);
}
// returns true if the assignment reported
function checkArrayDestructure(receiverNode, senderType, senderNode) {
// any array
// const [x] = ([] as any[]);
if ((0, util_1.isTypeAnyArrayType)(senderType, checker)) {
context.report({
node: receiverNode,
messageId: 'unsafeArrayPattern',
data: createData(senderType),
});
return false;
}
if (!checker.isTupleType(senderType)) {
return true;
}
const tupleElements = checker.getTypeArguments(senderType);
// tuple with any
// const [x] = [1 as any];
let didReport = false;
for (let receiverIndex = 0; receiverIndex < receiverNode.elements.length; receiverIndex += 1) {
const receiverElement = receiverNode.elements[receiverIndex];
if (!receiverElement) {
continue;
}
if (receiverElement.type === utils_1.AST_NODE_TYPES.RestElement) {
// don't handle rests as they're not a 1:1 assignment
continue;
}
const senderType = tupleElements[receiverIndex];
if (!senderType) {
continue;
}
// check for the any type first so we can handle [[[x]]] = [any]
if ((0, util_1.isTypeAnyType)(senderType)) {
context.report({
node: receiverElement,
messageId: 'unsafeArrayPatternFromTuple',
data: createData(senderType),
});
// we want to report on every invalid element in the tuple
didReport = true;
}
else if (receiverElement.type === utils_1.AST_NODE_TYPES.ArrayPattern) {
didReport = checkArrayDestructure(receiverElement, senderType, senderNode);
}
else if (receiverElement.type === utils_1.AST_NODE_TYPES.ObjectPattern) {
didReport = checkObjectDestructure(receiverElement, senderType, senderNode);
}
}
return didReport;
}
// returns true if the assignment reported
function checkObjectDestructureHelper(receiverNode, senderNode) {
if (receiverNode.type !== utils_1.AST_NODE_TYPES.ObjectPattern) {
return false;
}
const senderTsNode = services.esTreeNodeToTSNodeMap.get(senderNode);
const senderType = services.getTypeAtLocation(senderNode);
return checkObjectDestructure(receiverNode, senderType, senderTsNode);
}
// returns true if the assignment reported
function checkObjectDestructure(receiverNode, senderType, senderNode) {
const properties = new Map(senderType
.getProperties()
.map(property => [
property.getName(),
checker.getTypeOfSymbolAtLocation(property, senderNode),
]));
let didReport = false;
for (const receiverProperty of receiverNode.properties) {
if (receiverProperty.type === utils_1.AST_NODE_TYPES.RestElement) {
// don't bother checking rest
continue;
}
let key;
if (!receiverProperty.computed) {
key =
receiverProperty.key.type === utils_1.AST_NODE_TYPES.Identifier
? receiverProperty.key.name
: String(receiverProperty.key.value);
}
else if (receiverProperty.key.type === utils_1.AST_NODE_TYPES.Literal) {
key = String(receiverProperty.key.value);
}
else if (receiverProperty.key.type === utils_1.AST_NODE_TYPES.TemplateLiteral &&
receiverProperty.key.quasis.length === 1) {
const cooked = (0, util_1.nullThrows)(receiverProperty.key.quasis[0].value.cooked, 'cooked can only be null inside a TaggedTemplateExpression, which is not possible here');
key = cooked;
}
else {
// can't figure out the name, so skip it
continue;
}
const senderType = properties.get(key);
if (!senderType) {
continue;
}
// check for the any type first so we can handle {x: {y: z}} = {x: any}
if ((0, util_1.isTypeAnyType)(senderType)) {
context.report({
node: receiverProperty.value,
messageId: 'unsafeObjectPattern',
data: createData(senderType),
});
didReport = true;
}
else if (receiverProperty.value.type === utils_1.AST_NODE_TYPES.ArrayPattern) {
didReport = checkArrayDestructure(receiverProperty.value, senderType, senderNode);
}
else if (receiverProperty.value.type === utils_1.AST_NODE_TYPES.ObjectPattern) {
didReport = checkObjectDestructure(receiverProperty.value, senderType, senderNode);
}
}
return didReport;
}
// returns true if the assignment reported
function checkAssignment(receiverNode, senderNode, reportingNode, comparisonType) {
const receiverTsNode = services.esTreeNodeToTSNodeMap.get(receiverNode);
const receiverType = comparisonType === ComparisonType.Contextual
? ((0, util_1.getContextualType)(checker, receiverTsNode) ??
services.getTypeAtLocation(receiverNode))
: services.getTypeAtLocation(receiverNode);
const senderType = services.getTypeAtLocation(senderNode);
if ((0, util_1.isTypeAnyType)(senderType)) {
// handle cases when we assign any ==> unknown.
if ((0, util_1.isTypeUnknownType)(receiverType)) {
return false;
}
let messageId = 'anyAssignment';
if (!isNoImplicitThis) {
// `var foo = this`
const thisExpression = (0, util_1.getThisExpression)(senderNode);
if (thisExpression &&
(0, util_1.isTypeAnyType)((0, util_1.getConstrainedTypeAtLocation)(services, thisExpression))) {
messageId = 'anyAssignmentThis';
}
}
context.report({
node: reportingNode,
messageId,
data: createData(senderType),
});
return true;
}
if (comparisonType === ComparisonType.None) {
return false;
}
const result = (0, util_1.isUnsafeAssignment)(senderType, receiverType, checker, senderNode);
if (!result) {
return false;
}
const { receiver, sender } = result;
context.report({
node: reportingNode,
messageId: 'unsafeAssignment',
data: createData(sender, receiver),
});
return true;
}
function getComparisonType(typeAnnotation) {
return typeAnnotation
? // if there's a type annotation, we can do a comparison
ComparisonType.Basic
: // no type annotation means the variable's type will just be inferred, thus equal
ComparisonType.None;
}
function createData(senderType, receiverType) {
if (receiverType) {
return {
receiver: `\`${checker.typeToString(receiverType)}\``,
sender: `\`${checker.typeToString(senderType)}\``,
};
}
return {
sender: tsutils.isIntrinsicErrorType(senderType)
? 'error typed'
: '`any`',
};
}
return {
'AccessorProperty[value != null]'(node) {
checkAssignment(node.key, node.value, node, getComparisonType(node.typeAnnotation));
},
'AssignmentExpression[operator = "="], AssignmentPattern'(node) {
let didReport = checkAssignment(node.left, node.right, node,
// the variable already has some form of a type to compare against
ComparisonType.Basic);
if (!didReport) {
didReport = checkArrayDestructureHelper(node.left, node.right);
}
if (!didReport) {
checkObjectDestructureHelper(node.left, node.right);
}
},
'PropertyDefinition[value != null]'(node) {
checkAssignment(node.key, node.value, node, getComparisonType(node.typeAnnotation));
},
'VariableDeclarator[init != null]'(node) {
const init = (0, util_1.nullThrows)(node.init, util_1.NullThrowsReasons.MissingToken(node.type, 'init'));
let didReport = checkAssignment(node.id, init, node, getComparisonType(node.id.typeAnnotation));
if (!didReport) {
didReport = checkArrayDestructureHelper(node.id, init);
}
if (!didReport) {
checkObjectDestructureHelper(node.id, init);
}
},
// object pattern props are checked via assignments
':not(ObjectPattern) > Property'(node) {
if (node.value.type === utils_1.AST_NODE_TYPES.AssignmentPattern ||
node.value.type === utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression) {
// handled by other selector
return;
}
checkAssignment(node.key, node.value, node, ComparisonType.Contextual);
},
'ArrayExpression > SpreadElement'(node) {
const restType = services.getTypeAtLocation(node.argument);
if ((0, util_1.isTypeAnyType)(restType) || (0, util_1.isTypeAnyArrayType)(restType, checker)) {
context.report({
node,
messageId: 'unsafeArraySpread',
data: createData(restType),
});
}
},
'JSXAttribute[value != null]'(node) {
const value = (0, util_1.nullThrows)(node.value, util_1.NullThrowsReasons.MissingToken(node.type, 'value'));
if (value.type !== utils_1.AST_NODE_TYPES.JSXExpressionContainer ||
value.expression.type === utils_1.AST_NODE_TYPES.JSXEmptyExpression) {
return;
}
checkAssignment(node.name, value.expression, value.expression, ComparisonType.Contextual);
},
};
},
});

View File

@@ -0,0 +1,26 @@
import { _ as _construct } from "./_construct.js";
import { _ as _get_prototype_of } from "./_get_prototype_of.js";
import { _ as _is_native_function } from "./_is_native_function.js";
import { _ as _set_prototype_of } from "./_set_prototype_of.js";
function _wrap_native_super(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
_wrap_native_super = function(Class) {
if (Class === null || !_is_native_function(Class)) return Class;
if (typeof Class !== "function") throw new TypeError("Super expression must either be null or a function");
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct(Class, arguments, _get_prototype_of(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } });
return _set_prototype_of(Wrapper, Class);
};
return _wrap_native_super(Class);
}
export { _wrap_native_super as _ };

View File

@@ -0,0 +1,43 @@
import { URL, UrlObject } from 'node:url'
import { Duplex } from 'node:stream'
import Dispatcher from './dispatcher'
/** Performs an HTTP request. */
declare function request<TOpaque = null> (
url: string | URL | UrlObject,
options?: { dispatcher?: Dispatcher } & Omit<Dispatcher.RequestOptions<TOpaque>, 'origin' | 'path' | 'method'> & Partial<Pick<Dispatcher.RequestOptions, 'method'>>,
): Promise<Dispatcher.ResponseData<TOpaque>>
/** A faster version of `request`. */
declare function stream<TOpaque = null> (
url: string | URL | UrlObject,
options: { dispatcher?: Dispatcher } & Omit<Dispatcher.RequestOptions<TOpaque>, 'origin' | 'path'>,
factory: Dispatcher.StreamFactory<TOpaque>
): Promise<Dispatcher.StreamData<TOpaque>>
/** For easy use with `stream.pipeline`. */
declare function pipeline<TOpaque = null> (
url: string | URL | UrlObject,
options: { dispatcher?: Dispatcher } & Omit<Dispatcher.PipelineOptions<TOpaque>, 'origin' | 'path'>,
handler: Dispatcher.PipelineHandler<TOpaque>
): Duplex
/** Starts two-way communications with the requested resource. */
declare function connect<TOpaque = null> (
url: string | URL | UrlObject,
options?: { dispatcher?: Dispatcher } & Omit<Dispatcher.ConnectOptions<TOpaque>, 'origin' | 'path'>
): Promise<Dispatcher.ConnectData<TOpaque>>
/** Upgrade to a different protocol. */
declare function upgrade (
url: string | URL | UrlObject,
options?: { dispatcher?: Dispatcher } & Omit<Dispatcher.UpgradeOptions, 'origin' | 'path'>
): Promise<Dispatcher.UpgradeData>
export {
request,
stream,
pipeline,
connect,
upgrade
}

View File

@@ -0,0 +1,18 @@
"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.es2020_symbol_wellknown = void 0;
const base_config_1 = require("./base-config");
const es2015_iterable_1 = require("./es2015.iterable");
const es2015_symbol_1 = require("./es2015.symbol");
exports.es2020_symbol_wellknown = {
libs: [es2015_iterable_1.es2015_iterable, es2015_symbol_1.es2015_symbol],
variables: [
['SymbolConstructor', base_config_1.TYPE],
['RegExpStringIterator', base_config_1.TYPE],
['RegExp', base_config_1.TYPE],
],
};

View File

@@ -0,0 +1,176 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
function getRussianPlural(count: number, one: string, few: string, many: string): string {
const absCount = Math.abs(count);
const lastDigit = absCount % 10;
const lastTwoDigits = absCount % 100;
if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
return many;
}
if (lastDigit === 1) {
return one;
}
if (lastDigit >= 2 && lastDigit <= 4) {
return few;
}
return many;
}
interface RussianSizable {
unit: {
one: string;
few: string;
many: string;
};
verb: string;
}
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, RussianSizable> = {
string: {
unit: {
one: "символ",
few: "символа",
many: "символов",
},
verb: "иметь",
},
file: {
unit: {
one: "байт",
few: "байта",
many: "байт",
},
verb: "иметь",
},
array: {
unit: {
one: "элемент",
few: "элемента",
many: "элементов",
},
verb: "иметь",
},
set: {
unit: {
one: "элемент",
few: "элемента",
many: "элементов",
},
verb: "иметь",
},
};
function getSizing(origin: string): RussianSizable | null {
return Sizable[origin] ?? null;
}
const FormatDictionary: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "ввод",
email: "email адрес",
url: "URL",
emoji: "эмодзи",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO дата и время",
date: "ISO дата",
time: "ISO время",
duration: "ISO длительность",
ipv4: "IPv4 адрес",
ipv6: "IPv6 адрес",
cidrv4: "IPv4 диапазон",
cidrv6: "IPv6 диапазон",
base64: "строка в формате base64",
base64url: "строка в формате base64url",
json_string: "JSON строка",
e164: "номер E.164",
jwt: "JWT",
template_literal: "ввод",
};
const TypeDictionary: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
} = {
nan: "NaN",
number: "число",
array: "массив",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `Неверный ввод: ожидалось instanceof ${issue.expected}, получено ${received}`;
}
return `Неверный ввод: ожидалось ${expected}, получено ${received}`;
}
case "invalid_value":
if (issue.values.length === 1) return `Неверный ввод: ожидалось ${util.stringifyPrimitive(issue.values[0])}`;
return `Неверный вариант: ожидалось одно из ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing) {
const maxValue = Number(issue.maximum);
const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
return `Слишком большое значение: ожидалось, что ${issue.origin ?? "значение"} будет иметь ${adj}${issue.maximum.toString()} ${unit}`;
}
return `Слишком большое значение: ожидалось, что ${issue.origin ?? "значение"} будет ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
const minValue = Number(issue.minimum);
const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет иметь ${adj}${issue.minimum.toString()} ${unit}`;
}
return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with") return `Неверная строка: должна начинаться с "${_issue.prefix}"`;
if (_issue.format === "ends_with") return `Неверная строка: должна заканчиваться на "${_issue.suffix}"`;
if (_issue.format === "includes") return `Неверная строка: должна содержать "${_issue.includes}"`;
if (_issue.format === "regex") return `Неверная строка: должна соответствовать шаблону ${_issue.pattern}`;
return `Неверный ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Неверное число: должно быть кратным ${issue.divisor}`;
case "unrecognized_keys":
return `Нераспознанн${issue.keys.length > 1 ? "ые" : "ый"} ключ${issue.keys.length > 1 ? "и" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Неверный ключ в ${issue.origin}`;
case "invalid_union":
return "Неверные входные данные";
case "invalid_element":
return `Неверное значение в ${issue.origin}`;
default:
return `Неверные входные данные`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,171 @@
### Esrecurse [![Build Status](https://travis-ci.org/estools/esrecurse.svg?branch=master)](https://travis-ci.org/estools/esrecurse)
Esrecurse ([esrecurse](https://github.com/estools/esrecurse)) is
[ECMAScript](https://www.ecma-international.org/publications/standards/Ecma-262.htm)
recursive traversing functionality.
### Example Usage
The following code will output all variables declared at the root of a file.
```javascript
esrecurse.visit(ast, {
XXXStatement: function (node) {
this.visit(node.left);
// do something...
this.visit(node.right);
}
});
```
We can use `Visitor` instance.
```javascript
var visitor = new esrecurse.Visitor({
XXXStatement: function (node) {
this.visit(node.left);
// do something...
this.visit(node.right);
}
});
visitor.visit(ast);
```
We can inherit `Visitor` instance easily.
```javascript
class Derived extends esrecurse.Visitor {
constructor()
{
super(null);
}
XXXStatement(node) {
}
}
```
```javascript
function DerivedVisitor() {
esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */);
}
util.inherits(DerivedVisitor, esrecurse.Visitor);
DerivedVisitor.prototype.XXXStatement = function (node) {
this.visit(node.left);
// do something...
this.visit(node.right);
};
```
And you can invoke default visiting operation inside custom visit operation.
```javascript
function DerivedVisitor() {
esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */);
}
util.inherits(DerivedVisitor, esrecurse.Visitor);
DerivedVisitor.prototype.XXXStatement = function (node) {
// do something...
this.visitChildren(node);
};
```
The `childVisitorKeys` option does customize the behaviour of `this.visitChildren(node)`.
We can use user-defined node types.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
esrecurse.visit(
ast,
{
Literal: function (node) {
// do something...
}
},
{
// Extending the existing traversing rules.
childVisitorKeys: {
// TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ]
TestExpression: ['argument']
}
}
);
```
We can use the `fallback` option as well.
If the `fallback` option is `"iteration"`, `esrecurse` would visit all enumerable properties of unknown nodes.
Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`).
```javascript
esrecurse.visit(
ast,
{
Literal: function (node) {
// do something...
}
},
{
fallback: 'iteration'
}
);
```
If the `fallback` option is a function, `esrecurse` calls this function to determine the enumerable properties of unknown nodes.
Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`).
```javascript
esrecurse.visit(
ast,
{
Literal: function (node) {
// do something...
}
},
{
fallback: function (node) {
return Object.keys(node).filter(function(key) {
return key !== 'argument'
});
}
}
);
```
### License
Copyright (C) 2014 [Yusuke Suzuki](https://github.com/Constellation)
(twitter: [@Constellation](https://twitter.com/Constellation)) and other contributors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,191 @@
import _typeof from "./typeof.js";
import setFunctionName from "./setFunctionName.js";
import toPropertyKey from "./toPropertyKey.js";
function applyDecs2203RFactory() {
function createAddInitializerMethod(e, t) {
return function (r) {
!function (e) {
if (e.v) throw Error("attempted to call addInitializer after decoration was finished");
}(t), assertCallable(r, "An initializer"), e.push(r);
};
}
function memberDec(e, t, r, n, a, i, o, s) {
var c;
switch (a) {
case 1:
c = "accessor";
break;
case 2:
c = "method";
break;
case 3:
c = "getter";
break;
case 4:
c = "setter";
break;
default:
c = "field";
}
var l,
u,
f = {
kind: c,
name: o ? "#" + t : toPropertyKey(t),
"static": i,
"private": o
},
p = {
v: !1
};
0 !== a && (f.addInitializer = createAddInitializerMethod(n, p)), 0 === a ? o ? (l = r.get, u = r.set) : (l = function l() {
return this[t];
}, u = function u(e) {
this[t] = e;
}) : 2 === a ? l = function l() {
return r.value;
} : (1 !== a && 3 !== a || (l = function l() {
return r.get.call(this);
}), 1 !== a && 4 !== a || (u = function u(e) {
r.set.call(this, e);
})), f.access = l && u ? {
get: l,
set: u
} : l ? {
get: l
} : {
set: u
};
try {
return e(s, f);
} finally {
p.v = !0;
}
}
function assertCallable(e, t) {
if ("function" != typeof e) throw new TypeError(t + " must be a function");
}
function assertValidReturnValue(e, t) {
var r = _typeof(t);
if (1 === e) {
if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init");
} else if ("function" !== r) throw new TypeError((0 === e ? "field" : 10 === e ? "class" : "method") + " decorators must return a function or void 0");
}
function applyMemberDec(e, t, r, n, a, i, o, s) {
var c,
l,
u,
f,
p,
d,
h,
v = r[0];
if (o ? (0 === a || 1 === a ? (c = {
get: r[3],
set: r[4]
}, u = "get") : 3 === a ? (c = {
get: r[3]
}, u = "get") : 4 === a ? (c = {
set: r[3]
}, u = "set") : c = {
value: r[3]
}, 0 !== a && (1 === a && setFunctionName(r[4], "#" + n, "set"), setFunctionName(r[3], "#" + n, u))) : 0 !== a && (c = Object.getOwnPropertyDescriptor(t, n)), 1 === a ? f = {
get: c.get,
set: c.set
} : 2 === a ? f = c.value : 3 === a ? f = c.get : 4 === a && (f = c.set), "function" == typeof v) void 0 !== (p = memberDec(v, n, c, s, a, i, o, f)) && (assertValidReturnValue(a, p), 0 === a ? l = p : 1 === a ? (l = p.init, d = p.get || f.get, h = p.set || f.set, f = {
get: d,
set: h
}) : f = p);else for (var g = v.length - 1; g >= 0; g--) {
var y;
void 0 !== (p = memberDec(v[g], n, c, s, a, i, o, f)) && (assertValidReturnValue(a, p), 0 === a ? y = p : 1 === a ? (y = p.init, d = p.get || f.get, h = p.set || f.set, f = {
get: d,
set: h
}) : f = p, void 0 !== y && (void 0 === l ? l = y : "function" == typeof l ? l = [l, y] : l.push(y)));
}
if (0 === a || 1 === a) {
if (void 0 === l) l = function l(e, t) {
return t;
};else if ("function" != typeof l) {
var m = l;
l = function l(e, t) {
for (var r = t, n = 0; n < m.length; n++) r = m[n].call(e, r);
return r;
};
} else {
var b = l;
l = function l(e, t) {
return b.call(e, t);
};
}
e.push(l);
}
0 !== a && (1 === a ? (c.get = f.get, c.set = f.set) : 2 === a ? c.value = f : 3 === a ? c.get = f : 4 === a && (c.set = f), o ? 1 === a ? (e.push(function (e, t) {
return f.get.call(e, t);
}), e.push(function (e, t) {
return f.set.call(e, t);
})) : 2 === a ? e.push(f) : e.push(function (e, t) {
return f.call(e, t);
}) : Object.defineProperty(t, n, c));
}
function applyMemberDecs(e, t) {
for (var r, n, a = [], i = new Map(), o = new Map(), s = 0; s < t.length; s++) {
var c = t[s];
if (Array.isArray(c)) {
var l,
u,
f = c[1],
p = c[2],
d = c.length > 3,
h = f >= 5;
if (h ? (l = e, 0 != (f -= 5) && (u = n = n || [])) : (l = e.prototype, 0 !== f && (u = r = r || [])), 0 !== f && !d) {
var v = h ? o : i,
g = v.get(p) || 0;
if (!0 === g || 3 === g && 4 !== f || 4 === g && 3 !== f) throw 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: " + p);
!g && f > 2 ? v.set(p, f) : v.set(p, !0);
}
applyMemberDec(a, l, c, p, f, h, d, u);
}
}
return pushInitializers(a, r), pushInitializers(a, n), a;
}
function pushInitializers(e, t) {
t && e.push(function (e) {
for (var r = 0; r < t.length; r++) t[r].call(e);
return e;
});
}
return function (e, t, r) {
return {
e: applyMemberDecs(e, t),
get c() {
return function (e, t) {
if (t.length > 0) {
for (var r = [], n = e, a = e.name, i = t.length - 1; i >= 0; i--) {
var o = {
v: !1
};
try {
var s = t[i](n, {
kind: "class",
name: a,
addInitializer: createAddInitializerMethod(r, o)
});
} finally {
o.v = !0;
}
void 0 !== s && (assertValidReturnValue(10, s), n = s);
}
return [n, function () {
for (var e = 0; e < r.length; e++) r[e].call(n);
}];
}
}(e, r);
}
};
};
}
function applyDecs2203R(e, t, r) {
return (applyDecs2203R = applyDecs2203RFactory())(e, t, r);
}
export { applyDecs2203R as default };

View File

@@ -0,0 +1,236 @@
/*! *****************************************************************************
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.
***************************************************************************** */
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/typingsInstaller/nodeTypingsInstaller.ts
var nodeTypingsInstaller_exports = {};
__export(nodeTypingsInstaller_exports, {
NodeTypingsInstaller: () => NodeTypingsInstaller
});
module.exports = __toCommonJS(nodeTypingsInstaller_exports);
var fs = __toESM(require("fs"));
var path = __toESM(require("path"));
// src/typescript/typescript.ts
var typescript_exports = {};
__reExport(typescript_exports, require("./typescript.js"));
// src/typingsInstaller/nodeTypingsInstaller.ts
var FileLog = class {
constructor(logFile) {
this.logFile = logFile;
this.isEnabled = () => {
return typeof this.logFile === "string";
};
this.writeLine = (text) => {
if (typeof this.logFile !== "string") return;
try {
fs.appendFileSync(this.logFile, `[${typescript_exports.server.nowString()}] ${text}${typescript_exports.sys.newLine}`);
} catch (e) {
this.logFile = void 0;
}
};
}
};
function getDefaultNPMLocation(processName, validateDefaultNpmLocation2, host) {
if (path.basename(processName).indexOf("node") === 0) {
const npmPath = path.join(path.dirname(process.argv[0]), "npm");
if (!validateDefaultNpmLocation2) {
return npmPath;
}
if (host.fileExists(npmPath)) {
return `"${npmPath}"`;
}
}
return "npm";
}
function loadTypesRegistryFile(typesRegistryFilePath, host, log2) {
if (!host.fileExists(typesRegistryFilePath)) {
if (log2.isEnabled()) {
log2.writeLine(`Types registry file '${typesRegistryFilePath}' does not exist`);
}
return /* @__PURE__ */ new Map();
}
try {
const content = JSON.parse(host.readFile(typesRegistryFilePath));
return new Map(Object.entries(content.entries));
} catch (e) {
if (log2.isEnabled()) {
log2.writeLine(`Error when loading types registry file '${typesRegistryFilePath}': ${e.message}, ${e.stack}`);
}
return /* @__PURE__ */ new Map();
}
}
var typesRegistryPackageName = "types-registry";
function getTypesRegistryFileLocation(globalTypingsCacheLocation2) {
return (0, typescript_exports.combinePaths)((0, typescript_exports.normalizeSlashes)(globalTypingsCacheLocation2), `node_modules/${typesRegistryPackageName}/index.json`);
}
var NodeTypingsInstaller = class extends typescript_exports.server.typingsInstaller.TypingsInstaller {
constructor(globalTypingsCacheLocation2, typingSafeListLocation2, typesMapLocation2, npmLocation2, validateDefaultNpmLocation2, throttleLimit, log2) {
const libDirectory = (0, typescript_exports.getDirectoryPath)((0, typescript_exports.normalizePath)(typescript_exports.sys.getExecutingFilePath()));
super(
typescript_exports.sys,
globalTypingsCacheLocation2,
typingSafeListLocation2 ? (0, typescript_exports.toPath)(typingSafeListLocation2, "", (0, typescript_exports.createGetCanonicalFileName)(typescript_exports.sys.useCaseSensitiveFileNames)) : (0, typescript_exports.toPath)("typingSafeList.json", libDirectory, (0, typescript_exports.createGetCanonicalFileName)(typescript_exports.sys.useCaseSensitiveFileNames)),
typesMapLocation2 ? (0, typescript_exports.toPath)(typesMapLocation2, "", (0, typescript_exports.createGetCanonicalFileName)(typescript_exports.sys.useCaseSensitiveFileNames)) : (0, typescript_exports.toPath)("typesMap.json", libDirectory, (0, typescript_exports.createGetCanonicalFileName)(typescript_exports.sys.useCaseSensitiveFileNames)),
throttleLimit,
log2
);
this.npmPath = npmLocation2 !== void 0 ? npmLocation2 : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation2, this.installTypingHost);
if (this.npmPath.includes(" ") && this.npmPath[0] !== `"`) {
this.npmPath = `"${this.npmPath}"`;
}
if (this.log.isEnabled()) {
this.log.writeLine(`Process id: ${process.pid}`);
this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${typescript_exports.server.Arguments.NpmLocation}' ${npmLocation2 === void 0 ? "not " : ""} provided)`);
this.log.writeLine(`validateDefaultNpmLocation: ${validateDefaultNpmLocation2}`);
}
({ execSync: this.nodeExecSync } = require("child_process"));
this.ensurePackageDirectoryExists(globalTypingsCacheLocation2);
try {
if (this.log.isEnabled()) {
this.log.writeLine(`Updating ${typesRegistryPackageName} npm package...`);
}
this.execSyncAndLog(`${this.npmPath} install --ignore-scripts ${typesRegistryPackageName}@${this.latestDistTag}`, { cwd: globalTypingsCacheLocation2 });
if (this.log.isEnabled()) {
this.log.writeLine(`Updated ${typesRegistryPackageName} npm package`);
}
} catch (e) {
if (this.log.isEnabled()) {
this.log.writeLine(`Error updating ${typesRegistryPackageName} package: ${e.message}`);
}
this.delayedInitializationError = {
kind: "event::initializationFailed",
message: e.message,
stack: e.stack
};
}
this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation2), this.installTypingHost, this.log);
}
handleRequest(req) {
if (this.delayedInitializationError) {
this.sendResponse(this.delayedInitializationError);
this.delayedInitializationError = void 0;
}
super.handleRequest(req);
}
sendResponse(response) {
if (this.log.isEnabled()) {
this.log.writeLine(`Sending response:${typescript_exports.server.stringifyIndented(response)}`);
}
process.send(response);
if (this.log.isEnabled()) {
this.log.writeLine(`Response has been sent.`);
}
}
installWorker(requestId, packageNames, cwd, onRequestCompleted) {
if (this.log.isEnabled()) {
this.log.writeLine(`#${requestId} with cwd: ${cwd} arguments: ${JSON.stringify(packageNames)}`);
}
const start = Date.now();
const hasError = typescript_exports.server.typingsInstaller.installNpmPackages(this.npmPath, typescript_exports.version, packageNames, (command) => this.execSyncAndLog(command, { cwd }));
if (this.log.isEnabled()) {
this.log.writeLine(`npm install #${requestId} took: ${Date.now() - start} ms`);
}
onRequestCompleted(!hasError);
}
/** Returns 'true' in case of error. */
execSyncAndLog(command, options) {
if (this.log.isEnabled()) {
this.log.writeLine(`Exec: ${command}`);
}
try {
const stdout = this.nodeExecSync(command, { ...options, encoding: "utf-8" });
if (this.log.isEnabled()) {
this.log.writeLine(` Succeeded. stdout:${indent(typescript_exports.sys.newLine, stdout)}`);
}
return false;
} catch (error) {
const { stdout, stderr } = error;
this.log.writeLine(` Failed. stdout:${indent(typescript_exports.sys.newLine, stdout)}${typescript_exports.sys.newLine} stderr:${indent(typescript_exports.sys.newLine, stderr)}`);
return true;
}
}
};
var logFilePath = typescript_exports.server.findArgument(typescript_exports.server.Arguments.LogFile);
var globalTypingsCacheLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.GlobalCacheLocation);
var typingSafeListLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.TypingSafeListLocation);
var typesMapLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.TypesMapLocation);
var npmLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.NpmLocation);
var validateDefaultNpmLocation = typescript_exports.server.hasArgument(typescript_exports.server.Arguments.ValidateDefaultNpmLocation);
var log = new FileLog(logFilePath);
if (log.isEnabled()) {
process.on("uncaughtException", (e) => {
log.writeLine(`Unhandled exception: ${e} at ${e.stack}`);
});
}
process.on("disconnect", () => {
if (log.isEnabled()) {
log.writeLine(`Parent process has exited, shutting down...`);
}
process.exit(0);
});
var installer;
process.on("message", (req) => {
installer ?? (installer = new NodeTypingsInstaller(
globalTypingsCacheLocation,
typingSafeListLocation,
typesMapLocation,
npmLocation,
validateDefaultNpmLocation,
/*throttleLimit*/
5,
log
));
installer.handleRequest(req);
});
function indent(newline, str) {
return str && str.length ? `${newline} ` + str.replace(/\r?\n/, `${newline} `) : "";
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
NodeTypingsInstaller
});
//# sourceMappingURL=typingsInstaller.js.map

View File

@@ -0,0 +1,191 @@
/*! *****************************************************************************
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.
***************************************************************************** */
/// <reference lib="es2015.symbol" />
/// <reference lib="es2015.iterable" />
/// <reference lib="es2018.asynciterable" />
interface SymbolConstructor {
/**
* A method that is used to release resources held by an object. Called by the semantics of the `using` statement.
*/
readonly dispose: unique symbol;
/**
* A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement.
*/
readonly asyncDispose: unique symbol;
}
interface Disposable {
[Symbol.dispose](): void;
}
interface AsyncDisposable {
[Symbol.asyncDispose](): PromiseLike<void>;
}
interface SuppressedError extends Error {
error: any;
suppressed: any;
}
interface SuppressedErrorConstructor {
new (error: any, suppressed: any, message?: string): SuppressedError;
(error: any, suppressed: any, message?: string): SuppressedError;
readonly prototype: SuppressedError;
}
declare var SuppressedError: SuppressedErrorConstructor;
interface DisposableStack {
/**
* Returns a value indicating whether this stack has been disposed.
*/
readonly disposed: boolean;
/**
* Disposes each resource in the stack in the reverse order that they were added.
*/
dispose(): void;
/**
* Adds a disposable resource to the stack, returning the resource.
* @param value The resource to add. `null` and `undefined` will not be added, but will be returned.
* @returns The provided {@link value}.
*/
use<T extends Disposable | null | undefined>(value: T): T;
/**
* Adds a value and associated disposal callback as a resource to the stack.
* @param value The value to add.
* @param onDispose The callback to use in place of a `[Symbol.dispose]()` method. Will be invoked with `value`
* as the first parameter.
* @returns The provided {@link value}.
*/
adopt<T>(value: T, onDispose: (value: T) => void): T;
/**
* Adds a callback to be invoked when the stack is disposed.
*/
defer(onDispose: () => void): void;
/**
* Move all resources out of this stack and into a new `DisposableStack`, and marks this stack as disposed.
* @example
* ```ts
* class C {
* #res1: Disposable;
* #res2: Disposable;
* #disposables: DisposableStack;
* constructor() {
* // stack will be disposed when exiting constructor for any reason
* using stack = new DisposableStack();
*
* // get first resource
* this.#res1 = stack.use(getResource1());
*
* // get second resource. If this fails, both `stack` and `#res1` will be disposed.
* this.#res2 = stack.use(getResource2());
*
* // all operations succeeded, move resources out of `stack` so that they aren't disposed
* // when constructor exits
* this.#disposables = stack.move();
* }
*
* [Symbol.dispose]() {
* this.#disposables.dispose();
* }
* }
* ```
*/
move(): DisposableStack;
[Symbol.dispose](): void;
readonly [Symbol.toStringTag]: string;
}
interface DisposableStackConstructor {
new (): DisposableStack;
readonly prototype: DisposableStack;
}
declare var DisposableStack: DisposableStackConstructor;
interface AsyncDisposableStack {
/**
* Returns a value indicating whether this stack has been disposed.
*/
readonly disposed: boolean;
/**
* Disposes each resource in the stack in the reverse order that they were added.
*/
disposeAsync(): Promise<void>;
/**
* Adds a disposable resource to the stack, returning the resource.
* @param value The resource to add. `null` and `undefined` will not be added, but will be returned.
* @returns The provided {@link value}.
*/
use<T extends AsyncDisposable | Disposable | null | undefined>(value: T): T;
/**
* Adds a value and associated disposal callback as a resource to the stack.
* @param value The value to add.
* @param onDisposeAsync The callback to use in place of a `[Symbol.asyncDispose]()` method. Will be invoked with `value`
* as the first parameter.
* @returns The provided {@link value}.
*/
adopt<T>(value: T, onDisposeAsync: (value: T) => PromiseLike<void> | void): T;
/**
* Adds a callback to be invoked when the stack is disposed.
*/
defer(onDisposeAsync: () => PromiseLike<void> | void): void;
/**
* Move all resources out of this stack and into a new `DisposableStack`, and marks this stack as disposed.
* @example
* ```ts
* class C {
* #res1: Disposable;
* #res2: Disposable;
* #disposables: DisposableStack;
* constructor() {
* // stack will be disposed when exiting constructor for any reason
* using stack = new DisposableStack();
*
* // get first resource
* this.#res1 = stack.use(getResource1());
*
* // get second resource. If this fails, both `stack` and `#res1` will be disposed.
* this.#res2 = stack.use(getResource2());
*
* // all operations succeeded, move resources out of `stack` so that they aren't disposed
* // when constructor exits
* this.#disposables = stack.move();
* }
*
* [Symbol.dispose]() {
* this.#disposables.dispose();
* }
* }
* ```
*/
move(): AsyncDisposableStack;
[Symbol.asyncDispose](): Promise<void>;
readonly [Symbol.toStringTag]: string;
}
interface AsyncDisposableStackConstructor {
new (): AsyncDisposableStack;
readonly prototype: AsyncDisposableStack;
}
declare var AsyncDisposableStack: AsyncDisposableStackConstructor;
interface IteratorObject<T, TReturn, TNext> extends Disposable {
}
interface AsyncIteratorObject<T, TReturn, TNext> extends AsyncDisposable {
}

View File

@@ -0,0 +1,177 @@
# @eslint-community/regexpp
[![npm version](https://img.shields.io/npm/v/@eslint-community/regexpp.svg)](https://www.npmjs.com/package/@eslint-community/regexpp)
[![Downloads/month](https://img.shields.io/npm/dm/@eslint-community/regexpp.svg)](http://www.npmtrends.com/@eslint-community/regexpp)
[![Build Status](https://github.com/eslint-community/regexpp/workflows/CI/badge.svg)](https://github.com/eslint-community/regexpp/actions)
[![codecov](https://codecov.io/gh/eslint-community/regexpp/branch/main/graph/badge.svg)](https://codecov.io/gh/eslint-community/regexpp)
A regular expression parser for ECMAScript.
## 💿 Installation
```bash
$ npm install @eslint-community/regexpp
```
- require Node@^12.0.0 || ^14.0.0 || >=16.0.0.
## 📖 Usage
```ts
import {
AST,
RegExpParser,
RegExpValidator,
RegExpVisitor,
parseRegExpLiteral,
validateRegExpLiteral,
visitRegExpAST
} from "@eslint-community/regexpp"
```
### parseRegExpLiteral(source, options?)
Parse a given regular expression literal then make AST object.
This is equivalent to `new RegExpParser(options).parseLiteral(source)`.
- **Parameters:**
- `source` (`string | RegExp`) The source code to parse.
- `options?` ([`RegExpParser.Options`]) The options to parse.
- **Return:**
- The AST of the regular expression.
### validateRegExpLiteral(source, options?)
Validate a given regular expression literal.
This is equivalent to `new RegExpValidator(options).validateLiteral(source)`.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `options?` ([`RegExpValidator.Options`]) The options to validate.
### visitRegExpAST(ast, handlers)
Visit each node of a given AST.
This is equivalent to `new RegExpVisitor(handlers).visit(ast)`.
- **Parameters:**
- `ast` ([`AST.Node`]) The AST to visit.
- `handlers` ([`RegExpVisitor.Handlers`]) The callbacks.
### RegExpParser
#### new RegExpParser(options?)
- **Parameters:**
- `options?` ([`RegExpParser.Options`]) The options to parse.
#### parser.parseLiteral(source, start?, end?)
Parse a regular expression literal.
- **Parameters:**
- `source` (`string`) The source code to parse. E.g. `"/abc/g"`.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- **Return:**
- The AST of the regular expression.
#### parser.parsePattern(source, start?, end?, flags?)
Parse a regular expression pattern.
- **Parameters:**
- `source` (`string`) The source code to parse. E.g. `"abc"`.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode.
- **Return:**
- The AST of the regular expression pattern.
#### parser.parseFlags(source, start?, end?)
Parse a regular expression flags.
- **Parameters:**
- `source` (`string`) The source code to parse. E.g. `"gim"`.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- **Return:**
- The AST of the regular expression flags.
### RegExpValidator
#### new RegExpValidator(options)
- **Parameters:**
- `options` ([`RegExpValidator.Options`]) The options to validate.
#### validator.validateLiteral(source, start, end)
Validate a regular expression literal.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
#### validator.validatePattern(source, start, end, flags)
Validate a regular expression pattern.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode.
#### validator.validateFlags(source, start, end)
Validate a regular expression flags.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
### RegExpVisitor
#### new RegExpVisitor(handlers)
- **Parameters:**
- `handlers` ([`RegExpVisitor.Handlers`]) The callbacks.
#### visitor.visit(ast)
Validate a regular expression literal.
- **Parameters:**
- `ast` ([`AST.Node`]) The AST to visit.
## 📰 Changelog
- [GitHub Releases](https://github.com/eslint-community/regexpp/releases)
## 🍻 Contributing
Welcome contributing!
Please use GitHub's Issues/PRs.
### Development Tools
- `npm test` runs tests and measures coverage.
- `npm run build` compiles TypeScript source code to `index.js`, `index.js.map`, and `index.d.ts`.
- `npm run clean` removes the temporary files which are created by `npm test` and `npm run build`.
- `npm run lint` runs ESLint.
- `npm run update:test` updates test fixtures.
- `npm run update:ids` updates `src/unicode/ids.ts`.
- `npm run watch` runs tests with `--watch` option.
[`AST.Node`]: src/ast.ts#L4
[`RegExpParser.Options`]: src/parser.ts#L743
[`RegExpValidator.Options`]: src/validator.ts#L220
[`RegExpVisitor.Handlers`]: src/visitor.ts#L291

View File

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

View File

@@ -0,0 +1,305 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PoseidonSponge = void 0;
exports.grainGenConstants = grainGenConstants;
exports.validateOpts = validateOpts;
exports.splitConstants = splitConstants;
exports.poseidon = poseidon;
exports.poseidonSponge = poseidonSponge;
/**
* Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash.
*
* There are many poseidon variants with different constants.
* We don't provide them: you should construct them manually.
* Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const utils_ts_1 = require("../utils.js");
const modular_ts_1 = require("./modular.js");
// Grain LFSR (Linear-Feedback Shift Register): https://eprint.iacr.org/2009/109.pdf
function grainLFSR(state) {
let pos = 0;
if (state.length !== 80)
throw new Error('grainLFRS: wrong state length, should be 80 bits');
const getBit = () => {
const r = (offset) => state[(pos + offset) % 80];
const bit = r(62) ^ r(51) ^ r(38) ^ r(23) ^ r(13) ^ r(0);
state[pos] = bit;
pos = ++pos % 80;
return !!bit;
};
for (let i = 0; i < 160; i++)
getBit();
return () => {
// https://en.wikipedia.org/wiki/Shrinking_generator
while (true) {
const b1 = getBit();
const b2 = getBit();
if (!b1)
continue;
return b2;
}
};
}
function assertValidPosOpts(opts) {
const { Fp, roundsFull } = opts;
(0, modular_ts_1.validateField)(Fp);
(0, utils_ts_1._validateObject)(opts, {
t: 'number',
roundsFull: 'number',
roundsPartial: 'number',
}, {
isSboxInverse: 'boolean',
});
for (const i of ['t', 'roundsFull', 'roundsPartial']) {
if (!Number.isSafeInteger(opts[i]) || opts[i] < 1)
throw new Error('invalid number ' + i);
}
if (roundsFull & 1)
throw new Error('roundsFull is not even' + roundsFull);
}
function poseidonGrain(opts) {
assertValidPosOpts(opts);
const { Fp } = opts;
const state = Array(80).fill(1);
let pos = 0;
const writeBits = (value, bitCount) => {
for (let i = bitCount - 1; i >= 0; i--)
state[pos++] = Number((0, utils_ts_1.bitGet)(value, i));
};
const _0n = BigInt(0);
const _1n = BigInt(1);
writeBits(_1n, 2); // prime field
writeBits(opts.isSboxInverse ? _1n : _0n, 4); // b2..b5
writeBits(BigInt(Fp.BITS), 12); // b6..b17
writeBits(BigInt(opts.t), 12); // b18..b29
writeBits(BigInt(opts.roundsFull), 10); // b30..b39
writeBits(BigInt(opts.roundsPartial), 10); // b40..b49
const getBit = grainLFSR(state);
return (count, reject) => {
const res = [];
for (let i = 0; i < count; i++) {
while (true) {
let num = _0n;
for (let i = 0; i < Fp.BITS; i++) {
num <<= _1n;
if (getBit())
num |= _1n;
}
if (reject && num >= Fp.ORDER)
continue; // rejection sampling
res.push(Fp.create(num));
break;
}
}
return res;
};
}
// NOTE: this is not standard but used often for constant generation for poseidon
// (grain LFRS-like structure)
function grainGenConstants(opts, skipMDS = 0) {
const { Fp, t, roundsFull, roundsPartial } = opts;
const rounds = roundsFull + roundsPartial;
const sample = poseidonGrain(opts);
const roundConstants = [];
for (let r = 0; r < rounds; r++)
roundConstants.push(sample(t, true));
if (skipMDS > 0)
for (let i = 0; i < skipMDS; i++)
sample(2 * t, false);
const xs = sample(t, false);
const ys = sample(t, false);
// Construct MDS Matrix M[i][j] = 1 / (xs[i] + ys[j])
const mds = [];
for (let i = 0; i < t; i++) {
const row = [];
for (let j = 0; j < t; j++) {
const xy = Fp.add(xs[i], ys[j]);
if (Fp.is0(xy))
throw new Error(`Error generating MDS matrix: xs[${i}] + ys[${j}] resulted in zero.`);
row.push(xy);
}
mds.push((0, modular_ts_1.FpInvertBatch)(Fp, row));
}
return { roundConstants, mds };
}
function validateOpts(opts) {
assertValidPosOpts(opts);
const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts;
const { roundsFull, roundsPartial, sboxPower, t } = opts;
// MDS is TxT matrix
if (!Array.isArray(mds) || mds.length !== t)
throw new Error('Poseidon: invalid MDS matrix');
const _mds = mds.map((mdsRow) => {
if (!Array.isArray(mdsRow) || mdsRow.length !== t)
throw new Error('invalid MDS matrix row: ' + mdsRow);
return mdsRow.map((i) => {
if (typeof i !== 'bigint')
throw new Error('invalid MDS matrix bigint: ' + i);
return Fp.create(i);
});
});
if (rev !== undefined && typeof rev !== 'boolean')
throw new Error('invalid param reversePartialPowIdx=' + rev);
if (roundsFull & 1)
throw new Error('roundsFull is not even' + roundsFull);
const rounds = roundsFull + roundsPartial;
if (!Array.isArray(rc) || rc.length !== rounds)
throw new Error('Poseidon: invalid round constants');
const roundConstants = rc.map((rc) => {
if (!Array.isArray(rc) || rc.length !== t)
throw new Error('invalid round constants');
return rc.map((i) => {
if (typeof i !== 'bigint' || !Fp.isValid(i))
throw new Error('invalid round constant');
return Fp.create(i);
});
});
if (!sboxPower || ![3, 5, 7, 17].includes(sboxPower))
throw new Error('invalid sboxPower');
const _sboxPower = BigInt(sboxPower);
let sboxFn = (n) => (0, modular_ts_1.FpPow)(Fp, n, _sboxPower);
// Unwrapped sbox power for common cases (195->142μs)
if (sboxPower === 3)
sboxFn = (n) => Fp.mul(Fp.sqrN(n), n);
else if (sboxPower === 5)
sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n);
return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds: _mds });
}
function splitConstants(rc, t) {
if (typeof t !== 'number')
throw new Error('poseidonSplitConstants: invalid t');
if (!Array.isArray(rc) || rc.length % t)
throw new Error('poseidonSplitConstants: invalid rc');
const res = [];
let tmp = [];
for (let i = 0; i < rc.length; i++) {
tmp.push(rc[i]);
if (tmp.length === t) {
res.push(tmp);
tmp = [];
}
}
return res;
}
/** Poseidon NTT-friendly hash. */
function poseidon(opts) {
const _opts = validateOpts(opts);
const { Fp, mds, roundConstants, rounds: totalRounds, roundsPartial, sboxFn, t } = _opts;
const halfRoundsFull = _opts.roundsFull / 2;
const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0;
const poseidonRound = (values, isFull, idx) => {
values = values.map((i, j) => Fp.add(i, roundConstants[idx][j]));
if (isFull)
values = values.map((i) => sboxFn(i));
else
values[partialIdx] = sboxFn(values[partialIdx]);
// Matrix multiplication
values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO));
return values;
};
const poseidonHash = function poseidonHash(values) {
if (!Array.isArray(values) || values.length !== t)
throw new Error('invalid values, expected array of bigints with length ' + t);
values = values.map((i) => {
if (typeof i !== 'bigint')
throw new Error('invalid bigint=' + i);
return Fp.create(i);
});
let lastRound = 0;
// Apply r_f/2 full rounds.
for (let i = 0; i < halfRoundsFull; i++)
values = poseidonRound(values, true, lastRound++);
// Apply r_p partial rounds.
for (let i = 0; i < roundsPartial; i++)
values = poseidonRound(values, false, lastRound++);
// Apply r_f/2 full rounds.
for (let i = 0; i < halfRoundsFull; i++)
values = poseidonRound(values, true, lastRound++);
if (lastRound !== totalRounds)
throw new Error('invalid number of rounds');
return values;
};
// For verification in tests
poseidonHash.roundConstants = roundConstants;
return poseidonHash;
}
class PoseidonSponge {
constructor(Fp, rate, capacity, hash) {
this.pos = 0;
this.isAbsorbing = true;
this.Fp = Fp;
this.hash = hash;
this.rate = rate;
this.capacity = capacity;
this.state = new Array(rate + capacity);
this.clean();
}
process() {
this.state = this.hash(this.state);
}
absorb(input) {
for (const i of input)
if (typeof i !== 'bigint' || !this.Fp.isValid(i))
throw new Error('invalid input: ' + i);
for (let i = 0; i < input.length;) {
if (!this.isAbsorbing || this.pos === this.rate) {
this.process();
this.pos = 0;
this.isAbsorbing = true;
}
const chunk = Math.min(this.rate - this.pos, input.length - i);
for (let j = 0; j < chunk; j++) {
const idx = this.capacity + this.pos++;
this.state[idx] = this.Fp.add(this.state[idx], input[i++]);
}
}
}
squeeze(count) {
const res = [];
while (res.length < count) {
if (this.isAbsorbing || this.pos === this.rate) {
this.process();
this.pos = 0;
this.isAbsorbing = false;
}
const chunk = Math.min(this.rate - this.pos, count - res.length);
for (let i = 0; i < chunk; i++)
res.push(this.state[this.capacity + this.pos++]);
}
return res;
}
clean() {
this.state.fill(this.Fp.ZERO);
this.isAbsorbing = true;
this.pos = 0;
}
clone() {
const c = new PoseidonSponge(this.Fp, this.rate, this.capacity, this.hash);
c.pos = this.pos;
c.state = [...this.state];
return c;
}
}
exports.PoseidonSponge = PoseidonSponge;
/**
* The method is not defined in spec, but nevertheless used often.
* Check carefully for compatibility: there are many edge cases, like absorbing an empty array.
* We cross-test against:
* - https://github.com/ProvableHQ/snarkVM/tree/staging/algorithms
* - https://github.com/arkworks-rs/crypto-primitives/tree/main
*/
function poseidonSponge(opts) {
for (const i of ['rate', 'capacity']) {
if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i]))
throw new Error('invalid number ' + i);
}
const { rate, capacity } = opts;
const t = opts.rate + opts.capacity;
// Re-use hash instance between multiple instances
const hash = poseidon({ ...opts, t });
const { Fp } = opts;
return () => new PoseidonSponge(Fp, rate, capacity, hash);
}
//# sourceMappingURL=poseidon.js.map

View File

@@ -0,0 +1,136 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
const util = __importStar(require("../core/util.cjs"));
const error = () => {
const Sizable = {
string: { unit: "harf", verb: "olmalıdır" },
file: { unit: "bayt", verb: "olmalıdır" },
array: { unit: "unsur", verb: "olmalıdır" },
set: { unit: "unsur", verb: "olmalıdır" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "giren",
email: "epostagâh",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO hengâmı",
date: "ISO tarihi",
time: "ISO zamanı",
duration: "ISO müddeti",
ipv4: "IPv4 nişânı",
ipv6: "IPv6 nişânı",
cidrv4: "IPv4 menzili",
cidrv6: "IPv6 menzili",
base64: "base64-şifreli metin",
base64url: "base64url-şifreli metin",
json_string: "JSON metin",
e164: "E.164 sayısı",
jwt: "JWT",
template_literal: "giren",
};
const TypeDictionary = {
nan: "NaN",
number: "numara",
array: "saf",
null: "gayb",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `Fâsit giren: umulan instanceof ${issue.expected}, alınan ${received}`;
}
return `Fâsit giren: umulan ${expected}, alınan ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Fâsit giren: umulan ${util.stringifyPrimitive(issue.values[0])}`;
return `Fâsit tercih: mûteberler ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmalıydı.`;
return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} olmalıydı.`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} ${sizing.unit} sahip olmalıydı.`;
}
return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} olmalıydı.`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with")
return `Fâsit metin: "${_issue.prefix}" ile başlamalı.`;
if (_issue.format === "ends_with")
return `Fâsit metin: "${_issue.suffix}" ile bitmeli.`;
if (_issue.format === "includes")
return `Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`;
if (_issue.format === "regex")
return `Fâsit metin: ${_issue.pattern} nakşına uymalı.`;
return `Fâsit ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Fâsit sayı: ${issue.divisor} katı olmalıydı.`;
case "unrecognized_keys":
return `Tanınmayan anahtar ${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `${issue.origin} için tanınmayan anahtar var.`;
case "invalid_union":
return "Giren tanınamadı.";
case "invalid_element":
return `${issue.origin} için tanınmayan kıymet var.`;
default:
return `Kıymet tanınamadı.`;
}
};
};
function default_1() {
return {
localeError: error(),
};
}
module.exports = exports.default;