WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "@esbuild/linux-x64",
|
||||
"version": "0.28.2",
|
||||
"description": "The Linux 64-bit binary for esbuild, a JavaScript bundler.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/evanw/esbuild.git"
|
||||
},
|
||||
"license": "MIT",
|
||||
"preferUnplugged": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
'use strict'
|
||||
|
||||
const bench = require('fastbench')
|
||||
const pino = require('../../')
|
||||
const fs = require('node:fs')
|
||||
const dest = fs.createWriteStream('/dev/null')
|
||||
const plog = pino(dest)
|
||||
delete require.cache[require.resolve('../../')]
|
||||
const plogAsync = require('../../')(pino.destination({ dest: '/dev/null', sync: false }))
|
||||
delete require.cache[require.resolve('../../')]
|
||||
const plogUnsafe = require('../../')({ safe: false }, dest)
|
||||
delete require.cache[require.resolve('../../')]
|
||||
const plogUnsafeAsync = require('../../')(
|
||||
{ safe: false },
|
||||
pino.destination({ dest: '/dev/null', sync: false })
|
||||
)
|
||||
const plogRedact = pino({ redact: ['a.b.c'] }, dest)
|
||||
delete require.cache[require.resolve('../../')]
|
||||
const plogAsyncRedact = require('../../')(
|
||||
{ redact: ['a.b.c'] },
|
||||
pino.destination({ dest: '/dev/null', sync: false })
|
||||
)
|
||||
delete require.cache[require.resolve('../../')]
|
||||
const plogUnsafeRedact = require('../../')({ redact: ['a.b.c'], safe: false }, dest)
|
||||
delete require.cache[require.resolve('../../')]
|
||||
const plogUnsafeAsyncRedact = require('../../')(
|
||||
{ redact: ['a.b.c'], safe: false },
|
||||
pino.destination({ dest: '/dev/null', sync: false })
|
||||
)
|
||||
|
||||
const max = 10
|
||||
|
||||
// note that "redact me." is the same amount of bytes as the censor: "[Redacted]"
|
||||
|
||||
const run = bench([
|
||||
function benchPinoNoRedact (cb) {
|
||||
for (var i = 0; i < max; i++) {
|
||||
plog.info({ a: { b: { c: 'redact me.', d: 'leave me' } } })
|
||||
}
|
||||
setImmediate(cb)
|
||||
},
|
||||
function benchPinoRedact (cb) {
|
||||
for (var i = 0; i < max; i++) {
|
||||
plogRedact.info({ a: { b: { c: 'redact me.', d: 'leave me' } } })
|
||||
}
|
||||
setImmediate(cb)
|
||||
},
|
||||
function benchPinoUnsafeNoRedact (cb) {
|
||||
for (var i = 0; i < max; i++) {
|
||||
plogUnsafe.info({ a: { b: { c: 'redact me.', d: 'leave me' } } })
|
||||
}
|
||||
setImmediate(cb)
|
||||
},
|
||||
function benchPinoUnsafeRedact (cb) {
|
||||
for (var i = 0; i < max; i++) {
|
||||
plogUnsafeRedact.info({ a: { b: { c: 'redact me.', d: 'leave me' } } })
|
||||
}
|
||||
setImmediate(cb)
|
||||
},
|
||||
function benchPinoAsyncNoRedact (cb) {
|
||||
for (var i = 0; i < max; i++) {
|
||||
plogAsync.info({ a: { b: { c: 'redact me.', d: 'leave me' } } })
|
||||
}
|
||||
setImmediate(cb)
|
||||
},
|
||||
function benchPinoAsyncRedact (cb) {
|
||||
for (var i = 0; i < max; i++) {
|
||||
plogAsyncRedact.info({ a: { b: { c: 'redact me.', d: 'leave me' } } })
|
||||
}
|
||||
setImmediate(cb)
|
||||
},
|
||||
function benchPinoUnsafeAsyncNoRedact (cb) {
|
||||
for (var i = 0; i < max; i++) {
|
||||
plogUnsafeAsync.info({ a: { b: { c: 'redact me.', d: 'leave me' } } })
|
||||
}
|
||||
setImmediate(cb)
|
||||
},
|
||||
function benchPinoUnsafeAsyncRedact (cb) {
|
||||
for (var i = 0; i < max; i++) {
|
||||
plogUnsafeAsyncRedact.info({ a: { b: { c: 'redact me.', d: 'leave me' } } })
|
||||
}
|
||||
setImmediate(cb)
|
||||
}
|
||||
], 10000)
|
||||
|
||||
run(run)
|
||||
@@ -0,0 +1,559 @@
|
||||
"use strict";
|
||||
|
||||
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
|
||||
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
|
||||
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
|
||||
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
|
||||
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
|
||||
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
|
||||
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
|
||||
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
|
||||
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
|
||||
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
|
||||
// A simple implementation of make-array
|
||||
function makeArray(subject) {
|
||||
return Array.isArray(subject) ? subject : [subject];
|
||||
}
|
||||
var EMPTY = '';
|
||||
var SPACE = ' ';
|
||||
var ESCAPE = '\\';
|
||||
var REGEX_TEST_BLANK_LINE = /^\s+$/;
|
||||
var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
|
||||
var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
|
||||
var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
|
||||
var REGEX_SPLITALL_CRLF = /\r?\n/g;
|
||||
// /foo,
|
||||
// ./foo,
|
||||
// ../foo,
|
||||
// .
|
||||
// ..
|
||||
var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
|
||||
var SLASH = '/';
|
||||
|
||||
// Do not use ternary expression here, since "istanbul ignore next" is buggy
|
||||
var TMP_KEY_IGNORE = 'node-ignore';
|
||||
/* istanbul ignore else */
|
||||
if (typeof Symbol !== 'undefined') {
|
||||
TMP_KEY_IGNORE = Symbol["for"]('node-ignore');
|
||||
}
|
||||
var KEY_IGNORE = TMP_KEY_IGNORE;
|
||||
var define = function define(object, key, value) {
|
||||
return Object.defineProperty(object, key, {
|
||||
value: value
|
||||
});
|
||||
};
|
||||
var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
|
||||
var RETURN_FALSE = function RETURN_FALSE() {
|
||||
return false;
|
||||
};
|
||||
|
||||
// Sanitize the range of a regular expression
|
||||
// The cases are complicated, see test cases for details
|
||||
var sanitizeRange = function sanitizeRange(range) {
|
||||
return range.replace(REGEX_REGEXP_RANGE, function (match, from, to) {
|
||||
return from.charCodeAt(0) <= to.charCodeAt(0) ? match
|
||||
// Invalid range (out of order) which is ok for gitignore rules but
|
||||
// fatal for JavaScript regular expression, so eliminate it.
|
||||
: EMPTY;
|
||||
});
|
||||
};
|
||||
|
||||
// See fixtures #59
|
||||
var cleanRangeBackSlash = function cleanRangeBackSlash(slashes) {
|
||||
var length = slashes.length;
|
||||
return slashes.slice(0, length - length % 2);
|
||||
};
|
||||
|
||||
// > If the pattern ends with a slash,
|
||||
// > it is removed for the purpose of the following description,
|
||||
// > but it would only find a match with a directory.
|
||||
// > In other words, foo/ will match a directory foo and paths underneath it,
|
||||
// > but will not match a regular file or a symbolic link foo
|
||||
// > (this is consistent with the way how pathspec works in general in Git).
|
||||
// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
|
||||
// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
|
||||
// you could use option `mark: true` with `glob`
|
||||
|
||||
// '`foo/`' should not continue with the '`..`'
|
||||
var REPLACERS = [[
|
||||
// remove BOM
|
||||
// TODO:
|
||||
// Other similar zero-width characters?
|
||||
/^\uFEFF/, function () {
|
||||
return EMPTY;
|
||||
}],
|
||||
// > Trailing spaces are ignored unless they are quoted with backslash ("\")
|
||||
[
|
||||
// (a\ ) -> (a )
|
||||
// (a ) -> (a)
|
||||
// (a ) -> (a)
|
||||
// (a \ ) -> (a )
|
||||
/((?:\\\\)*?)(\\?\s+)$/, function (_, m1, m2) {
|
||||
return m1 + (m2.indexOf('\\') === 0 ? SPACE : EMPTY);
|
||||
}],
|
||||
// replace (\ ) with ' '
|
||||
// (\ ) -> ' '
|
||||
// (\\ ) -> '\\ '
|
||||
// (\\\ ) -> '\\ '
|
||||
[/(\\+?)\s/g, function (_, m1) {
|
||||
var length = m1.length;
|
||||
return m1.slice(0, length - length % 2) + SPACE;
|
||||
}],
|
||||
// Escape metacharacters
|
||||
// which is written down by users but means special for regular expressions.
|
||||
|
||||
// > There are 12 characters with special meanings:
|
||||
// > - the backslash \,
|
||||
// > - the caret ^,
|
||||
// > - the dollar sign $,
|
||||
// > - the period or dot .,
|
||||
// > - the vertical bar or pipe symbol |,
|
||||
// > - the question mark ?,
|
||||
// > - the asterisk or star *,
|
||||
// > - the plus sign +,
|
||||
// > - the opening parenthesis (,
|
||||
// > - the closing parenthesis ),
|
||||
// > - and the opening square bracket [,
|
||||
// > - the opening curly brace {,
|
||||
// > These special characters are often called "metacharacters".
|
||||
[/[\\$.|*+(){^]/g, function (match) {
|
||||
return "\\".concat(match);
|
||||
}], [
|
||||
// > a question mark (?) matches a single character
|
||||
/(?!\\)\?/g, function () {
|
||||
return '[^/]';
|
||||
}],
|
||||
// leading slash
|
||||
[
|
||||
// > A leading slash matches the beginning of the pathname.
|
||||
// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
|
||||
// A leading slash matches the beginning of the pathname
|
||||
/^\//, function () {
|
||||
return '^';
|
||||
}],
|
||||
// replace special metacharacter slash after the leading slash
|
||||
[/\//g, function () {
|
||||
return '\\/';
|
||||
}], [
|
||||
// > A leading "**" followed by a slash means match in all directories.
|
||||
// > For example, "**/foo" matches file or directory "foo" anywhere,
|
||||
// > the same as pattern "foo".
|
||||
// > "**/foo/bar" matches file or directory "bar" anywhere that is directly
|
||||
// > under directory "foo".
|
||||
// Notice that the '*'s have been replaced as '\\*'
|
||||
/^\^*\\\*\\\*\\\//,
|
||||
// '**/foo' <-> 'foo'
|
||||
function () {
|
||||
return '^(?:.*\\/)?';
|
||||
}],
|
||||
// starting
|
||||
[
|
||||
// there will be no leading '/'
|
||||
// (which has been replaced by section "leading slash")
|
||||
// If starts with '**', adding a '^' to the regular expression also works
|
||||
/^(?=[^^])/, function startingReplacer() {
|
||||
// If has a slash `/` at the beginning or middle
|
||||
return !/\/(?!$)/.test(this)
|
||||
// > Prior to 2.22.1
|
||||
// > If the pattern does not contain a slash /,
|
||||
// > Git treats it as a shell glob pattern
|
||||
// Actually, if there is only a trailing slash,
|
||||
// git also treats it as a shell glob pattern
|
||||
|
||||
// After 2.22.1 (compatible but clearer)
|
||||
// > If there is a separator at the beginning or middle (or both)
|
||||
// > of the pattern, then the pattern is relative to the directory
|
||||
// > level of the particular .gitignore file itself.
|
||||
// > Otherwise the pattern may also match at any level below
|
||||
// > the .gitignore level.
|
||||
? '(?:^|\\/)'
|
||||
|
||||
// > Otherwise, Git treats the pattern as a shell glob suitable for
|
||||
// > consumption by fnmatch(3)
|
||||
: '^';
|
||||
}],
|
||||
// two globstars
|
||||
[
|
||||
// Use lookahead assertions so that we could match more than one `'/**'`
|
||||
/\\\/\\\*\\\*(?=\\\/|$)/g,
|
||||
// Zero, one or several directories
|
||||
// should not use '*', or it will be replaced by the next replacer
|
||||
|
||||
// Check if it is not the last `'/**'`
|
||||
function (_, index, str) {
|
||||
return index + 6 < str.length
|
||||
|
||||
// case: /**/
|
||||
// > A slash followed by two consecutive asterisks then a slash matches
|
||||
// > zero or more directories.
|
||||
// > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
|
||||
// '/**/'
|
||||
? '(?:\\/[^\\/]+)*'
|
||||
|
||||
// case: /**
|
||||
// > A trailing `"/**"` matches everything inside.
|
||||
|
||||
// #21: everything inside but it should not include the current folder
|
||||
: '\\/.+';
|
||||
}],
|
||||
// normal intermediate wildcards
|
||||
[
|
||||
// Never replace escaped '*'
|
||||
// ignore rule '\*' will match the path '*'
|
||||
|
||||
// 'abc.*/' -> go
|
||||
// 'abc.*' -> skip this rule,
|
||||
// coz trailing single wildcard will be handed by [trailing wildcard]
|
||||
/(^|[^\\]+)(\\\*)+(?=.+)/g,
|
||||
// '*.js' matches '.js'
|
||||
// '*.js' doesn't match 'abc'
|
||||
function (_, p1, p2) {
|
||||
// 1.
|
||||
// > An asterisk "*" matches anything except a slash.
|
||||
// 2.
|
||||
// > Other consecutive asterisks are considered regular asterisks
|
||||
// > and will match according to the previous rules.
|
||||
var unescaped = p2.replace(/\\\*/g, '[^\\/]*');
|
||||
return p1 + unescaped;
|
||||
}], [
|
||||
// unescape, revert step 3 except for back slash
|
||||
// For example, if a user escape a '\\*',
|
||||
// after step 3, the result will be '\\\\\\*'
|
||||
/\\\\\\(?=[$.|*+(){^])/g, function () {
|
||||
return ESCAPE;
|
||||
}], [
|
||||
// '\\\\' -> '\\'
|
||||
/\\\\/g, function () {
|
||||
return ESCAPE;
|
||||
}], [
|
||||
// > The range notation, e.g. [a-zA-Z],
|
||||
// > can be used to match one of the characters in a range.
|
||||
|
||||
// `\` is escaped by step 3
|
||||
/(\\)?\[([^\]/]*?)(\\*)($|\])/g, function (match, leadEscape, range, endEscape, close) {
|
||||
return leadEscape === ESCAPE
|
||||
// '\\[bar]' -> '\\\\[bar\\]'
|
||||
? "\\[".concat(range).concat(cleanRangeBackSlash(endEscape)).concat(close) : close === ']' ? endEscape.length % 2 === 0
|
||||
// A normal case, and it is a range notation
|
||||
// '[bar]'
|
||||
// '[bar\\\\]'
|
||||
? "[".concat(sanitizeRange(range)).concat(endEscape, "]") // Invalid range notaton
|
||||
// '[bar\\]' -> '[bar\\\\]'
|
||||
: '[]' : '[]';
|
||||
}],
|
||||
// ending
|
||||
[
|
||||
// 'js' will not match 'js.'
|
||||
// 'ab' will not match 'abc'
|
||||
/(?:[^*])$/,
|
||||
// WTF!
|
||||
// https://git-scm.com/docs/gitignore
|
||||
// changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
|
||||
// which re-fixes #24, #38
|
||||
|
||||
// > If there is a separator at the end of the pattern then the pattern
|
||||
// > will only match directories, otherwise the pattern can match both
|
||||
// > files and directories.
|
||||
|
||||
// 'js*' will not match 'a.js'
|
||||
// 'js/' will not match 'a.js'
|
||||
// 'js' will match 'a.js' and 'a.js/'
|
||||
function (match) {
|
||||
return /\/$/.test(match)
|
||||
// foo/ will not match 'foo'
|
||||
? "".concat(match, "$") // foo matches 'foo' and 'foo/'
|
||||
: "".concat(match, "(?=$|\\/$)");
|
||||
}],
|
||||
// trailing wildcard
|
||||
[/(\^|\\\/)?\\\*$/, function (_, p1) {
|
||||
var prefix = p1
|
||||
// '\^':
|
||||
// '/*' does not match EMPTY
|
||||
// '/*' does not match everything
|
||||
|
||||
// '\\\/':
|
||||
// 'abc/*' does not match 'abc/'
|
||||
? "".concat(p1, "[^/]+") // 'a*' matches 'a'
|
||||
// 'a*' matches 'aa'
|
||||
: '[^/]*';
|
||||
return "".concat(prefix, "(?=$|\\/$)");
|
||||
}]];
|
||||
|
||||
// A simple cache, because an ignore rule only has only one certain meaning
|
||||
var regexCache = Object.create(null);
|
||||
|
||||
// @param {pattern}
|
||||
var makeRegex = function makeRegex(pattern, ignoreCase) {
|
||||
var source = regexCache[pattern];
|
||||
if (!source) {
|
||||
source = REPLACERS.reduce(function (prev, _ref) {
|
||||
var _ref2 = _slicedToArray(_ref, 2),
|
||||
matcher = _ref2[0],
|
||||
replacer = _ref2[1];
|
||||
return prev.replace(matcher, replacer.bind(pattern));
|
||||
}, pattern);
|
||||
regexCache[pattern] = source;
|
||||
}
|
||||
return ignoreCase ? new RegExp(source, 'i') : new RegExp(source);
|
||||
};
|
||||
var isString = function isString(subject) {
|
||||
return typeof subject === 'string';
|
||||
};
|
||||
|
||||
// > A blank line matches no files, so it can serve as a separator for readability.
|
||||
var checkPattern = function checkPattern(pattern) {
|
||||
return pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)
|
||||
|
||||
// > A line starting with # serves as a comment.
|
||||
&& pattern.indexOf('#') !== 0;
|
||||
};
|
||||
var splitPattern = function splitPattern(pattern) {
|
||||
return pattern.split(REGEX_SPLITALL_CRLF);
|
||||
};
|
||||
var IgnoreRule = /*#__PURE__*/_createClass(function IgnoreRule(origin, pattern, negative, regex) {
|
||||
_classCallCheck(this, IgnoreRule);
|
||||
this.origin = origin;
|
||||
this.pattern = pattern;
|
||||
this.negative = negative;
|
||||
this.regex = regex;
|
||||
});
|
||||
var createRule = function createRule(pattern, ignoreCase) {
|
||||
var origin = pattern;
|
||||
var negative = false;
|
||||
|
||||
// > An optional prefix "!" which negates the pattern;
|
||||
if (pattern.indexOf('!') === 0) {
|
||||
negative = true;
|
||||
pattern = pattern.substr(1);
|
||||
}
|
||||
pattern = pattern
|
||||
// > Put a backslash ("\") in front of the first "!" for patterns that
|
||||
// > begin with a literal "!", for example, `"\!important!.txt"`.
|
||||
.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')
|
||||
// > Put a backslash ("\") in front of the first hash for patterns that
|
||||
// > begin with a hash.
|
||||
.replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#');
|
||||
var regex = makeRegex(pattern, ignoreCase);
|
||||
return new IgnoreRule(origin, pattern, negative, regex);
|
||||
};
|
||||
var throwError = function throwError(message, Ctor) {
|
||||
throw new Ctor(message);
|
||||
};
|
||||
var checkPath = function checkPath(path, originalPath, doThrow) {
|
||||
if (!isString(path)) {
|
||||
return doThrow("path must be a string, but got `".concat(originalPath, "`"), TypeError);
|
||||
}
|
||||
|
||||
// We don't know if we should ignore EMPTY, so throw
|
||||
if (!path) {
|
||||
return doThrow("path must not be empty", TypeError);
|
||||
}
|
||||
|
||||
// Check if it is a relative path
|
||||
if (checkPath.isNotRelative(path)) {
|
||||
var r = '`path.relative()`d';
|
||||
return doThrow("path should be a ".concat(r, " string, but got \"").concat(originalPath, "\""), RangeError);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
var isNotRelative = function isNotRelative(path) {
|
||||
return REGEX_TEST_INVALID_PATH.test(path);
|
||||
};
|
||||
checkPath.isNotRelative = isNotRelative;
|
||||
checkPath.convert = function (p) {
|
||||
return p;
|
||||
};
|
||||
var Ignore = /*#__PURE__*/function () {
|
||||
function Ignore() {
|
||||
var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
|
||||
_ref3$ignorecase = _ref3.ignorecase,
|
||||
ignorecase = _ref3$ignorecase === void 0 ? true : _ref3$ignorecase,
|
||||
_ref3$ignoreCase = _ref3.ignoreCase,
|
||||
ignoreCase = _ref3$ignoreCase === void 0 ? ignorecase : _ref3$ignoreCase,
|
||||
_ref3$allowRelativePa = _ref3.allowRelativePaths,
|
||||
allowRelativePaths = _ref3$allowRelativePa === void 0 ? false : _ref3$allowRelativePa;
|
||||
_classCallCheck(this, Ignore);
|
||||
define(this, KEY_IGNORE, true);
|
||||
this._rules = [];
|
||||
this._ignoreCase = ignoreCase;
|
||||
this._allowRelativePaths = allowRelativePaths;
|
||||
this._initCache();
|
||||
}
|
||||
_createClass(Ignore, [{
|
||||
key: "_initCache",
|
||||
value: function _initCache() {
|
||||
this._ignoreCache = Object.create(null);
|
||||
this._testCache = Object.create(null);
|
||||
}
|
||||
}, {
|
||||
key: "_addPattern",
|
||||
value: function _addPattern(pattern) {
|
||||
// #32
|
||||
if (pattern && pattern[KEY_IGNORE]) {
|
||||
this._rules = this._rules.concat(pattern._rules);
|
||||
this._added = true;
|
||||
return;
|
||||
}
|
||||
if (checkPattern(pattern)) {
|
||||
var rule = createRule(pattern, this._ignoreCase);
|
||||
this._added = true;
|
||||
this._rules.push(rule);
|
||||
}
|
||||
}
|
||||
|
||||
// @param {Array<string> | string | Ignore} pattern
|
||||
}, {
|
||||
key: "add",
|
||||
value: function add(pattern) {
|
||||
this._added = false;
|
||||
makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this);
|
||||
|
||||
// Some rules have just added to the ignore,
|
||||
// making the behavior changed.
|
||||
if (this._added) {
|
||||
this._initCache();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
// legacy
|
||||
}, {
|
||||
key: "addPattern",
|
||||
value: function addPattern(pattern) {
|
||||
return this.add(pattern);
|
||||
}
|
||||
|
||||
// | ignored : unignored
|
||||
// negative | 0:0 | 0:1 | 1:0 | 1:1
|
||||
// -------- | ------- | ------- | ------- | --------
|
||||
// 0 | TEST | TEST | SKIP | X
|
||||
// 1 | TESTIF | SKIP | TEST | X
|
||||
|
||||
// - SKIP: always skip
|
||||
// - TEST: always test
|
||||
// - TESTIF: only test if checkUnignored
|
||||
// - X: that never happen
|
||||
|
||||
// @param {boolean} whether should check if the path is unignored,
|
||||
// setting `checkUnignored` to `false` could reduce additional
|
||||
// path matching.
|
||||
|
||||
// @returns {TestResult} true if a file is ignored
|
||||
}, {
|
||||
key: "_testOne",
|
||||
value: function _testOne(path, checkUnignored) {
|
||||
var ignored = false;
|
||||
var unignored = false;
|
||||
this._rules.forEach(function (rule) {
|
||||
var negative = rule.negative;
|
||||
if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
|
||||
return;
|
||||
}
|
||||
var matched = rule.regex.test(path);
|
||||
if (matched) {
|
||||
ignored = !negative;
|
||||
unignored = negative;
|
||||
}
|
||||
});
|
||||
return {
|
||||
ignored: ignored,
|
||||
unignored: unignored
|
||||
};
|
||||
}
|
||||
|
||||
// @returns {TestResult}
|
||||
}, {
|
||||
key: "_test",
|
||||
value: function _test(originalPath, cache, checkUnignored, slices) {
|
||||
var path = originalPath
|
||||
// Supports nullable path
|
||||
&& checkPath.convert(originalPath);
|
||||
checkPath(path, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
|
||||
return this._t(path, cache, checkUnignored, slices);
|
||||
}
|
||||
}, {
|
||||
key: "_t",
|
||||
value: function _t(path, cache, checkUnignored, slices) {
|
||||
if (path in cache) {
|
||||
return cache[path];
|
||||
}
|
||||
if (!slices) {
|
||||
// path/to/a.js
|
||||
// ['path', 'to', 'a.js']
|
||||
slices = path.split(SLASH);
|
||||
}
|
||||
slices.pop();
|
||||
|
||||
// If the path has no parent directory, just test it
|
||||
if (!slices.length) {
|
||||
return cache[path] = this._testOne(path, checkUnignored);
|
||||
}
|
||||
var parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices);
|
||||
|
||||
// If the path contains a parent directory, check the parent first
|
||||
return cache[path] = parent.ignored
|
||||
// > It is not possible to re-include a file if a parent directory of
|
||||
// > that file is excluded.
|
||||
? parent : this._testOne(path, checkUnignored);
|
||||
}
|
||||
}, {
|
||||
key: "ignores",
|
||||
value: function ignores(path) {
|
||||
return this._test(path, this._ignoreCache, false).ignored;
|
||||
}
|
||||
}, {
|
||||
key: "createFilter",
|
||||
value: function createFilter() {
|
||||
var _this = this;
|
||||
return function (path) {
|
||||
return !_this.ignores(path);
|
||||
};
|
||||
}
|
||||
}, {
|
||||
key: "filter",
|
||||
value: function filter(paths) {
|
||||
return makeArray(paths).filter(this.createFilter());
|
||||
}
|
||||
|
||||
// @returns {TestResult}
|
||||
}, {
|
||||
key: "test",
|
||||
value: function test(path) {
|
||||
return this._test(path, this._testCache, true);
|
||||
}
|
||||
}]);
|
||||
return Ignore;
|
||||
}();
|
||||
var factory = function factory(options) {
|
||||
return new Ignore(options);
|
||||
};
|
||||
var isPathValid = function isPathValid(path) {
|
||||
return checkPath(path && checkPath.convert(path), path, RETURN_FALSE);
|
||||
};
|
||||
factory.isPathValid = isPathValid;
|
||||
|
||||
// Fixes typescript
|
||||
factory["default"] = factory;
|
||||
module.exports = factory;
|
||||
|
||||
// Windows
|
||||
// --------------------------------------------------------------
|
||||
/* istanbul ignore if */
|
||||
if (
|
||||
// Detect `process` so that it can run in browsers.
|
||||
typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
|
||||
/* eslint no-control-regex: "off" */
|
||||
var makePosix = function makePosix(str) {
|
||||
return /^\\\\\?\\/.test(str) || /[\0-\x1F"<>\|]+/.test(str) ? str : str.replace(/\\/g, '/');
|
||||
};
|
||||
checkPath.convert = makePosix;
|
||||
|
||||
// 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'
|
||||
// 'd:\\foo'
|
||||
var REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
|
||||
checkPath.isNotRelative = function (path) {
|
||||
return REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,810 @@
|
||||
'use strict'
|
||||
|
||||
const { describe, test } = require('node:test')
|
||||
const assert = require('node:assert')
|
||||
const tspl = require('@matteo.collina/tspl')
|
||||
|
||||
const { sink, once, check } = require('./helper')
|
||||
const pino = require('../')
|
||||
|
||||
const levelsLib = require('../lib/levels')
|
||||
|
||||
// Silence all warnings for this test
|
||||
process.removeAllListeners('warning')
|
||||
process.on('warning', () => {})
|
||||
|
||||
test('set the level by string', async () => {
|
||||
const expected = [{
|
||||
level: 50,
|
||||
msg: 'this is an error'
|
||||
}, {
|
||||
level: 60,
|
||||
msg: 'this is fatal'
|
||||
}]
|
||||
const stream = sink()
|
||||
const instance = pino(stream)
|
||||
instance.level = 'error'
|
||||
instance.info('hello world')
|
||||
instance.error('this is an error')
|
||||
instance.fatal('this is fatal')
|
||||
const result = await once(stream, 'data')
|
||||
const current = expected.shift()
|
||||
check(assert.equal, result, current.level, current.msg)
|
||||
})
|
||||
|
||||
test('the wrong level throws', async () => {
|
||||
const instance = pino()
|
||||
assert.throws(() => {
|
||||
instance.level = 'kaboom'
|
||||
})
|
||||
})
|
||||
|
||||
test('set the level by number', async () => {
|
||||
const expected = [{
|
||||
level: 50,
|
||||
msg: 'this is an error'
|
||||
}, {
|
||||
level: 60,
|
||||
msg: 'this is fatal'
|
||||
}]
|
||||
const stream = sink()
|
||||
const instance = pino(stream)
|
||||
|
||||
instance.level = 50
|
||||
instance.info('hello world')
|
||||
instance.error('this is an error')
|
||||
instance.fatal('this is fatal')
|
||||
const result = await once(stream, 'data')
|
||||
const current = expected.shift()
|
||||
check(assert.equal, result, current.level, current.msg)
|
||||
})
|
||||
|
||||
test('exposes level string mappings', async () => {
|
||||
assert.equal(pino.levels.values.error, 50)
|
||||
})
|
||||
|
||||
test('exposes level number mappings', async () => {
|
||||
assert.equal(pino.levels.labels[50], 'error')
|
||||
})
|
||||
|
||||
test('returns level integer', async () => {
|
||||
const instance = pino({ level: 'error' })
|
||||
assert.equal(instance.levelVal, 50)
|
||||
})
|
||||
|
||||
test('child returns level integer', async () => {
|
||||
const parent = pino({ level: 'error' })
|
||||
const child = parent.child({ foo: 'bar' })
|
||||
assert.equal(child.levelVal, 50)
|
||||
})
|
||||
|
||||
test('set the level via exported pino function', async () => {
|
||||
const expected = [{
|
||||
level: 50,
|
||||
msg: 'this is an error'
|
||||
}, {
|
||||
level: 60,
|
||||
msg: 'this is fatal'
|
||||
}]
|
||||
const stream = sink()
|
||||
const instance = pino({ level: 'error' }, stream)
|
||||
|
||||
instance.info('hello world')
|
||||
instance.error('this is an error')
|
||||
instance.fatal('this is fatal')
|
||||
const result = await once(stream, 'data')
|
||||
const current = expected.shift()
|
||||
check(assert.equal, result, current.level, current.msg)
|
||||
})
|
||||
|
||||
test('level-change event', async (t) => {
|
||||
const plan = tspl(t, { plan: 8 })
|
||||
const instance = pino()
|
||||
function handle (lvl, val, prevLvl, prevVal, logger) {
|
||||
plan.equal(lvl, 'trace')
|
||||
plan.equal(val, 10)
|
||||
plan.equal(prevLvl, 'info')
|
||||
plan.equal(prevVal, 30)
|
||||
plan.equal(logger, instance)
|
||||
}
|
||||
instance.on('level-change', handle)
|
||||
instance.level = 'trace'
|
||||
instance.removeListener('level-change', handle)
|
||||
instance.level = 'info'
|
||||
|
||||
let count = 0
|
||||
|
||||
const l1 = () => count++
|
||||
const l2 = () => count++
|
||||
const l3 = () => count++
|
||||
instance.on('level-change', l1)
|
||||
instance.on('level-change', l2)
|
||||
instance.on('level-change', l3)
|
||||
|
||||
instance.level = 'trace'
|
||||
instance.removeListener('level-change', l3)
|
||||
instance.level = 'fatal'
|
||||
instance.removeListener('level-change', l1)
|
||||
instance.level = 'debug'
|
||||
instance.removeListener('level-change', l2)
|
||||
instance.level = 'info'
|
||||
|
||||
plan.equal(count, 6)
|
||||
|
||||
instance.once('level-change', (lvl, val, prevLvl, prevVal, logger) => plan.equal(logger, instance))
|
||||
instance.level = 'info'
|
||||
const child = instance.child({})
|
||||
instance.once('level-change', (lvl, val, prevLvl, prevVal, logger) => plan.equal(logger, child))
|
||||
child.level = 'trace'
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('enable', async (t) => {
|
||||
const instance = pino({
|
||||
level: 'trace',
|
||||
enabled: false
|
||||
}, sink((result, enc) => {
|
||||
throw Error('no data should be logged')
|
||||
}))
|
||||
|
||||
Object.keys(pino.levels.values).forEach((level) => {
|
||||
instance[level]('hello world')
|
||||
})
|
||||
})
|
||||
|
||||
test('silent level', async () => {
|
||||
const instance = pino({
|
||||
level: 'silent'
|
||||
}, sink((result, enc) => {
|
||||
throw Error('no data should be logged')
|
||||
}))
|
||||
|
||||
Object.keys(pino.levels.values).forEach((level) => {
|
||||
instance[level]('hello world')
|
||||
})
|
||||
})
|
||||
|
||||
test('set silent via Infinity', async () => {
|
||||
const instance = pino({
|
||||
level: Infinity
|
||||
}, sink((result, enc) => {
|
||||
throw Error('no data should be logged')
|
||||
}))
|
||||
|
||||
Object.keys(pino.levels.values).forEach((level) => {
|
||||
instance[level]('hello world')
|
||||
})
|
||||
})
|
||||
|
||||
test('exposed levels', async () => {
|
||||
assert.deepEqual(Object.keys(pino.levels.values), [
|
||||
'trace',
|
||||
'debug',
|
||||
'info',
|
||||
'warn',
|
||||
'error',
|
||||
'fatal'
|
||||
])
|
||||
})
|
||||
|
||||
test('exposed labels', async () => {
|
||||
assert.deepEqual(Object.keys(pino.levels.labels), [
|
||||
'10',
|
||||
'20',
|
||||
'30',
|
||||
'40',
|
||||
'50',
|
||||
'60'
|
||||
])
|
||||
})
|
||||
|
||||
test('setting level in child', async (t) => {
|
||||
const plan = tspl(t, { plan: 10 })
|
||||
const expected = [{
|
||||
level: 50,
|
||||
msg: 'this is an error'
|
||||
}, {
|
||||
level: 60,
|
||||
msg: 'this is fatal'
|
||||
}]
|
||||
const instance = pino(sink((result, enc, cb) => {
|
||||
const current = expected.shift()
|
||||
check(plan.equal, result, current.level, current.msg)
|
||||
cb()
|
||||
})).child({ level: 30 })
|
||||
|
||||
instance.level = 'error'
|
||||
instance.info('hello world')
|
||||
instance.error('this is an error')
|
||||
instance.fatal('this is fatal')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('setting level by assigning a number to level', async () => {
|
||||
const instance = pino()
|
||||
assert.equal(instance.levelVal, 30)
|
||||
assert.equal(instance.level, 'info')
|
||||
instance.level = 50
|
||||
assert.equal(instance.levelVal, 50)
|
||||
assert.equal(instance.level, 'error')
|
||||
})
|
||||
|
||||
test('setting level by number to unknown value results in a throw', async () => {
|
||||
const instance = pino()
|
||||
assert.throws(() => { instance.level = 973 })
|
||||
})
|
||||
|
||||
test('setting level by assigning a known label to level', async () => {
|
||||
const instance = pino()
|
||||
assert.equal(instance.levelVal, 30)
|
||||
assert.equal(instance.level, 'info')
|
||||
instance.level = 'error'
|
||||
assert.equal(instance.levelVal, 50)
|
||||
assert.equal(instance.level, 'error')
|
||||
})
|
||||
|
||||
test('levelVal is read only', async () => {
|
||||
const instance = pino()
|
||||
assert.throws(() => { instance.levelVal = 20 })
|
||||
})
|
||||
|
||||
test('produces labels when told to', async (t) => {
|
||||
const plan = tspl(t, { plan: 5 })
|
||||
const expected = [{
|
||||
level: 'info',
|
||||
msg: 'hello world'
|
||||
}]
|
||||
const instance = pino({
|
||||
formatters: {
|
||||
level (label, number) {
|
||||
return { level: label }
|
||||
}
|
||||
}
|
||||
}, sink((result, enc, cb) => {
|
||||
const current = expected.shift()
|
||||
check(plan.equal, result, current.level, current.msg)
|
||||
cb()
|
||||
}))
|
||||
|
||||
instance.info('hello world')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('resets levels from labels to numbers', async (t) => {
|
||||
const plan = tspl(t, { plan: 5 })
|
||||
const expected = [{
|
||||
level: 30,
|
||||
msg: 'hello world'
|
||||
}]
|
||||
pino({ useLevelLabels: true })
|
||||
const instance = pino({ useLevelLabels: false }, sink((result, enc, cb) => {
|
||||
const current = expected.shift()
|
||||
check(plan.equal, result, current.level, current.msg)
|
||||
cb()
|
||||
}))
|
||||
|
||||
instance.info('hello world')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('changes label naming when told to', async (t) => {
|
||||
const plan = tspl(t, { plan: 2 })
|
||||
const expected = [{
|
||||
priority: 30,
|
||||
msg: 'hello world'
|
||||
}]
|
||||
const instance = pino({
|
||||
formatters: {
|
||||
level (label, number) {
|
||||
return { priority: number }
|
||||
}
|
||||
}
|
||||
}, sink((result, enc, cb) => {
|
||||
const current = expected.shift()
|
||||
plan.equal(result.priority, current.priority)
|
||||
plan.equal(result.msg, current.msg)
|
||||
cb()
|
||||
}))
|
||||
|
||||
instance.info('hello world')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('children produce labels when told to', async (t) => {
|
||||
const plan = tspl(t, { plan: 10 })
|
||||
const expected = [
|
||||
{
|
||||
level: 'info',
|
||||
msg: 'child 1'
|
||||
},
|
||||
{
|
||||
level: 'info',
|
||||
msg: 'child 2'
|
||||
}
|
||||
]
|
||||
const instance = pino({
|
||||
formatters: {
|
||||
level (label, number) {
|
||||
return { level: label }
|
||||
}
|
||||
}
|
||||
}, sink((result, enc, cb) => {
|
||||
const current = expected.shift()
|
||||
check(plan.equal, result, current.level, current.msg)
|
||||
cb()
|
||||
}))
|
||||
|
||||
const child1 = instance.child({ name: 'child1' })
|
||||
const child2 = child1.child({ name: 'child2' })
|
||||
|
||||
child1.info('child 1')
|
||||
child2.info('child 2')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('produces labels for custom levels', async (t) => {
|
||||
const plan = tspl(t, { plan: 10 })
|
||||
const expected = [
|
||||
{
|
||||
level: 'info',
|
||||
msg: 'hello world'
|
||||
},
|
||||
{
|
||||
level: 'foo',
|
||||
msg: 'foobar'
|
||||
}
|
||||
]
|
||||
const opts = {
|
||||
formatters: {
|
||||
level (label, number) {
|
||||
return { level: label }
|
||||
}
|
||||
},
|
||||
customLevels: {
|
||||
foo: 35
|
||||
}
|
||||
}
|
||||
const instance = pino(opts, sink((result, enc, cb) => {
|
||||
const current = expected.shift()
|
||||
check(plan.equal, result, current.level, current.msg)
|
||||
cb()
|
||||
}))
|
||||
|
||||
instance.info('hello world')
|
||||
instance.foo('foobar')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('setting levelKey does not affect labels when told to', async (t) => {
|
||||
const plan = tspl(t, { plan: 1 })
|
||||
const instance = pino(
|
||||
{
|
||||
formatters: {
|
||||
level (label, number) {
|
||||
return { priority: label }
|
||||
}
|
||||
}
|
||||
},
|
||||
sink((result, enc, cb) => {
|
||||
plan.equal(result.priority, 'info')
|
||||
cb()
|
||||
})
|
||||
)
|
||||
|
||||
instance.info('hello world')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('throws when creating a default label that does not exist in logger levels', async () => {
|
||||
const defaultLevel = 'foo'
|
||||
assert.throws(
|
||||
() => {
|
||||
pino({
|
||||
customLevels: {
|
||||
bar: 5
|
||||
},
|
||||
level: defaultLevel
|
||||
})
|
||||
},
|
||||
Error(`default level:${defaultLevel} must be included in custom levels`)
|
||||
)
|
||||
})
|
||||
|
||||
test('throws when creating a default value that does not exist in logger levels', async () => {
|
||||
const defaultLevel = 15
|
||||
assert.throws(
|
||||
() => {
|
||||
pino({
|
||||
customLevels: {
|
||||
bar: 5
|
||||
},
|
||||
level: defaultLevel
|
||||
})
|
||||
},
|
||||
Error(`default level:${defaultLevel} must be included in custom levels`)
|
||||
)
|
||||
})
|
||||
|
||||
test('throws when creating a default value that does not exist in logger levels', async ({ equal, throws }) => {
|
||||
assert.throws(
|
||||
() => {
|
||||
pino({
|
||||
customLevels: {
|
||||
foo: 5
|
||||
},
|
||||
useOnlyCustomLevels: true
|
||||
})
|
||||
},
|
||||
/default level:info must be included in custom levels/
|
||||
)
|
||||
})
|
||||
|
||||
test('passes when creating a default value that exists in logger levels', async () => {
|
||||
pino({
|
||||
level: 30
|
||||
})
|
||||
})
|
||||
|
||||
test('log null value when message is null', async () => {
|
||||
const expected = {
|
||||
msg: null,
|
||||
level: 30
|
||||
}
|
||||
|
||||
const stream = sink()
|
||||
const instance = pino(stream)
|
||||
instance.level = 'info'
|
||||
instance.info(null)
|
||||
|
||||
const result = await once(stream, 'data')
|
||||
check(assert.equal, result, expected.level, expected.msg)
|
||||
})
|
||||
|
||||
test('formats when base param is null', async () => {
|
||||
const expected = {
|
||||
msg: 'a string',
|
||||
level: 30
|
||||
}
|
||||
|
||||
const stream = sink()
|
||||
const instance = pino(stream)
|
||||
instance.level = 'info'
|
||||
instance.info(null, 'a %s', 'string')
|
||||
|
||||
const result = await once(stream, 'data')
|
||||
check(assert.equal, result, expected.level, expected.msg)
|
||||
})
|
||||
|
||||
test('fatal method sync-flushes the destination if sync flushing is available', async (t) => {
|
||||
const plan = tspl(t, { plan: 2 })
|
||||
const stream = sink()
|
||||
stream.flushSync = () => {
|
||||
plan.ok('destination flushed')
|
||||
}
|
||||
const instance = pino(stream)
|
||||
instance.fatal('this is fatal')
|
||||
await once(stream, 'data')
|
||||
plan.doesNotThrow(() => {
|
||||
stream.flushSync = undefined
|
||||
instance.fatal('this is fatal')
|
||||
})
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('fatal method should call async when sync-flushing fails', async (t) => {
|
||||
const plan = tspl(t, { plan: 1 })
|
||||
const messages = [
|
||||
'this is fatal 1'
|
||||
]
|
||||
const stream = sink((result) => assert.equal(result.msg, messages.shift()))
|
||||
stream.flushSync = () => { throw new Error('Error') }
|
||||
stream.flush = () => { throw Error('flush should be called') }
|
||||
|
||||
const instance = pino(stream)
|
||||
plan.doesNotThrow(() => instance.fatal(messages[0]))
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('calling silent method on logger instance', async () => {
|
||||
const instance = pino({ level: 'silent' }, sink((result, enc) => {
|
||||
throw Error('no data should be logged')
|
||||
}))
|
||||
instance.silent('hello world')
|
||||
})
|
||||
|
||||
test('calling silent method on child logger', async () => {
|
||||
const child = pino({ level: 'silent' }, sink((result, enc) => {
|
||||
throw Error('no data should be logged')
|
||||
})).child({})
|
||||
child.silent('hello world')
|
||||
})
|
||||
|
||||
test('changing level from info to silent and back to info', async () => {
|
||||
const expected = {
|
||||
level: 30,
|
||||
msg: 'hello world'
|
||||
}
|
||||
const stream = sink()
|
||||
const instance = pino({ level: 'info' }, stream)
|
||||
|
||||
instance.level = 'silent'
|
||||
instance.info('hello world')
|
||||
let result = stream.read()
|
||||
assert.equal(result, null)
|
||||
|
||||
instance.level = 'info'
|
||||
instance.info('hello world')
|
||||
result = await once(stream, 'data')
|
||||
check(assert.equal, result, expected.level, expected.msg)
|
||||
})
|
||||
|
||||
test('changing level from info to silent and back to info in child logger', async () => {
|
||||
const expected = {
|
||||
level: 30,
|
||||
msg: 'hello world'
|
||||
}
|
||||
const stream = sink()
|
||||
const child = pino({ level: 'info' }, stream).child({})
|
||||
|
||||
child.level = 'silent'
|
||||
child.info('hello world')
|
||||
let result = stream.read()
|
||||
assert.equal(result, null)
|
||||
|
||||
child.level = 'info'
|
||||
child.info('hello world')
|
||||
result = await once(stream, 'data')
|
||||
check(assert.equal, result, expected.level, expected.msg)
|
||||
})
|
||||
|
||||
describe('changing level respects level comparison set to', () => {
|
||||
const ascLevels = {
|
||||
debug: 1,
|
||||
info: 2,
|
||||
warn: 3
|
||||
}
|
||||
|
||||
const descLevels = {
|
||||
debug: 3,
|
||||
info: 2,
|
||||
warn: 1
|
||||
}
|
||||
|
||||
const expected = {
|
||||
level: 2,
|
||||
msg: 'hello world'
|
||||
}
|
||||
|
||||
test('ASC in parent logger', async () => {
|
||||
const customLevels = ascLevels
|
||||
const levelComparison = 'ASC'
|
||||
|
||||
const stream = sink()
|
||||
const logger = pino({ levelComparison, customLevels, useOnlyCustomLevels: true, level: 'info' }, stream)
|
||||
|
||||
logger.level = 'warn'
|
||||
logger.info('hello world')
|
||||
let result = stream.read()
|
||||
assert.equal(result, null)
|
||||
|
||||
logger.level = 'debug'
|
||||
logger.info('hello world')
|
||||
result = await once(stream, 'data')
|
||||
check(assert.equal, result, expected.level, expected.msg)
|
||||
})
|
||||
|
||||
test('DESC in parent logger', async () => {
|
||||
const customLevels = descLevels
|
||||
const levelComparison = 'DESC'
|
||||
|
||||
const stream = sink()
|
||||
const logger = pino({ levelComparison, customLevels, useOnlyCustomLevels: true, level: 'info' }, stream)
|
||||
|
||||
logger.level = 'warn'
|
||||
logger.info('hello world')
|
||||
let result = stream.read()
|
||||
assert.equal(result, null)
|
||||
|
||||
logger.level = 'debug'
|
||||
logger.info('hello world')
|
||||
result = await once(stream, 'data')
|
||||
check(assert.equal, result, expected.level, expected.msg)
|
||||
})
|
||||
|
||||
test('custom function in parent logger', async () => {
|
||||
const customLevels = {
|
||||
info: 2,
|
||||
debug: 345,
|
||||
warn: 789
|
||||
}
|
||||
const levelComparison = (current, expected) => {
|
||||
if (expected === customLevels.warn) return false
|
||||
return true
|
||||
}
|
||||
|
||||
const stream = sink()
|
||||
const logger = pino({ levelComparison, customLevels, useOnlyCustomLevels: true, level: 'info' }, stream)
|
||||
|
||||
logger.level = 'warn'
|
||||
logger.info('hello world')
|
||||
let result = stream.read()
|
||||
assert.equal(result, null)
|
||||
|
||||
logger.level = 'debug'
|
||||
logger.info('hello world')
|
||||
result = await once(stream, 'data')
|
||||
check(assert.equal, result, expected.level, expected.msg)
|
||||
})
|
||||
|
||||
test('ASC in child logger', async () => {
|
||||
const customLevels = ascLevels
|
||||
const levelComparison = 'ASC'
|
||||
|
||||
const stream = sink()
|
||||
const logger = pino({ levelComparison, customLevels, useOnlyCustomLevels: true, level: 'info' }, stream).child({ })
|
||||
|
||||
logger.level = 'warn'
|
||||
logger.info('hello world')
|
||||
let result = stream.read()
|
||||
assert.equal(result, null)
|
||||
|
||||
logger.level = 'debug'
|
||||
logger.info('hello world')
|
||||
result = await once(stream, 'data')
|
||||
check(assert.equal, result, expected.level, expected.msg)
|
||||
})
|
||||
|
||||
test('DESC in parent logger', async () => {
|
||||
const customLevels = descLevels
|
||||
const levelComparison = 'DESC'
|
||||
|
||||
const stream = sink()
|
||||
const logger = pino({ levelComparison, customLevels, useOnlyCustomLevels: true, level: 'info' }, stream).child({ })
|
||||
|
||||
logger.level = 'warn'
|
||||
logger.info('hello world')
|
||||
let result = stream.read()
|
||||
assert.equal(result, null)
|
||||
|
||||
logger.level = 'debug'
|
||||
logger.info('hello world')
|
||||
result = await once(stream, 'data')
|
||||
check(assert.equal, result, expected.level, expected.msg)
|
||||
})
|
||||
|
||||
test('custom function in child logger', async () => {
|
||||
const customLevels = {
|
||||
info: 2,
|
||||
debug: 345,
|
||||
warn: 789
|
||||
}
|
||||
const levelComparison = (current, expected) => {
|
||||
if (expected === customLevels.warn) return false
|
||||
return true
|
||||
}
|
||||
|
||||
const stream = sink()
|
||||
const logger = pino({ levelComparison, customLevels, useOnlyCustomLevels: true, level: 'info' }, stream).child({ })
|
||||
|
||||
logger.level = 'warn'
|
||||
logger.info('hello world')
|
||||
let result = stream.read()
|
||||
assert.equal(result, null)
|
||||
|
||||
logger.level = 'debug'
|
||||
logger.info('hello world')
|
||||
result = await once(stream, 'data')
|
||||
check(assert.equal, result, expected.level, expected.msg)
|
||||
})
|
||||
})
|
||||
|
||||
test('changing level respects level comparison DESC', async () => {
|
||||
const customLevels = {
|
||||
warn: 1,
|
||||
info: 2,
|
||||
debug: 3
|
||||
}
|
||||
|
||||
const levelComparison = 'DESC'
|
||||
|
||||
const expected = {
|
||||
level: 2,
|
||||
msg: 'hello world'
|
||||
}
|
||||
|
||||
const stream = sink()
|
||||
const logger = pino({ levelComparison, customLevels, useOnlyCustomLevels: true, level: 'info' }, stream)
|
||||
|
||||
logger.level = 'warn'
|
||||
logger.info('hello world')
|
||||
let result = stream.read()
|
||||
assert.equal(result, null)
|
||||
|
||||
logger.level = 'debug'
|
||||
logger.info('hello world')
|
||||
result = await once(stream, 'data')
|
||||
check(assert.equal, result, expected.level, expected.msg)
|
||||
})
|
||||
|
||||
// testing for potential loss of Pino constructor scope from serializers - an edge case with circular refs see: https://github.com/pinojs/pino/issues/833
|
||||
test('trying to get levels when `this` is no longer a Pino instance returns an empty string', async () => {
|
||||
const notPinoInstance = { some: 'object', getLevel: levelsLib.getLevel }
|
||||
const blankedLevelValue = notPinoInstance.getLevel()
|
||||
assert.equal(blankedLevelValue, '')
|
||||
})
|
||||
|
||||
test('accepts capital letter for INFO level', async () => {
|
||||
const stream = sink()
|
||||
const logger = pino({
|
||||
level: 'INFO'
|
||||
}, stream)
|
||||
|
||||
logger.info('test')
|
||||
const { level } = await once(stream, 'data')
|
||||
assert.equal(level, 30)
|
||||
})
|
||||
|
||||
test('accepts capital letter for FATAL level', async () => {
|
||||
const stream = sink()
|
||||
const logger = pino({
|
||||
level: 'FATAL'
|
||||
}, stream)
|
||||
|
||||
logger.fatal('test')
|
||||
const { level } = await once(stream, 'data')
|
||||
assert.equal(level, 60)
|
||||
})
|
||||
|
||||
test('accepts capital letter for ERROR level', async () => {
|
||||
const stream = sink()
|
||||
const logger = pino({
|
||||
level: 'ERROR'
|
||||
}, stream)
|
||||
|
||||
logger.error('test')
|
||||
const { level } = await once(stream, 'data')
|
||||
assert.equal(level, 50)
|
||||
})
|
||||
|
||||
test('accepts capital letter for WARN level', async () => {
|
||||
const stream = sink()
|
||||
const logger = pino({
|
||||
level: 'WARN'
|
||||
}, stream)
|
||||
|
||||
logger.warn('test')
|
||||
const { level } = await once(stream, 'data')
|
||||
assert.equal(level, 40)
|
||||
})
|
||||
|
||||
test('accepts capital letter for DEBUG level', async () => {
|
||||
const stream = sink()
|
||||
const logger = pino({
|
||||
level: 'DEBUG'
|
||||
}, stream)
|
||||
|
||||
logger.debug('test')
|
||||
const { level } = await once(stream, 'data')
|
||||
assert.equal(level, 20)
|
||||
})
|
||||
|
||||
test('accepts capital letter for TRACE level', async () => {
|
||||
const stream = sink()
|
||||
const logger = pino({
|
||||
level: 'TRACE'
|
||||
}, stream)
|
||||
|
||||
logger.trace('test')
|
||||
const { level } = await once(stream, 'data')
|
||||
assert.equal(level, 10)
|
||||
})
|
||||
@@ -0,0 +1,2 @@
|
||||
import type { LibDefinition } from '../variable';
|
||||
export declare const es2020: LibDefinition;
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"blake3.d.ts","sourceRoot":"","sources":["../src/blake3.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,MAAM,EAAY,MAAM,aAAa,CAAC;AAE/C,OAAO,EAGL,KAAK,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,KAAK,EACvC,MAAM,YAAY,CAAC;AAwBpB;;;;;;GAMG;AACH,MAAM,MAAM,UAAU,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,KAAK,CAAC;IAAC,OAAO,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAE1E,+CAA+C;AAC/C,qBAAa,MAAO,SAAQ,MAAM,CAAC,MAAM,CAAE,YAAW,OAAO,CAAC,MAAM,CAAC;IACnE,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,EAAE,CAAc;IACxB,OAAO,CAAC,KAAK,CAAc;IAC3B,OAAO,CAAC,KAAK,CAAqB;IAElC,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,SAAS,CAAa;IAC9B,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,SAAS,CAAQ;gBAEb,IAAI,GAAE,UAAe,EAAE,KAAK,SAAI;IA2B5C,SAAS,CAAC,GAAG,IAAI,EAAE;IAGnB,SAAS,CAAC,GAAG,IAAI,IAAI;IACrB,OAAO,CAAC,UAAU;IAmBlB,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,GAAE,MAAU,EAAE,MAAM,GAAE,OAAe,GAAG,IAAI;IAiCvF,UAAU,CAAC,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM;IAe/B,OAAO,IAAI,IAAI;IAMf,OAAO,CAAC,aAAa;IA+BrB,SAAS,CAAC,MAAM,IAAI,IAAI;IAoBxB,OAAO,CAAC,SAAS;IAcjB,OAAO,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU;IAIpC,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU;IAI9B,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU;IAQvC,MAAM,IAAI,UAAU;CAGrB;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,MAAM,EAAE,OAEpB,CAAC"}
|
||||
@@ -0,0 +1,767 @@
|
||||
import * as core from "../core/index.js";
|
||||
import { util } from "../core/index.js";
|
||||
import type { StandardSchemaWithJSONProps } from "../core/standard-schema.js";
|
||||
import * as parse from "./parse.js";
|
||||
export type ZodStandardSchemaWithJSON<T> = StandardSchemaWithJSONProps<core.input<T>, core.output<T>>;
|
||||
export interface ZodType<out Output = unknown, out Input = unknown, out Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> extends core.$ZodType<Output, Input, Internals> {
|
||||
def: Internals["def"];
|
||||
type: Internals["def"]["type"];
|
||||
/** @deprecated Use `.def` instead. */
|
||||
_def: Internals["def"];
|
||||
/** @deprecated Use `z.output<typeof schema>` instead. */
|
||||
_output: Internals["output"];
|
||||
/** @deprecated Use `z.input<typeof schema>` instead. */
|
||||
_input: Internals["input"];
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
/** Converts this schema to a JSON Schema representation. */
|
||||
toJSONSchema(params?: core.ToJSONSchemaParams): core.ZodStandardJSONSchemaPayload<this>;
|
||||
check(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
|
||||
with(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
|
||||
clone(def?: Internals["def"], params?: {
|
||||
parent: boolean;
|
||||
}): this;
|
||||
register<R extends core.$ZodRegistry>(registry: R, ...meta: this extends R["_schema"] ? undefined extends R["_meta"] ? [core.$replace<R["_meta"], this>?] : [core.$replace<R["_meta"], this>] : ["Incompatible schema"]): this;
|
||||
brand<T extends PropertyKey = PropertyKey, Dir extends "in" | "out" | "inout" = "out">(value?: T): PropertyKey extends T ? this : core.$ZodBranded<this, T, Dir>;
|
||||
parse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
|
||||
safeParse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.output<this>>;
|
||||
parseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
|
||||
safeParseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
|
||||
spa: (data: unknown, params?: core.ParseContext<core.$ZodIssue>) => Promise<parse.ZodSafeParseResult<core.output<this>>>;
|
||||
encode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): core.input<this>;
|
||||
decode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
|
||||
encodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<core.input<this>>;
|
||||
decodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
|
||||
safeEncode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.input<this>>;
|
||||
safeDecode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.output<this>>;
|
||||
safeEncodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.input<this>>>;
|
||||
safeDecodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
|
||||
refine<Ch extends (arg: core.output<this>) => unknown | Promise<unknown>>(check: Ch, params?: string | core.$ZodCustomParams): Ch extends (arg: any) => arg is infer R ? this & ZodType<R, core.input<this>> : this;
|
||||
superRefine(refinement: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): this;
|
||||
overwrite(fn: (x: core.output<this>) => core.output<this>): this;
|
||||
optional(): ZodOptional<this>;
|
||||
exactOptional(): ZodExactOptional<this>;
|
||||
nonoptional(params?: string | core.$ZodNonOptionalParams): ZodNonOptional<this>;
|
||||
nullable(): ZodNullable<this>;
|
||||
nullish(): ZodOptional<ZodNullable<this>>;
|
||||
default(def: util.NoUndefined<core.output<this>>): ZodDefault<this>;
|
||||
default(def: () => util.NoUndefined<core.output<this>>): ZodDefault<this>;
|
||||
prefault(def: () => core.input<this>): ZodPrefault<this>;
|
||||
prefault(def: core.input<this>): ZodPrefault<this>;
|
||||
array(): ZodArray<this>;
|
||||
or<T extends core.SomeType>(option: T): ZodUnion<[this, T]>;
|
||||
and<T extends core.SomeType>(incoming: T): ZodIntersection<this, T>;
|
||||
transform<NewOut>(transform: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => NewOut | Promise<NewOut>): ZodPipe<this, ZodTransform<Awaited<NewOut>, core.output<this>>>;
|
||||
catch(def: core.output<this>): ZodCatch<this>;
|
||||
catch(def: (ctx: core.$ZodCatchCtx) => core.output<this>): ZodCatch<this>;
|
||||
pipe<T extends core.$ZodType<any, core.output<this>>>(target: T | core.$ZodType<any, core.output<this>>): ZodPipe<this, T>;
|
||||
readonly(): ZodReadonly<this>;
|
||||
/** Returns a new instance that has been registered in `z.globalRegistry` with the specified description */
|
||||
describe(description: string): this;
|
||||
description?: string;
|
||||
/** Returns the metadata associated with this instance in `z.globalRegistry` */
|
||||
meta(): core.$replace<core.GlobalMeta, this> | undefined;
|
||||
/** Returns a new instance that has been registered in `z.globalRegistry` with the specified metadata */
|
||||
meta(data: core.$replace<core.GlobalMeta, this>): this;
|
||||
/** @deprecated Try safe-parsing `undefined` (this is what `isOptional` does internally):
|
||||
*
|
||||
* ```ts
|
||||
* const schema = z.string().optional();
|
||||
* const isOptional = schema.safeParse(undefined).success; // true
|
||||
* ```
|
||||
*/
|
||||
isOptional(): boolean;
|
||||
/**
|
||||
* @deprecated Try safe-parsing `null` (this is what `isNullable` does internally):
|
||||
*
|
||||
* ```ts
|
||||
* const schema = z.string().nullable();
|
||||
* const isNullable = schema.safeParse(null).success; // true
|
||||
* ```
|
||||
*/
|
||||
isNullable(): boolean;
|
||||
apply<T>(fn: (schema: this) => T): T;
|
||||
}
|
||||
export interface _ZodType<out Internals extends core.$ZodTypeInternals = core.$ZodTypeInternals> extends ZodType<any, any, Internals> {
|
||||
}
|
||||
export declare const ZodType: core.$constructor<ZodType>;
|
||||
export interface _ZodString<T extends core.$ZodStringInternals<unknown> = core.$ZodStringInternals<unknown>> extends _ZodType<T> {
|
||||
format: string | null;
|
||||
minLength: number | null;
|
||||
maxLength: number | null;
|
||||
regex(regex: RegExp, params?: string | core.$ZodCheckRegexParams): this;
|
||||
includes(value: string, params?: string | core.$ZodCheckIncludesParams): this;
|
||||
startsWith(value: string, params?: string | core.$ZodCheckStartsWithParams): this;
|
||||
endsWith(value: string, params?: string | core.$ZodCheckEndsWithParams): this;
|
||||
min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this;
|
||||
max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this;
|
||||
length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this;
|
||||
nonempty(params?: string | core.$ZodCheckMinLengthParams): this;
|
||||
lowercase(params?: string | core.$ZodCheckLowerCaseParams): this;
|
||||
uppercase(params?: string | core.$ZodCheckUpperCaseParams): this;
|
||||
trim(): this;
|
||||
normalize(form?: "NFC" | "NFD" | "NFKC" | "NFKD" | (string & {})): this;
|
||||
toLowerCase(): this;
|
||||
toUpperCase(): this;
|
||||
slugify(): this;
|
||||
}
|
||||
/** @internal */
|
||||
export declare const _ZodString: core.$constructor<_ZodString>;
|
||||
export interface ZodString extends _ZodString<core.$ZodStringInternals<string>> {
|
||||
/** @deprecated Use `z.email()` instead. */
|
||||
email(params?: string | core.$ZodCheckEmailParams): this;
|
||||
/** @deprecated Use `z.url()` instead. */
|
||||
url(params?: string | core.$ZodCheckURLParams): this;
|
||||
/** @deprecated Use `z.jwt()` instead. */
|
||||
jwt(params?: string | core.$ZodCheckJWTParams): this;
|
||||
/** @deprecated Use `z.emoji()` instead. */
|
||||
emoji(params?: string | core.$ZodCheckEmojiParams): this;
|
||||
/** @deprecated Use `z.guid()` instead. */
|
||||
guid(params?: string | core.$ZodCheckGUIDParams): this;
|
||||
/** @deprecated Use `z.uuid()` instead. */
|
||||
uuid(params?: string | core.$ZodCheckUUIDParams): this;
|
||||
/** @deprecated Use `z.uuid()` instead. */
|
||||
uuidv4(params?: string | core.$ZodCheckUUIDParams): this;
|
||||
/** @deprecated Use `z.uuid()` instead. */
|
||||
uuidv6(params?: string | core.$ZodCheckUUIDParams): this;
|
||||
/** @deprecated Use `z.uuid()` instead. */
|
||||
uuidv7(params?: string | core.$ZodCheckUUIDParams): this;
|
||||
/** @deprecated Use `z.nanoid()` instead. */
|
||||
nanoid(params?: string | core.$ZodCheckNanoIDParams): this;
|
||||
/** @deprecated Use `z.guid()` instead. */
|
||||
guid(params?: string | core.$ZodCheckGUIDParams): this;
|
||||
/**
|
||||
* @deprecated CUID v1 is deprecated by its authors due to information leakage
|
||||
* (timestamps embedded in the id). Use `z.cuid2()` instead.
|
||||
* See https://github.com/paralleldrive/cuid.
|
||||
*/
|
||||
cuid(params?: string | core.$ZodCheckCUIDParams): this;
|
||||
/** @deprecated Use `z.cuid2()` instead. */
|
||||
cuid2(params?: string | core.$ZodCheckCUID2Params): this;
|
||||
/** @deprecated Use `z.ulid()` instead. */
|
||||
ulid(params?: string | core.$ZodCheckULIDParams): this;
|
||||
/** @deprecated Use `z.base64()` instead. */
|
||||
base64(params?: string | core.$ZodCheckBase64Params): this;
|
||||
/** @deprecated Use `z.base64url()` instead. */
|
||||
base64url(params?: string | core.$ZodCheckBase64URLParams): this;
|
||||
/** @deprecated Use `z.xid()` instead. */
|
||||
xid(params?: string | core.$ZodCheckXIDParams): this;
|
||||
/** @deprecated Use `z.ksuid()` instead. */
|
||||
ksuid(params?: string | core.$ZodCheckKSUIDParams): this;
|
||||
/** @deprecated Use `z.ipv4()` instead. */
|
||||
ipv4(params?: string | core.$ZodCheckIPv4Params): this;
|
||||
/** @deprecated Use `z.ipv6()` instead. */
|
||||
ipv6(params?: string | core.$ZodCheckIPv6Params): this;
|
||||
/** @deprecated Use `z.cidrv4()` instead. */
|
||||
cidrv4(params?: string | core.$ZodCheckCIDRv4Params): this;
|
||||
/** @deprecated Use `z.cidrv6()` instead. */
|
||||
cidrv6(params?: string | core.$ZodCheckCIDRv6Params): this;
|
||||
/** @deprecated Use `z.e164()` instead. */
|
||||
e164(params?: string | core.$ZodCheckE164Params): this;
|
||||
/** @deprecated Use `z.iso.datetime()` instead. */
|
||||
datetime(params?: string | core.$ZodCheckISODateTimeParams): this;
|
||||
/** @deprecated Use `z.iso.date()` instead. */
|
||||
date(params?: string | core.$ZodCheckISODateParams): this;
|
||||
/** @deprecated Use `z.iso.time()` instead. */
|
||||
time(params?: string | core.$ZodCheckISOTimeParams): this;
|
||||
/** @deprecated Use `z.iso.duration()` instead. */
|
||||
duration(params?: string | core.$ZodCheckISODurationParams): this;
|
||||
}
|
||||
export declare const ZodString: core.$constructor<ZodString>;
|
||||
export declare function string(params?: string | core.$ZodStringParams): ZodString;
|
||||
export declare function string<T extends string>(params?: string | core.$ZodStringParams): core.$ZodType<T, T>;
|
||||
export interface ZodStringFormat<Format extends string = string> extends _ZodString<core.$ZodStringFormatInternals<Format>> {
|
||||
}
|
||||
export declare const ZodStringFormat: core.$constructor<ZodStringFormat>;
|
||||
export interface ZodEmail extends ZodStringFormat<"email"> {
|
||||
_zod: core.$ZodEmailInternals;
|
||||
}
|
||||
export declare const ZodEmail: core.$constructor<ZodEmail>;
|
||||
export declare function email(params?: string | core.$ZodEmailParams): ZodEmail;
|
||||
export interface ZodGUID extends ZodStringFormat<"guid"> {
|
||||
_zod: core.$ZodGUIDInternals;
|
||||
}
|
||||
export declare const ZodGUID: core.$constructor<ZodGUID>;
|
||||
export declare function guid(params?: string | core.$ZodGUIDParams): ZodGUID;
|
||||
export interface ZodUUID extends ZodStringFormat<"uuid"> {
|
||||
_zod: core.$ZodUUIDInternals;
|
||||
}
|
||||
export declare const ZodUUID: core.$constructor<ZodUUID>;
|
||||
export declare function uuid(params?: string | core.$ZodUUIDParams): ZodUUID;
|
||||
export declare function uuidv4(params?: string | core.$ZodUUIDv4Params): ZodUUID;
|
||||
export declare function uuidv6(params?: string | core.$ZodUUIDv6Params): ZodUUID;
|
||||
export declare function uuidv7(params?: string | core.$ZodUUIDv7Params): ZodUUID;
|
||||
export interface ZodURL extends ZodStringFormat<"url"> {
|
||||
_zod: core.$ZodURLInternals;
|
||||
}
|
||||
export declare const ZodURL: core.$constructor<ZodURL>;
|
||||
export declare function url(params?: string | core.$ZodURLParams): ZodURL;
|
||||
export declare function httpUrl(params?: string | Omit<core.$ZodURLParams, "protocol" | "hostname">): ZodURL;
|
||||
export interface ZodEmoji extends ZodStringFormat<"emoji"> {
|
||||
_zod: core.$ZodEmojiInternals;
|
||||
}
|
||||
export declare const ZodEmoji: core.$constructor<ZodEmoji>;
|
||||
export declare function emoji(params?: string | core.$ZodEmojiParams): ZodEmoji;
|
||||
export interface ZodNanoID extends ZodStringFormat<"nanoid"> {
|
||||
_zod: core.$ZodNanoIDInternals;
|
||||
}
|
||||
export declare const ZodNanoID: core.$constructor<ZodNanoID>;
|
||||
export declare function nanoid(params?: string | core.$ZodNanoIDParams): ZodNanoID;
|
||||
/**
|
||||
* @deprecated CUID v1 is deprecated by its authors due to information leakage
|
||||
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
|
||||
* See https://github.com/paralleldrive/cuid.
|
||||
*/
|
||||
export interface ZodCUID extends ZodStringFormat<"cuid"> {
|
||||
_zod: core.$ZodCUIDInternals;
|
||||
}
|
||||
/**
|
||||
* @deprecated CUID v1 is deprecated by its authors due to information leakage
|
||||
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
|
||||
* See https://github.com/paralleldrive/cuid.
|
||||
*/
|
||||
export declare const ZodCUID: core.$constructor<ZodCUID>;
|
||||
/**
|
||||
* Validates a CUID v1 string.
|
||||
*
|
||||
* @deprecated CUID v1 is deprecated by its authors due to information leakage
|
||||
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
|
||||
* See https://github.com/paralleldrive/cuid.
|
||||
*/
|
||||
export declare function cuid(params?: string | core.$ZodCUIDParams): ZodCUID;
|
||||
export interface ZodCUID2 extends ZodStringFormat<"cuid2"> {
|
||||
_zod: core.$ZodCUID2Internals;
|
||||
}
|
||||
export declare const ZodCUID2: core.$constructor<ZodCUID2>;
|
||||
export declare function cuid2(params?: string | core.$ZodCUID2Params): ZodCUID2;
|
||||
export interface ZodULID extends ZodStringFormat<"ulid"> {
|
||||
_zod: core.$ZodULIDInternals;
|
||||
}
|
||||
export declare const ZodULID: core.$constructor<ZodULID>;
|
||||
export declare function ulid(params?: string | core.$ZodULIDParams): ZodULID;
|
||||
export interface ZodXID extends ZodStringFormat<"xid"> {
|
||||
_zod: core.$ZodXIDInternals;
|
||||
}
|
||||
export declare const ZodXID: core.$constructor<ZodXID>;
|
||||
export declare function xid(params?: string | core.$ZodXIDParams): ZodXID;
|
||||
export interface ZodKSUID extends ZodStringFormat<"ksuid"> {
|
||||
_zod: core.$ZodKSUIDInternals;
|
||||
}
|
||||
export declare const ZodKSUID: core.$constructor<ZodKSUID>;
|
||||
export declare function ksuid(params?: string | core.$ZodKSUIDParams): ZodKSUID;
|
||||
export interface ZodIPv4 extends ZodStringFormat<"ipv4"> {
|
||||
_zod: core.$ZodIPv4Internals;
|
||||
}
|
||||
export declare const ZodIPv4: core.$constructor<ZodIPv4>;
|
||||
export declare function ipv4(params?: string | core.$ZodIPv4Params): ZodIPv4;
|
||||
export interface ZodMAC extends ZodStringFormat<"mac"> {
|
||||
_zod: core.$ZodMACInternals;
|
||||
}
|
||||
export declare const ZodMAC: core.$constructor<ZodMAC>;
|
||||
export declare function mac(params?: string | core.$ZodMACParams): ZodMAC;
|
||||
export interface ZodIPv6 extends ZodStringFormat<"ipv6"> {
|
||||
_zod: core.$ZodIPv6Internals;
|
||||
}
|
||||
export declare const ZodIPv6: core.$constructor<ZodIPv6>;
|
||||
export declare function ipv6(params?: string | core.$ZodIPv6Params): ZodIPv6;
|
||||
export interface ZodCIDRv4 extends ZodStringFormat<"cidrv4"> {
|
||||
_zod: core.$ZodCIDRv4Internals;
|
||||
}
|
||||
export declare const ZodCIDRv4: core.$constructor<ZodCIDRv4>;
|
||||
export declare function cidrv4(params?: string | core.$ZodCIDRv4Params): ZodCIDRv4;
|
||||
export interface ZodCIDRv6 extends ZodStringFormat<"cidrv6"> {
|
||||
_zod: core.$ZodCIDRv6Internals;
|
||||
}
|
||||
export declare const ZodCIDRv6: core.$constructor<ZodCIDRv6>;
|
||||
export declare function cidrv6(params?: string | core.$ZodCIDRv6Params): ZodCIDRv6;
|
||||
export interface ZodBase64 extends ZodStringFormat<"base64"> {
|
||||
_zod: core.$ZodBase64Internals;
|
||||
}
|
||||
export declare const ZodBase64: core.$constructor<ZodBase64>;
|
||||
export declare function base64(params?: string | core.$ZodBase64Params): ZodBase64;
|
||||
export interface ZodBase64URL extends ZodStringFormat<"base64url"> {
|
||||
_zod: core.$ZodBase64URLInternals;
|
||||
}
|
||||
export declare const ZodBase64URL: core.$constructor<ZodBase64URL>;
|
||||
export declare function base64url(params?: string | core.$ZodBase64URLParams): ZodBase64URL;
|
||||
export interface ZodE164 extends ZodStringFormat<"e164"> {
|
||||
_zod: core.$ZodE164Internals;
|
||||
}
|
||||
export declare const ZodE164: core.$constructor<ZodE164>;
|
||||
export declare function e164(params?: string | core.$ZodE164Params): ZodE164;
|
||||
export interface ZodJWT extends ZodStringFormat<"jwt"> {
|
||||
_zod: core.$ZodJWTInternals;
|
||||
}
|
||||
export declare const ZodJWT: core.$constructor<ZodJWT>;
|
||||
export declare function jwt(params?: string | core.$ZodJWTParams): ZodJWT;
|
||||
export interface ZodCustomStringFormat<Format extends string = string> extends ZodStringFormat<Format>, core.$ZodCustomStringFormat<Format> {
|
||||
_zod: core.$ZodCustomStringFormatInternals<Format>;
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
}
|
||||
export declare const ZodCustomStringFormat: core.$constructor<ZodCustomStringFormat>;
|
||||
export declare function stringFormat<Format extends string>(format: Format, fnOrRegex: ((arg: string) => util.MaybeAsync<unknown>) | RegExp, _params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<Format>;
|
||||
export declare function hostname(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hostname">;
|
||||
export declare function hex(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hex">;
|
||||
export declare function hash<Alg extends util.HashAlgorithm, Enc extends util.HashEncoding = "hex">(alg: Alg, params?: {
|
||||
enc?: Enc;
|
||||
} & core.$ZodStringFormatParams): ZodCustomStringFormat<`${Alg}_${Enc}`>;
|
||||
export interface _ZodNumber<Internals extends core.$ZodNumberInternals = core.$ZodNumberInternals> extends _ZodType<Internals> {
|
||||
gt(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
|
||||
/** Identical to .min() */
|
||||
gte(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
|
||||
min(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
|
||||
lt(value: number, params?: string | core.$ZodCheckLessThanParams): this;
|
||||
/** Identical to .max() */
|
||||
lte(value: number, params?: string | core.$ZodCheckLessThanParams): this;
|
||||
max(value: number, params?: string | core.$ZodCheckLessThanParams): this;
|
||||
/** Consider `z.int()` instead. This API is considered *legacy*; it will never be removed but a better alternative exists. */
|
||||
int(params?: string | core.$ZodCheckNumberFormatParams): this;
|
||||
/** @deprecated This is now identical to `.int()`. Only numbers in the safe integer range are accepted. */
|
||||
safe(params?: string | core.$ZodCheckNumberFormatParams): this;
|
||||
positive(params?: string | core.$ZodCheckGreaterThanParams): this;
|
||||
nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this;
|
||||
negative(params?: string | core.$ZodCheckLessThanParams): this;
|
||||
nonpositive(params?: string | core.$ZodCheckLessThanParams): this;
|
||||
multipleOf(value: number, params?: string | core.$ZodCheckMultipleOfParams): this;
|
||||
/** @deprecated Use `.multipleOf()` instead. */
|
||||
step(value: number, params?: string | core.$ZodCheckMultipleOfParams): this;
|
||||
/** @deprecated In v4 and later, z.number() does not allow infinite values by default. This is a no-op. */
|
||||
finite(params?: unknown): this;
|
||||
minValue: number | null;
|
||||
maxValue: number | null;
|
||||
/** @deprecated Check the `format` property instead. */
|
||||
isInt: boolean;
|
||||
/** @deprecated Number schemas no longer accept infinite values, so this always returns `true`. */
|
||||
isFinite: boolean;
|
||||
format: string | null;
|
||||
}
|
||||
export interface ZodNumber extends _ZodNumber<core.$ZodNumberInternals<number>> {
|
||||
}
|
||||
export declare const ZodNumber: core.$constructor<ZodNumber>;
|
||||
export declare function number(params?: string | core.$ZodNumberParams): ZodNumber;
|
||||
export interface ZodNumberFormat extends ZodNumber {
|
||||
_zod: core.$ZodNumberFormatInternals;
|
||||
}
|
||||
export declare const ZodNumberFormat: core.$constructor<ZodNumberFormat>;
|
||||
export interface ZodInt extends ZodNumberFormat {
|
||||
}
|
||||
export declare function int(params?: string | core.$ZodCheckNumberFormatParams): ZodInt;
|
||||
export interface ZodFloat32 extends ZodNumberFormat {
|
||||
}
|
||||
export declare function float32(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat32;
|
||||
export interface ZodFloat64 extends ZodNumberFormat {
|
||||
}
|
||||
export declare function float64(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat64;
|
||||
export interface ZodInt32 extends ZodNumberFormat {
|
||||
}
|
||||
export declare function int32(params?: string | core.$ZodCheckNumberFormatParams): ZodInt32;
|
||||
export interface ZodUInt32 extends ZodNumberFormat {
|
||||
}
|
||||
export declare function uint32(params?: string | core.$ZodCheckNumberFormatParams): ZodUInt32;
|
||||
export interface _ZodBoolean<T extends core.$ZodBooleanInternals = core.$ZodBooleanInternals> extends _ZodType<T> {
|
||||
}
|
||||
export interface ZodBoolean extends _ZodBoolean<core.$ZodBooleanInternals<boolean>> {
|
||||
}
|
||||
export declare const ZodBoolean: core.$constructor<ZodBoolean>;
|
||||
export declare function boolean(params?: string | core.$ZodBooleanParams): ZodBoolean;
|
||||
export interface _ZodBigInt<T extends core.$ZodBigIntInternals = core.$ZodBigIntInternals> extends _ZodType<T> {
|
||||
gte(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
|
||||
/** Alias of `.gte()` */
|
||||
min(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
|
||||
gt(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
|
||||
/** Alias of `.lte()` */
|
||||
lte(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
|
||||
max(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
|
||||
lt(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
|
||||
positive(params?: string | core.$ZodCheckGreaterThanParams): this;
|
||||
negative(params?: string | core.$ZodCheckLessThanParams): this;
|
||||
nonpositive(params?: string | core.$ZodCheckLessThanParams): this;
|
||||
nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this;
|
||||
multipleOf(value: bigint, params?: string | core.$ZodCheckMultipleOfParams): this;
|
||||
minValue: bigint | null;
|
||||
maxValue: bigint | null;
|
||||
format: string | null;
|
||||
}
|
||||
export interface ZodBigInt extends _ZodBigInt<core.$ZodBigIntInternals<bigint>> {
|
||||
}
|
||||
export declare const ZodBigInt: core.$constructor<ZodBigInt>;
|
||||
export declare function bigint(params?: string | core.$ZodBigIntParams): ZodBigInt;
|
||||
export interface ZodBigIntFormat extends ZodBigInt {
|
||||
_zod: core.$ZodBigIntFormatInternals;
|
||||
}
|
||||
export declare const ZodBigIntFormat: core.$constructor<ZodBigIntFormat>;
|
||||
export declare function int64(params?: string | core.$ZodBigIntFormatParams): ZodBigIntFormat;
|
||||
export declare function uint64(params?: string | core.$ZodBigIntFormatParams): ZodBigIntFormat;
|
||||
export interface ZodSymbol extends _ZodType<core.$ZodSymbolInternals> {
|
||||
}
|
||||
export declare const ZodSymbol: core.$constructor<ZodSymbol>;
|
||||
export declare function symbol(params?: string | core.$ZodSymbolParams): ZodSymbol;
|
||||
export interface ZodUndefined extends _ZodType<core.$ZodUndefinedInternals> {
|
||||
}
|
||||
export declare const ZodUndefined: core.$constructor<ZodUndefined>;
|
||||
declare function _undefined(params?: string | core.$ZodUndefinedParams): ZodUndefined;
|
||||
export { _undefined as undefined };
|
||||
export interface ZodNull extends _ZodType<core.$ZodNullInternals> {
|
||||
}
|
||||
export declare const ZodNull: core.$constructor<ZodNull>;
|
||||
declare function _null(params?: string | core.$ZodNullParams): ZodNull;
|
||||
export { _null as null };
|
||||
export interface ZodAny extends _ZodType<core.$ZodAnyInternals> {
|
||||
}
|
||||
export declare const ZodAny: core.$constructor<ZodAny>;
|
||||
export declare function any(): ZodAny;
|
||||
export interface ZodUnknown extends _ZodType<core.$ZodUnknownInternals> {
|
||||
}
|
||||
export declare const ZodUnknown: core.$constructor<ZodUnknown>;
|
||||
export declare function unknown(): ZodUnknown;
|
||||
export interface ZodNever extends _ZodType<core.$ZodNeverInternals> {
|
||||
}
|
||||
export declare const ZodNever: core.$constructor<ZodNever>;
|
||||
export declare function never(params?: string | core.$ZodNeverParams): ZodNever;
|
||||
export interface ZodVoid extends _ZodType<core.$ZodVoidInternals> {
|
||||
}
|
||||
export declare const ZodVoid: core.$constructor<ZodVoid>;
|
||||
declare function _void(params?: string | core.$ZodVoidParams): ZodVoid;
|
||||
export { _void as void };
|
||||
export interface _ZodDate<T extends core.$ZodDateInternals = core.$ZodDateInternals> extends _ZodType<T> {
|
||||
min(value: number | Date, params?: string | core.$ZodCheckGreaterThanParams): this;
|
||||
max(value: number | Date, params?: string | core.$ZodCheckLessThanParams): this;
|
||||
/** @deprecated Not recommended. */
|
||||
minDate: Date | null;
|
||||
/** @deprecated Not recommended. */
|
||||
maxDate: Date | null;
|
||||
}
|
||||
export interface ZodDate extends _ZodDate<core.$ZodDateInternals<Date>> {
|
||||
}
|
||||
export declare const ZodDate: core.$constructor<ZodDate>;
|
||||
export declare function date(params?: string | core.$ZodDateParams): ZodDate;
|
||||
export interface ZodArray<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodArrayInternals<T>>, core.$ZodArray<T> {
|
||||
element: T;
|
||||
min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this;
|
||||
nonempty(params?: string | core.$ZodCheckMinLengthParams): this;
|
||||
max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this;
|
||||
length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this;
|
||||
unwrap(): T;
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
}
|
||||
export declare const ZodArray: core.$constructor<ZodArray>;
|
||||
export declare function array<T extends core.SomeType>(element: T, params?: string | core.$ZodArrayParams): ZodArray<T>;
|
||||
export declare function keyof<T extends ZodObject>(schema: T): ZodEnum<util.KeysEnum<T["_zod"]["output"]>>;
|
||||
export type SafeExtendShape<Base extends core.$ZodShape, Ext extends core.$ZodLooseShape> = {
|
||||
[K in keyof Ext]: K extends keyof Base ? core.output<Ext[K]> extends core.output<Base[K]> ? core.input<Ext[K]> extends core.input<Base[K]> ? Ext[K] : never : never : Ext[K];
|
||||
};
|
||||
export interface ZodObject<
|
||||
/** @ts-ignore Cast variance */
|
||||
out Shape extends core.$ZodShape = core.$ZodLooseShape, out Config extends core.$ZodObjectConfig = core.$strip> extends _ZodType<core.$ZodObjectInternals<Shape, Config>>, core.$ZodObject<Shape, Config> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
shape: Shape;
|
||||
keyof(): ZodEnum<util.ToEnum<keyof Shape & string>>;
|
||||
/** Define a schema to validate all unrecognized keys. This overrides the existing strict/loose behavior. */
|
||||
catchall<T extends core.SomeType>(schema: T): ZodObject<Shape, core.$catchall<T>>;
|
||||
/** @deprecated Use `z.looseObject()` or `.loose()` instead. */
|
||||
passthrough(): ZodObject<Shape, core.$loose>;
|
||||
/** Consider `z.looseObject(A.shape)` instead */
|
||||
loose(): ZodObject<Shape, core.$loose>;
|
||||
/** Consider `z.strictObject(A.shape)` instead */
|
||||
strict(): ZodObject<Shape, core.$strict>;
|
||||
/** This is the default behavior. This method call is likely unnecessary. */
|
||||
strip(): ZodObject<Shape, core.$strip>;
|
||||
extend<U extends core.$ZodLooseShape>(shape: U): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
|
||||
safeExtend<U extends core.$ZodLooseShape>(shape: SafeExtendShape<Shape, U> & Partial<Record<keyof Shape, core.SomeType>>): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
|
||||
/**
|
||||
* @deprecated Use [`A.extend(B.shape)`](https://zod.dev/api?id=extend) instead.
|
||||
*/
|
||||
merge<U extends ZodObject>(other: U): ZodObject<util.Extend<Shape, U["shape"]>, U["_zod"]["config"]>;
|
||||
pick<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Pick<Shape, Extract<keyof Shape, keyof M>>>, Config>;
|
||||
omit<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Omit<Shape, Extract<keyof Shape, keyof M>>>, Config>;
|
||||
partial(): ZodObject<{
|
||||
-readonly [k in keyof Shape]: ZodOptional<Shape[k]>;
|
||||
}, Config>;
|
||||
partial<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
|
||||
-readonly [k in keyof Shape]: k extends keyof M ? ZodOptional<Shape[k]> : Shape[k];
|
||||
}, Config>;
|
||||
required(): ZodObject<{
|
||||
-readonly [k in keyof Shape]: ZodNonOptional<Shape[k]>;
|
||||
}, Config>;
|
||||
required<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
|
||||
-readonly [k in keyof Shape]: k extends keyof M ? ZodNonOptional<Shape[k]> : Shape[k];
|
||||
}, Config>;
|
||||
}
|
||||
export declare const ZodObject: core.$constructor<ZodObject>;
|
||||
export declare function object<T extends core.$ZodLooseShape = Partial<Record<never, core.SomeType>>>(shape?: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strip>;
|
||||
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strict>;
|
||||
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$loose>;
|
||||
export interface ZodUnion<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodUnionInternals<T>>, core.$ZodUnion<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
options: T;
|
||||
}
|
||||
export declare const ZodUnion: core.$constructor<ZodUnion>;
|
||||
export declare function union<const T extends readonly core.SomeType[]>(options: T, params?: string | core.$ZodUnionParams): ZodUnion<T>;
|
||||
export interface ZodXor<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodXorInternals<T>>, core.$ZodXor<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
options: T;
|
||||
}
|
||||
export declare const ZodXor: core.$constructor<ZodXor>;
|
||||
/** Creates an exclusive union (XOR) where exactly one option must match.
|
||||
* Unlike regular unions that succeed when any option matches, xor fails if
|
||||
* zero or more than one option matches the input. */
|
||||
export declare function xor<const T extends readonly core.SomeType[]>(options: T, params?: string | core.$ZodXorParams): ZodXor<T>;
|
||||
export interface ZodDiscriminatedUnion<Options extends readonly core.SomeType[] = readonly core.$ZodType[], Disc extends string = string> extends ZodUnion<Options>, core.$ZodDiscriminatedUnion<Options, Disc> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
_zod: core.$ZodDiscriminatedUnionInternals<Options, Disc>;
|
||||
def: core.$ZodDiscriminatedUnionDef<Options, Disc>;
|
||||
}
|
||||
export declare const ZodDiscriminatedUnion: core.$constructor<ZodDiscriminatedUnion>;
|
||||
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable<Disc>, ...core.$ZodTypeDiscriminable<Disc>[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodDiscriminatedUnion<Types, Disc>;
|
||||
export interface ZodIntersection<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodIntersectionInternals<A, B>>, core.$ZodIntersection<A, B> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
}
|
||||
export declare const ZodIntersection: core.$constructor<ZodIntersection>;
|
||||
export declare function intersection<T extends core.SomeType, U extends core.SomeType>(left: T, right: U): ZodIntersection<T, U>;
|
||||
export interface ZodTuple<T extends util.TupleItems = readonly core.$ZodType[], Rest extends core.SomeType | null = core.$ZodType | null> extends _ZodType<core.$ZodTupleInternals<T, Rest>>, core.$ZodTuple<T, Rest> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
rest<Rest extends core.SomeType = core.$ZodType>(rest: Rest): ZodTuple<T, Rest>;
|
||||
}
|
||||
export declare const ZodTuple: core.$constructor<ZodTuple>;
|
||||
export declare function tuple<T extends readonly [core.SomeType, ...core.SomeType[]]>(items: T, params?: string | core.$ZodTupleParams): ZodTuple<T, null>;
|
||||
export declare function tuple<T extends readonly [core.SomeType, ...core.SomeType[]], Rest extends core.SomeType>(items: T, rest: Rest, params?: string | core.$ZodTupleParams): ZodTuple<T, Rest>;
|
||||
export declare function tuple(items: [], params?: string | core.$ZodTupleParams): ZodTuple<[], null>;
|
||||
export interface ZodRecord<Key extends core.$ZodRecordKey = core.$ZodRecordKey, Value extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodRecordInternals<Key, Value>>, core.$ZodRecord<Key, Value> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
keyType: Key;
|
||||
valueType: Value;
|
||||
}
|
||||
export declare const ZodRecord: core.$constructor<ZodRecord>;
|
||||
export declare function record<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key, Value>;
|
||||
export declare function partialRecord<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key & core.$partial, Value>;
|
||||
export declare function looseRecord<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key, Value>;
|
||||
export interface ZodMap<Key extends core.SomeType = core.$ZodType, Value extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodMapInternals<Key, Value>>, core.$ZodMap<Key, Value> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
keyType: Key;
|
||||
valueType: Value;
|
||||
min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this;
|
||||
nonempty(params?: string | core.$ZodCheckMinSizeParams): this;
|
||||
max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this;
|
||||
size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this;
|
||||
}
|
||||
export declare const ZodMap: core.$constructor<ZodMap>;
|
||||
export declare function map<Key extends core.SomeType, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodMapParams): ZodMap<Key, Value>;
|
||||
export interface ZodSet<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodSetInternals<T>>, core.$ZodSet<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this;
|
||||
nonempty(params?: string | core.$ZodCheckMinSizeParams): this;
|
||||
max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this;
|
||||
size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this;
|
||||
}
|
||||
export declare const ZodSet: core.$constructor<ZodSet>;
|
||||
export declare function set<Value extends core.SomeType>(valueType: Value, params?: string | core.$ZodSetParams): ZodSet<Value>;
|
||||
export interface ZodEnum<
|
||||
/** @ts-ignore Cast variance */
|
||||
out T extends util.EnumLike = util.EnumLike> extends _ZodType<core.$ZodEnumInternals<T>>, core.$ZodEnum<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
enum: T;
|
||||
options: Array<T[keyof T]>;
|
||||
extract<const U extends readonly (keyof T)[]>(values: U, params?: string | core.$ZodEnumParams): ZodEnum<util.Flatten<Pick<T, U[number]>>>;
|
||||
exclude<const U extends readonly (keyof T)[]>(values: U, params?: string | core.$ZodEnumParams): ZodEnum<util.Flatten<Omit<T, U[number]>>>;
|
||||
}
|
||||
export declare const ZodEnum: core.$constructor<ZodEnum>;
|
||||
declare function _enum<const T extends readonly string[]>(values: T, params?: string | core.$ZodEnumParams): ZodEnum<util.ToEnum<T[number]>>;
|
||||
declare function _enum<const T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>;
|
||||
export { _enum as enum };
|
||||
/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.
|
||||
*
|
||||
* ```ts
|
||||
* enum Colors { red, green, blue }
|
||||
* z.enum(Colors);
|
||||
* ```
|
||||
*/
|
||||
export declare function nativeEnum<T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>;
|
||||
export interface ZodLiteral<T extends util.Literal = util.Literal> extends _ZodType<core.$ZodLiteralInternals<T>>, core.$ZodLiteral<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
values: Set<T>;
|
||||
/** @legacy Use `.values` instead. Accessing this property will throw an error if the literal accepts multiple values. */
|
||||
value: T;
|
||||
}
|
||||
export declare const ZodLiteral: core.$constructor<ZodLiteral>;
|
||||
export declare function literal<const T extends ReadonlyArray<util.Literal>>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T[number]>;
|
||||
export declare function literal<const T extends util.Literal>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T>;
|
||||
export interface ZodFile extends _ZodType<core.$ZodFileInternals>, core.$ZodFile {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
min(size: number, params?: string | core.$ZodCheckMinSizeParams): this;
|
||||
max(size: number, params?: string | core.$ZodCheckMaxSizeParams): this;
|
||||
mime(types: util.MimeTypes | Array<util.MimeTypes>, params?: string | core.$ZodCheckMimeTypeParams): this;
|
||||
}
|
||||
export declare const ZodFile: core.$constructor<ZodFile>;
|
||||
export declare function file(params?: string | core.$ZodFileParams): ZodFile;
|
||||
export interface ZodTransform<O = unknown, I = unknown> extends _ZodType<core.$ZodTransformInternals<O, I>>, core.$ZodTransform<O, I> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
}
|
||||
export declare const ZodTransform: core.$constructor<ZodTransform>;
|
||||
export declare function transform<I = unknown, O = I>(fn: (input: I, ctx: core.$RefinementCtx) => O): ZodTransform<Awaited<O>, I>;
|
||||
export interface ZodOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodOptionalInternals<T>>, core.$ZodOptional<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
unwrap(): T;
|
||||
}
|
||||
export declare const ZodOptional: core.$constructor<ZodOptional>;
|
||||
export declare function optional<T extends core.SomeType>(innerType: T): ZodOptional<T>;
|
||||
export interface ZodExactOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodExactOptionalInternals<T>>, core.$ZodExactOptional<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
unwrap(): T;
|
||||
}
|
||||
export declare const ZodExactOptional: core.$constructor<ZodExactOptional>;
|
||||
export declare function exactOptional<T extends core.SomeType>(innerType: T): ZodExactOptional<T>;
|
||||
export interface ZodNullable<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodNullableInternals<T>>, core.$ZodNullable<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
unwrap(): T;
|
||||
}
|
||||
export declare const ZodNullable: core.$constructor<ZodNullable>;
|
||||
export declare function nullable<T extends core.SomeType>(innerType: T): ZodNullable<T>;
|
||||
export declare function nullish<T extends core.SomeType>(innerType: T): ZodOptional<ZodNullable<T>>;
|
||||
export interface ZodDefault<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodDefaultInternals<T>>, core.$ZodDefault<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
unwrap(): T;
|
||||
/** @deprecated Use `.unwrap()` instead. */
|
||||
removeDefault(): T;
|
||||
}
|
||||
export declare const ZodDefault: core.$constructor<ZodDefault>;
|
||||
export declare function _default<T extends core.SomeType>(innerType: T, defaultValue: util.NoUndefined<core.output<T>> | (() => util.NoUndefined<core.output<T>>)): ZodDefault<T>;
|
||||
export interface ZodPrefault<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPrefaultInternals<T>>, core.$ZodPrefault<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
unwrap(): T;
|
||||
}
|
||||
export declare const ZodPrefault: core.$constructor<ZodPrefault>;
|
||||
export declare function prefault<T extends core.SomeType>(innerType: T, defaultValue: core.input<T> | (() => core.input<T>)): ZodPrefault<T>;
|
||||
export interface ZodNonOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodNonOptionalInternals<T>>, core.$ZodNonOptional<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
unwrap(): T;
|
||||
}
|
||||
export declare const ZodNonOptional: core.$constructor<ZodNonOptional>;
|
||||
export declare function nonoptional<T extends core.SomeType>(innerType: T, params?: string | core.$ZodNonOptionalParams): ZodNonOptional<T>;
|
||||
export interface ZodSuccess<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodSuccessInternals<T>>, core.$ZodSuccess<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
unwrap(): T;
|
||||
}
|
||||
export declare const ZodSuccess: core.$constructor<ZodSuccess>;
|
||||
export declare function success<T extends core.SomeType>(innerType: T): ZodSuccess<T>;
|
||||
export interface ZodCatch<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodCatchInternals<T>>, core.$ZodCatch<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
unwrap(): T;
|
||||
/** @deprecated Use `.unwrap()` instead. */
|
||||
removeCatch(): T;
|
||||
}
|
||||
export declare const ZodCatch: core.$constructor<ZodCatch>;
|
||||
declare function _catch<T extends core.SomeType>(innerType: T, catchValue: core.output<T> | ((ctx: core.$ZodCatchCtx) => core.output<T>)): ZodCatch<T>;
|
||||
export { _catch as catch };
|
||||
export interface ZodNaN extends _ZodType<core.$ZodNaNInternals>, core.$ZodNaN {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
}
|
||||
export declare const ZodNaN: core.$constructor<ZodNaN>;
|
||||
export declare function nan(params?: string | core.$ZodNaNParams): ZodNaN;
|
||||
export interface ZodPipe<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPipeInternals<A, B>>, core.$ZodPipe<A, B> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
in: A;
|
||||
out: B;
|
||||
}
|
||||
export declare const ZodPipe: core.$constructor<ZodPipe>;
|
||||
export declare function pipe<const A extends core.SomeType, B extends core.$ZodType<unknown, core.output<A>> = core.$ZodType<unknown, core.output<A>>>(in_: A, out: B | core.$ZodType<unknown, core.output<A>>): ZodPipe<A, B>;
|
||||
export interface ZodCodec<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends ZodPipe<A, B>, core.$ZodCodec<A, B> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
_zod: core.$ZodCodecInternals<A, B>;
|
||||
def: core.$ZodCodecDef<A, B>;
|
||||
}
|
||||
export declare const ZodCodec: core.$constructor<ZodCodec>;
|
||||
export declare function codec<const A extends core.SomeType, B extends core.SomeType = core.$ZodType>(in_: A, out: B, params: {
|
||||
decode: (value: core.output<A>, payload: core.ParsePayload<core.output<A>>) => core.util.MaybeAsync<core.input<B>>;
|
||||
encode: (value: core.input<B>, payload: core.ParsePayload<core.input<B>>) => core.util.MaybeAsync<core.output<A>>;
|
||||
}): ZodCodec<A, B>;
|
||||
export declare function invertCodec<A extends core.SomeType, B extends core.SomeType>(codec: ZodCodec<A, B>): ZodCodec<B, A>;
|
||||
export interface ZodPreprocess<B extends core.SomeType = core.$ZodType> extends ZodPipe<core.$ZodTransform, B>, core.$ZodPreprocess<B> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
_zod: core.$ZodPreprocessInternals<B>;
|
||||
def: core.$ZodPreprocessDef<B>;
|
||||
}
|
||||
export declare const ZodPreprocess: core.$constructor<ZodPreprocess>;
|
||||
export interface ZodReadonly<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodReadonlyInternals<T>>, core.$ZodReadonly<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
unwrap(): T;
|
||||
}
|
||||
export declare const ZodReadonly: core.$constructor<ZodReadonly>;
|
||||
export declare function readonly<T extends core.SomeType>(innerType: T): ZodReadonly<T>;
|
||||
export interface ZodTemplateLiteral<Template extends string = string> extends _ZodType<core.$ZodTemplateLiteralInternals<Template>>, core.$ZodTemplateLiteral<Template> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
}
|
||||
export declare const ZodTemplateLiteral: core.$constructor<ZodTemplateLiteral>;
|
||||
export declare function templateLiteral<const Parts extends core.$ZodTemplateLiteralPart[]>(parts: Parts, params?: string | core.$ZodTemplateLiteralParams): ZodTemplateLiteral<core.$PartsToTemplateLiteral<Parts>>;
|
||||
export interface ZodLazy<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodLazyInternals<T>>, core.$ZodLazy<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
unwrap(): T;
|
||||
}
|
||||
export declare const ZodLazy: core.$constructor<ZodLazy>;
|
||||
export declare function lazy<T extends core.SomeType>(getter: () => T): ZodLazy<T>;
|
||||
export interface ZodPromise<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPromiseInternals<T>>, core.$ZodPromise<T> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
unwrap(): T;
|
||||
}
|
||||
export declare const ZodPromise: core.$constructor<ZodPromise>;
|
||||
export declare function promise<T extends core.SomeType>(innerType: T): ZodPromise<T>;
|
||||
export interface ZodFunction<Args extends core.$ZodFunctionIn = core.$ZodFunctionIn, Returns extends core.$ZodFunctionOut = core.$ZodFunctionOut> extends _ZodType<core.$ZodFunctionInternals<Args, Returns>>, core.$ZodFunction<Args, Returns> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
_def: core.$ZodFunctionDef<Args, Returns>;
|
||||
_input: core.$InferInnerFunctionType<Args, Returns>;
|
||||
_output: core.$InferOuterFunctionType<Args, Returns>;
|
||||
input<const Items extends util.TupleItems, const Rest extends core.$ZodFunctionOut = core.$ZodFunctionOut>(args: Items, rest?: Rest): ZodFunction<core.$ZodTuple<Items, Rest>, Returns>;
|
||||
input<NewArgs extends core.$ZodFunctionIn>(args: NewArgs): ZodFunction<NewArgs, Returns>;
|
||||
input(...args: any[]): ZodFunction<any, Returns>;
|
||||
output<NewReturns extends core.$ZodType>(output: NewReturns): ZodFunction<Args, NewReturns>;
|
||||
}
|
||||
export declare const ZodFunction: core.$constructor<ZodFunction>;
|
||||
export declare function _function(): ZodFunction;
|
||||
export declare function _function<const In extends ReadonlyArray<core.$ZodType>>(params: {
|
||||
input: In;
|
||||
}): ZodFunction<ZodTuple<In, null>, core.$ZodFunctionOut>;
|
||||
export declare function _function<const In extends ReadonlyArray<core.$ZodType>, const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
|
||||
input: In;
|
||||
output: Out;
|
||||
}): ZodFunction<ZodTuple<In, null>, Out>;
|
||||
export declare function _function<const In extends core.$ZodFunctionIn = core.$ZodFunctionIn>(params: {
|
||||
input: In;
|
||||
}): ZodFunction<In, core.$ZodFunctionOut>;
|
||||
export declare function _function<const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
|
||||
output: Out;
|
||||
}): ZodFunction<core.$ZodFunctionIn, Out>;
|
||||
export declare function _function<In extends core.$ZodFunctionIn = core.$ZodFunctionIn, Out extends core.$ZodType = core.$ZodType>(params?: {
|
||||
input: In;
|
||||
output: Out;
|
||||
}): ZodFunction<In, Out>;
|
||||
export { _function as function };
|
||||
export interface ZodCustom<O = unknown, I = unknown> extends _ZodType<core.$ZodCustomInternals<O, I>>, core.$ZodCustom<O, I> {
|
||||
"~standard": ZodStandardSchemaWithJSON<this>;
|
||||
}
|
||||
export declare const ZodCustom: core.$constructor<ZodCustom>;
|
||||
export declare function check<O = unknown>(fn: core.CheckFn<O>): core.$ZodCheck<O>;
|
||||
export declare function custom<O>(fn?: (data: unknown) => unknown, _params?: string | core.$ZodCustomParams | undefined): ZodCustom<O, O>;
|
||||
export declare function refine<T>(fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>, _params?: string | core.$ZodCustomParams): core.$ZodCheck<T>;
|
||||
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): core.$ZodCheck<T>;
|
||||
export declare const describe: typeof core.describe;
|
||||
export declare const meta: typeof core.meta;
|
||||
type ZodInstanceOfParams = core.Params<ZodCustom, core.$ZodIssueCustom, "type" | "check" | "checks" | "fn" | "abort" | "error" | "params" | "path">;
|
||||
declare function _instanceof<T extends typeof util.Class>(cls: T, params?: ZodInstanceOfParams): ZodCustom<InstanceType<T>, InstanceType<T>>;
|
||||
export { _instanceof as instanceof };
|
||||
export declare const stringbool: (_params?: string | core.$ZodStringBoolParams) => ZodCodec<ZodString, ZodBoolean>;
|
||||
type _ZodJSONSchema = ZodUnion<[
|
||||
ZodString,
|
||||
ZodNumber,
|
||||
ZodBoolean,
|
||||
ZodNull,
|
||||
ZodArray<ZodJSONSchema>,
|
||||
ZodRecord<ZodString, ZodJSONSchema>
|
||||
]>;
|
||||
type _ZodJSONSchemaInternals = _ZodJSONSchema["_zod"];
|
||||
export interface ZodJSONSchemaInternals extends _ZodJSONSchemaInternals {
|
||||
output: util.JSONType;
|
||||
input: util.JSONType;
|
||||
}
|
||||
export interface ZodJSONSchema extends _ZodJSONSchema {
|
||||
_zod: ZodJSONSchemaInternals;
|
||||
}
|
||||
export declare function json(params?: string | core.$ZodCustomParams): ZodJSONSchema;
|
||||
export declare function preprocess<A, U extends core.SomeType, B = unknown>(fn: (arg: B, ctx: core.$RefinementCtx) => A, schema: U): ZodPreprocess<U>;
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es6",
|
||||
"lib": [ "es2015" ],
|
||||
"module": "commonjs",
|
||||
"noEmit": true,
|
||||
"strict": true
|
||||
},
|
||||
"include": [
|
||||
"./test/types/pino-pretty.test.d.ts",
|
||||
"./index.d.ts"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
/**
|
||||
* Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
|
||||
* For design rationale of types / exports, see weierstrass module documentation.
|
||||
* Untwisted Edwards curves exist, but they aren't used in real-world protocols.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bytesToHex, bytesToNumberLE, concatBytes, copyBytes, ensureBytes, isBytes, memoized, notImplemented, randomBytes as randomBytesWeb, } from "../utils.js";
|
||||
import { _createCurveFields, normalizeZ, pippenger, wNAF, } from "./curve.js";
|
||||
import { Field } from "./modular.js";
|
||||
// Be friendly to bad ECMAScript parsers by not using bigint literals
|
||||
// prettier-ignore
|
||||
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);
|
||||
function isEdValidXY(Fp, CURVE, x, y) {
|
||||
const x2 = Fp.sqr(x);
|
||||
const y2 = Fp.sqr(y);
|
||||
const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
|
||||
const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
|
||||
return Fp.eql(left, right);
|
||||
}
|
||||
export function edwards(params, extraOpts = {}) {
|
||||
const validated = _createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);
|
||||
const { Fp, Fn } = validated;
|
||||
let CURVE = validated.CURVE;
|
||||
const { h: cofactor } = CURVE;
|
||||
_validateObject(extraOpts, {}, { uvRatio: 'function' });
|
||||
// Important:
|
||||
// There are some places where Fp.BYTES is used instead of nByteLength.
|
||||
// So far, everything has been tested with curves of Fp.BYTES == nByteLength.
|
||||
// TODO: test and find curves which behave otherwise.
|
||||
const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);
|
||||
const modP = (n) => Fp.create(n); // Function overrides
|
||||
// sqrt(u/v)
|
||||
const uvRatio = extraOpts.uvRatio ||
|
||||
((u, v) => {
|
||||
try {
|
||||
return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };
|
||||
}
|
||||
catch (e) {
|
||||
return { isValid: false, value: _0n };
|
||||
}
|
||||
});
|
||||
// Validate whether the passed curve params are valid.
|
||||
// equation ax² + y² = 1 + dx²y² should work for generator point.
|
||||
if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))
|
||||
throw new Error('bad curve params: generator point');
|
||||
/**
|
||||
* Asserts coordinate is valid: 0 <= n < MASK.
|
||||
* Coordinates >= Fp.ORDER are allowed for zip215.
|
||||
*/
|
||||
function acoord(title, n, banZero = false) {
|
||||
const min = banZero ? _1n : _0n;
|
||||
aInRange('coordinate ' + title, n, min, MASK);
|
||||
return n;
|
||||
}
|
||||
function aextpoint(other) {
|
||||
if (!(other instanceof Point))
|
||||
throw new Error('ExtendedPoint expected');
|
||||
}
|
||||
// Converts Extended point to default (x, y) coordinates.
|
||||
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
||||
const toAffineMemo = memoized((p, iz) => {
|
||||
const { X, Y, Z } = p;
|
||||
const is0 = p.is0();
|
||||
if (iz == null)
|
||||
iz = is0 ? _8n : Fp.inv(Z); // 8 was chosen arbitrarily
|
||||
const x = modP(X * iz);
|
||||
const y = modP(Y * iz);
|
||||
const zz = Fp.mul(Z, iz);
|
||||
if (is0)
|
||||
return { x: _0n, y: _1n };
|
||||
if (zz !== _1n)
|
||||
throw new Error('invZ was invalid');
|
||||
return { x, y };
|
||||
});
|
||||
const assertValidMemo = memoized((p) => {
|
||||
const { a, d } = CURVE;
|
||||
if (p.is0())
|
||||
throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
|
||||
// Equation in affine coordinates: ax² + y² = 1 + dx²y²
|
||||
// Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
|
||||
const { X, Y, Z, T } = p;
|
||||
const X2 = modP(X * X); // X²
|
||||
const Y2 = modP(Y * Y); // Y²
|
||||
const Z2 = modP(Z * Z); // Z²
|
||||
const Z4 = modP(Z2 * Z2); // Z⁴
|
||||
const aX2 = modP(X2 * a); // aX²
|
||||
const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
|
||||
const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
|
||||
if (left !== right)
|
||||
throw new Error('bad point: equation left != right (1)');
|
||||
// In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
|
||||
const XY = modP(X * Y);
|
||||
const ZT = modP(Z * T);
|
||||
if (XY !== ZT)
|
||||
throw new Error('bad point: equation left != right (2)');
|
||||
return true;
|
||||
});
|
||||
// Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).
|
||||
// https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
|
||||
class Point {
|
||||
constructor(X, Y, Z, T) {
|
||||
this.X = acoord('x', X);
|
||||
this.Y = acoord('y', Y);
|
||||
this.Z = acoord('z', Z, true);
|
||||
this.T = acoord('t', T);
|
||||
Object.freeze(this);
|
||||
}
|
||||
static CURVE() {
|
||||
return CURVE;
|
||||
}
|
||||
static fromAffine(p) {
|
||||
if (p instanceof Point)
|
||||
throw new Error('extended point not allowed');
|
||||
const { x, y } = p || {};
|
||||
acoord('x', x);
|
||||
acoord('y', y);
|
||||
return new Point(x, y, _1n, modP(x * y));
|
||||
}
|
||||
// Uses algo from RFC8032 5.1.3.
|
||||
static fromBytes(bytes, zip215 = false) {
|
||||
const len = Fp.BYTES;
|
||||
const { a, d } = CURVE;
|
||||
bytes = copyBytes(abytes(bytes, len, 'point'));
|
||||
abool(zip215, 'zip215');
|
||||
const normed = copyBytes(bytes); // copy again, we'll manipulate it
|
||||
const lastByte = bytes[len - 1]; // select last byte
|
||||
normed[len - 1] = lastByte & ~0x80; // clear last bit
|
||||
const y = bytesToNumberLE(normed);
|
||||
// zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
|
||||
// RFC8032 prohibits >= p, but ZIP215 doesn't
|
||||
// zip215=true: 0 <= y < MASK (2^256 for ed25519)
|
||||
// zip215=false: 0 <= y < P (2^255-19 for ed25519)
|
||||
const max = zip215 ? MASK : Fp.ORDER;
|
||||
aInRange('point.y', y, _0n, max);
|
||||
// Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:
|
||||
// ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)
|
||||
const y2 = modP(y * y); // denominator is always non-0 mod p.
|
||||
const u = modP(y2 - _1n); // u = y² - 1
|
||||
const v = modP(d * y2 - a); // v = d y² + 1.
|
||||
let { isValid, value: x } = uvRatio(u, v); // √(u/v)
|
||||
if (!isValid)
|
||||
throw new Error('bad point: invalid y coordinate');
|
||||
const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper
|
||||
const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
|
||||
if (!zip215 && x === _0n && isLastByteOdd)
|
||||
// if x=0 and x_0 = 1, fail
|
||||
throw new Error('bad point: x=0 and x_0=1');
|
||||
if (isLastByteOdd !== isXOdd)
|
||||
x = modP(-x); // if x_0 != x mod 2, set x = p-x
|
||||
return Point.fromAffine({ x, y });
|
||||
}
|
||||
static fromHex(bytes, zip215 = false) {
|
||||
return Point.fromBytes(ensureBytes('point', bytes), zip215);
|
||||
}
|
||||
get x() {
|
||||
return this.toAffine().x;
|
||||
}
|
||||
get y() {
|
||||
return this.toAffine().y;
|
||||
}
|
||||
precompute(windowSize = 8, isLazy = true) {
|
||||
wnaf.createCache(this, windowSize);
|
||||
if (!isLazy)
|
||||
this.multiply(_2n); // random number
|
||||
return this;
|
||||
}
|
||||
// Useful in fromAffine() - not for fromBytes(), which always created valid points.
|
||||
assertValidity() {
|
||||
assertValidMemo(this);
|
||||
}
|
||||
// Compare one point to another.
|
||||
equals(other) {
|
||||
aextpoint(other);
|
||||
const { X: X1, Y: Y1, Z: Z1 } = this;
|
||||
const { X: X2, Y: Y2, Z: Z2 } = other;
|
||||
const X1Z2 = modP(X1 * Z2);
|
||||
const X2Z1 = modP(X2 * Z1);
|
||||
const Y1Z2 = modP(Y1 * Z2);
|
||||
const Y2Z1 = modP(Y2 * Z1);
|
||||
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
|
||||
}
|
||||
is0() {
|
||||
return this.equals(Point.ZERO);
|
||||
}
|
||||
negate() {
|
||||
// Flips point sign to a negative one (-x, y in affine coords)
|
||||
return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
|
||||
}
|
||||
// Fast algo for doubling Extended Point.
|
||||
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
|
||||
// Cost: 4M + 4S + 1*a + 6add + 1*2.
|
||||
double() {
|
||||
const { a } = CURVE;
|
||||
const { X: X1, Y: Y1, Z: Z1 } = this;
|
||||
const A = modP(X1 * X1); // A = X12
|
||||
const B = modP(Y1 * Y1); // B = Y12
|
||||
const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12
|
||||
const D = modP(a * A); // D = a*A
|
||||
const x1y1 = X1 + Y1;
|
||||
const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B
|
||||
const G = D + B; // G = D+B
|
||||
const F = G - C; // F = G-C
|
||||
const H = D - B; // H = D-B
|
||||
const X3 = modP(E * F); // X3 = E*F
|
||||
const Y3 = modP(G * H); // Y3 = G*H
|
||||
const T3 = modP(E * H); // T3 = E*H
|
||||
const Z3 = modP(F * G); // Z3 = F*G
|
||||
return new Point(X3, Y3, Z3, T3);
|
||||
}
|
||||
// Fast algo for adding 2 Extended Points.
|
||||
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
|
||||
// Cost: 9M + 1*a + 1*d + 7add.
|
||||
add(other) {
|
||||
aextpoint(other);
|
||||
const { a, d } = CURVE;
|
||||
const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
|
||||
const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
|
||||
const A = modP(X1 * X2); // A = X1*X2
|
||||
const B = modP(Y1 * Y2); // B = Y1*Y2
|
||||
const C = modP(T1 * d * T2); // C = T1*d*T2
|
||||
const D = modP(Z1 * Z2); // D = Z1*Z2
|
||||
const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B
|
||||
const F = D - C; // F = D-C
|
||||
const G = D + C; // G = D+C
|
||||
const H = modP(B - a * A); // H = B-a*A
|
||||
const X3 = modP(E * F); // X3 = E*F
|
||||
const Y3 = modP(G * H); // Y3 = G*H
|
||||
const T3 = modP(E * H); // T3 = E*H
|
||||
const Z3 = modP(F * G); // Z3 = F*G
|
||||
return new Point(X3, Y3, Z3, T3);
|
||||
}
|
||||
subtract(other) {
|
||||
return this.add(other.negate());
|
||||
}
|
||||
// Constant-time multiplication.
|
||||
multiply(scalar) {
|
||||
// 1 <= scalar < L
|
||||
if (!Fn.isValidNot0(scalar))
|
||||
throw new Error('invalid scalar: expected 1 <= sc < curve.n');
|
||||
const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));
|
||||
return normalizeZ(Point, [p, f])[0];
|
||||
}
|
||||
// Non-constant-time multiplication. Uses double-and-add algorithm.
|
||||
// It's faster, but should only be used when you don't care about
|
||||
// an exposed private key e.g. sig verification.
|
||||
// Does NOT allow scalars higher than CURVE.n.
|
||||
// Accepts optional accumulator to merge with multiply (important for sparse scalars)
|
||||
multiplyUnsafe(scalar, acc = Point.ZERO) {
|
||||
// 0 <= scalar < L
|
||||
if (!Fn.isValid(scalar))
|
||||
throw new Error('invalid scalar: expected 0 <= sc < curve.n');
|
||||
if (scalar === _0n)
|
||||
return Point.ZERO;
|
||||
if (this.is0() || scalar === _1n)
|
||||
return this;
|
||||
return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
|
||||
}
|
||||
// Checks if point is of small order.
|
||||
// If you add something to small order point, you will have "dirty"
|
||||
// point with torsion component.
|
||||
// Multiplies point by cofactor and checks if the result is 0.
|
||||
isSmallOrder() {
|
||||
return this.multiplyUnsafe(cofactor).is0();
|
||||
}
|
||||
// Multiplies point by curve order and checks if the result is 0.
|
||||
// Returns `false` is the point is dirty.
|
||||
isTorsionFree() {
|
||||
return wnaf.unsafe(this, CURVE.n).is0();
|
||||
}
|
||||
// Converts Extended point to default (x, y) coordinates.
|
||||
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
||||
toAffine(invertedZ) {
|
||||
return toAffineMemo(this, invertedZ);
|
||||
}
|
||||
clearCofactor() {
|
||||
if (cofactor === _1n)
|
||||
return this;
|
||||
return this.multiplyUnsafe(cofactor);
|
||||
}
|
||||
toBytes() {
|
||||
const { x, y } = this.toAffine();
|
||||
// Fp.toBytes() allows non-canonical encoding of y (>= p).
|
||||
const bytes = Fp.toBytes(y);
|
||||
// Each y has 2 valid points: (x, y), (x,-y).
|
||||
// When compressing, it's enough to store y and use the last byte to encode sign of x
|
||||
bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;
|
||||
return bytes;
|
||||
}
|
||||
toHex() {
|
||||
return bytesToHex(this.toBytes());
|
||||
}
|
||||
toString() {
|
||||
return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
|
||||
}
|
||||
// TODO: remove
|
||||
get ex() {
|
||||
return this.X;
|
||||
}
|
||||
get ey() {
|
||||
return this.Y;
|
||||
}
|
||||
get ez() {
|
||||
return this.Z;
|
||||
}
|
||||
get et() {
|
||||
return this.T;
|
||||
}
|
||||
static normalizeZ(points) {
|
||||
return normalizeZ(Point, points);
|
||||
}
|
||||
static msm(points, scalars) {
|
||||
return pippenger(Point, Fn, points, scalars);
|
||||
}
|
||||
_setWindowSize(windowSize) {
|
||||
this.precompute(windowSize);
|
||||
}
|
||||
toRawBytes() {
|
||||
return this.toBytes();
|
||||
}
|
||||
}
|
||||
// base / generator point
|
||||
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));
|
||||
// zero / infinity / identity point
|
||||
Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0
|
||||
// math field
|
||||
Point.Fp = Fp;
|
||||
// scalar field
|
||||
Point.Fn = Fn;
|
||||
const wnaf = new wNAF(Point, Fn.BITS);
|
||||
Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
|
||||
return Point;
|
||||
}
|
||||
/**
|
||||
* Base class for prime-order points like Ristretto255 and Decaf448.
|
||||
* These points eliminate cofactor issues by representing equivalence classes
|
||||
* of Edwards curve points.
|
||||
*/
|
||||
export class PrimeEdwardsPoint {
|
||||
constructor(ep) {
|
||||
this.ep = ep;
|
||||
}
|
||||
// Static methods that must be implemented by subclasses
|
||||
static fromBytes(_bytes) {
|
||||
notImplemented();
|
||||
}
|
||||
static fromHex(_hex) {
|
||||
notImplemented();
|
||||
}
|
||||
get x() {
|
||||
return this.toAffine().x;
|
||||
}
|
||||
get y() {
|
||||
return this.toAffine().y;
|
||||
}
|
||||
// Common implementations
|
||||
clearCofactor() {
|
||||
// no-op for prime-order groups
|
||||
return this;
|
||||
}
|
||||
assertValidity() {
|
||||
this.ep.assertValidity();
|
||||
}
|
||||
toAffine(invertedZ) {
|
||||
return this.ep.toAffine(invertedZ);
|
||||
}
|
||||
toHex() {
|
||||
return bytesToHex(this.toBytes());
|
||||
}
|
||||
toString() {
|
||||
return this.toHex();
|
||||
}
|
||||
isTorsionFree() {
|
||||
return true;
|
||||
}
|
||||
isSmallOrder() {
|
||||
return false;
|
||||
}
|
||||
add(other) {
|
||||
this.assertSame(other);
|
||||
return this.init(this.ep.add(other.ep));
|
||||
}
|
||||
subtract(other) {
|
||||
this.assertSame(other);
|
||||
return this.init(this.ep.subtract(other.ep));
|
||||
}
|
||||
multiply(scalar) {
|
||||
return this.init(this.ep.multiply(scalar));
|
||||
}
|
||||
multiplyUnsafe(scalar) {
|
||||
return this.init(this.ep.multiplyUnsafe(scalar));
|
||||
}
|
||||
double() {
|
||||
return this.init(this.ep.double());
|
||||
}
|
||||
negate() {
|
||||
return this.init(this.ep.negate());
|
||||
}
|
||||
precompute(windowSize, isLazy) {
|
||||
return this.init(this.ep.precompute(windowSize, isLazy));
|
||||
}
|
||||
/** @deprecated use `toBytes` */
|
||||
toRawBytes() {
|
||||
return this.toBytes();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Initializes EdDSA signatures over given Edwards curve.
|
||||
*/
|
||||
export function eddsa(Point, cHash, eddsaOpts = {}) {
|
||||
if (typeof cHash !== 'function')
|
||||
throw new Error('"hash" function param is required');
|
||||
_validateObject(eddsaOpts, {}, {
|
||||
adjustScalarBytes: 'function',
|
||||
randomBytes: 'function',
|
||||
domain: 'function',
|
||||
prehash: 'function',
|
||||
mapToCurve: 'function',
|
||||
});
|
||||
const { prehash } = eddsaOpts;
|
||||
const { BASE, Fp, Fn } = Point;
|
||||
const randomBytes = eddsaOpts.randomBytes || randomBytesWeb;
|
||||
const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
|
||||
const domain = eddsaOpts.domain ||
|
||||
((data, ctx, phflag) => {
|
||||
abool(phflag, 'phflag');
|
||||
if (ctx.length || phflag)
|
||||
throw new Error('Contexts/pre-hash are not supported');
|
||||
return data;
|
||||
}); // NOOP
|
||||
// Little-endian SHA512 with modulo n
|
||||
function modN_LE(hash) {
|
||||
return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit
|
||||
}
|
||||
// Get the hashed private scalar per RFC8032 5.1.5
|
||||
function getPrivateScalar(key) {
|
||||
const len = lengths.secretKey;
|
||||
key = ensureBytes('private key', key, len);
|
||||
// Hash private key with curve's hash function to produce uniformingly random input
|
||||
// Check byte lengths: ensure(64, h(ensure(32, key)))
|
||||
const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);
|
||||
const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE
|
||||
const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)
|
||||
const scalar = modN_LE(head); // The actual private scalar
|
||||
return { head, prefix, scalar };
|
||||
}
|
||||
/** Convenience method that creates public key from scalar. RFC8032 5.1.5 */
|
||||
function getExtendedPublicKey(secretKey) {
|
||||
const { head, prefix, scalar } = getPrivateScalar(secretKey);
|
||||
const point = BASE.multiply(scalar); // Point on Edwards curve aka public key
|
||||
const pointBytes = point.toBytes();
|
||||
return { head, prefix, scalar, point, pointBytes };
|
||||
}
|
||||
/** Calculates EdDSA pub key. RFC8032 5.1.5. */
|
||||
function getPublicKey(secretKey) {
|
||||
return getExtendedPublicKey(secretKey).pointBytes;
|
||||
}
|
||||
// int('LE', SHA512(dom2(F, C) || msgs)) mod N
|
||||
function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
|
||||
const msg = concatBytes(...msgs);
|
||||
return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));
|
||||
}
|
||||
/** Signs message with privateKey. RFC8032 5.1.6 */
|
||||
function sign(msg, secretKey, options = {}) {
|
||||
msg = ensureBytes('message', msg);
|
||||
if (prehash)
|
||||
msg = prehash(msg); // for ed25519ph etc.
|
||||
const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
|
||||
const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)
|
||||
const R = BASE.multiply(r).toBytes(); // R = rG
|
||||
const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)
|
||||
const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L
|
||||
if (!Fn.isValid(s))
|
||||
throw new Error('sign failed: invalid s'); // 0 <= s < L
|
||||
const rs = concatBytes(R, Fn.toBytes(s));
|
||||
return abytes(rs, lengths.signature, 'result');
|
||||
}
|
||||
// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:
|
||||
const verifyOpts = { zip215: true };
|
||||
/**
|
||||
* Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
|
||||
* An extended group equation is checked.
|
||||
*/
|
||||
function verify(sig, msg, publicKey, options = verifyOpts) {
|
||||
const { context, zip215 } = options;
|
||||
const len = lengths.signature;
|
||||
sig = ensureBytes('signature', sig, len);
|
||||
msg = ensureBytes('message', msg);
|
||||
publicKey = ensureBytes('publicKey', publicKey, lengths.publicKey);
|
||||
if (zip215 !== undefined)
|
||||
abool(zip215, 'zip215');
|
||||
if (prehash)
|
||||
msg = prehash(msg); // for ed25519ph, etc
|
||||
const mid = len / 2;
|
||||
const r = sig.subarray(0, mid);
|
||||
const s = bytesToNumberLE(sig.subarray(mid, len));
|
||||
let A, R, SB;
|
||||
try {
|
||||
// zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
|
||||
// zip215=true: 0 <= y < MASK (2^256 for ed25519)
|
||||
// zip215=false: 0 <= y < P (2^255-19 for ed25519)
|
||||
A = Point.fromBytes(publicKey, zip215);
|
||||
R = Point.fromBytes(r, zip215);
|
||||
SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside
|
||||
}
|
||||
catch (error) {
|
||||
return false;
|
||||
}
|
||||
if (!zip215 && A.isSmallOrder())
|
||||
return false; // zip215 allows public keys of small order
|
||||
const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
|
||||
const RkA = R.add(A.multiplyUnsafe(k));
|
||||
// Extended group equation
|
||||
// [8][S]B = [8]R + [8][k]A'
|
||||
return RkA.subtract(SB).clearCofactor().is0();
|
||||
}
|
||||
const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448
|
||||
const lengths = {
|
||||
secretKey: _size,
|
||||
publicKey: _size,
|
||||
signature: 2 * _size,
|
||||
seed: _size,
|
||||
};
|
||||
function randomSecretKey(seed = randomBytes(lengths.seed)) {
|
||||
return abytes(seed, lengths.seed, 'seed');
|
||||
}
|
||||
function keygen(seed) {
|
||||
const secretKey = utils.randomSecretKey(seed);
|
||||
return { secretKey, publicKey: getPublicKey(secretKey) };
|
||||
}
|
||||
function isValidSecretKey(key) {
|
||||
return isBytes(key) && key.length === Fn.BYTES;
|
||||
}
|
||||
function isValidPublicKey(key, zip215) {
|
||||
try {
|
||||
return !!Point.fromBytes(key, zip215);
|
||||
}
|
||||
catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const utils = {
|
||||
getExtendedPublicKey,
|
||||
randomSecretKey,
|
||||
isValidSecretKey,
|
||||
isValidPublicKey,
|
||||
/**
|
||||
* Converts ed public key to x public key. Uses formula:
|
||||
* - ed25519:
|
||||
* - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
|
||||
* - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
|
||||
* - ed448:
|
||||
* - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
|
||||
* - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
|
||||
*/
|
||||
toMontgomery(publicKey) {
|
||||
const { y } = Point.fromBytes(publicKey);
|
||||
const size = lengths.publicKey;
|
||||
const is25519 = size === 32;
|
||||
if (!is25519 && size !== 57)
|
||||
throw new Error('only defined for 25519 and 448');
|
||||
const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);
|
||||
return Fp.toBytes(u);
|
||||
},
|
||||
toMontgomerySecret(secretKey) {
|
||||
const size = lengths.secretKey;
|
||||
abytes(secretKey, size);
|
||||
const hashed = cHash(secretKey.subarray(0, size));
|
||||
return adjustScalarBytes(hashed).subarray(0, size);
|
||||
},
|
||||
/** @deprecated */
|
||||
randomPrivateKey: randomSecretKey,
|
||||
/** @deprecated */
|
||||
precompute(windowSize = 8, point = Point.BASE) {
|
||||
return point.precompute(windowSize, false);
|
||||
},
|
||||
};
|
||||
return Object.freeze({
|
||||
keygen,
|
||||
getPublicKey,
|
||||
sign,
|
||||
verify,
|
||||
utils,
|
||||
Point,
|
||||
lengths,
|
||||
});
|
||||
}
|
||||
function _eddsa_legacy_opts_to_new(c) {
|
||||
const CURVE = {
|
||||
a: c.a,
|
||||
d: c.d,
|
||||
p: c.Fp.ORDER,
|
||||
n: c.n,
|
||||
h: c.h,
|
||||
Gx: c.Gx,
|
||||
Gy: c.Gy,
|
||||
};
|
||||
const Fp = c.Fp;
|
||||
const Fn = Field(CURVE.n, c.nBitLength, true);
|
||||
const curveOpts = { Fp, Fn, uvRatio: c.uvRatio };
|
||||
const eddsaOpts = {
|
||||
randomBytes: c.randomBytes,
|
||||
adjustScalarBytes: c.adjustScalarBytes,
|
||||
domain: c.domain,
|
||||
prehash: c.prehash,
|
||||
mapToCurve: c.mapToCurve,
|
||||
};
|
||||
return { CURVE, curveOpts, hash: c.hash, eddsaOpts };
|
||||
}
|
||||
function _eddsa_new_output_to_legacy(c, eddsa) {
|
||||
const Point = eddsa.Point;
|
||||
const legacy = Object.assign({}, eddsa, {
|
||||
ExtendedPoint: Point,
|
||||
CURVE: c,
|
||||
nBitLength: Point.Fn.BITS,
|
||||
nByteLength: Point.Fn.BYTES,
|
||||
});
|
||||
return legacy;
|
||||
}
|
||||
// TODO: remove. Use eddsa
|
||||
export function twistedEdwards(c) {
|
||||
const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
|
||||
const Point = edwards(CURVE, curveOpts);
|
||||
const EDDSA = eddsa(Point, hash, eddsaOpts);
|
||||
return _eddsa_new_output_to_legacy(c, EDDSA);
|
||||
}
|
||||
//# sourceMappingURL=edwards.js.map
|
||||
@@ -0,0 +1,157 @@
|
||||
"use strict";
|
||||
/* --------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
* ------------------------------------------------------------------------------------------ */
|
||||
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;
|
||||
};
|
||||
})();
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = void 0;
|
||||
const ral_1 = __importDefault(require("./ral"));
|
||||
const Is = __importStar(require("./is"));
|
||||
const semaphore_1 = require("./semaphore");
|
||||
const events_1 = require("./events");
|
||||
const ContentLength = 'Content-Length: ';
|
||||
const CRLF = '\r\n';
|
||||
var MessageWriter;
|
||||
(function (MessageWriter) {
|
||||
function is(value) {
|
||||
const candidate = value;
|
||||
return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
|
||||
Is.func(candidate.onError) && Is.func(candidate.write);
|
||||
}
|
||||
MessageWriter.is = is;
|
||||
})(MessageWriter || (exports.MessageWriter = MessageWriter = {}));
|
||||
class AbstractMessageWriter {
|
||||
errorEmitter;
|
||||
closeEmitter;
|
||||
constructor() {
|
||||
this.errorEmitter = new events_1.Emitter();
|
||||
this.closeEmitter = new events_1.Emitter();
|
||||
}
|
||||
dispose() {
|
||||
this.errorEmitter.dispose();
|
||||
this.closeEmitter.dispose();
|
||||
}
|
||||
get onError() {
|
||||
return this.errorEmitter.event;
|
||||
}
|
||||
fireError(error, message, count) {
|
||||
this.errorEmitter.fire([this.asError(error), message, count]);
|
||||
}
|
||||
get onClose() {
|
||||
return this.closeEmitter.event;
|
||||
}
|
||||
fireClose() {
|
||||
this.closeEmitter.fire(undefined);
|
||||
}
|
||||
asError(error) {
|
||||
if (error instanceof Error) {
|
||||
return error;
|
||||
}
|
||||
else {
|
||||
return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.AbstractMessageWriter = AbstractMessageWriter;
|
||||
var ResolvedMessageWriterOptions;
|
||||
(function (ResolvedMessageWriterOptions) {
|
||||
function fromOptions(options) {
|
||||
if (options === undefined || typeof options === 'string') {
|
||||
return { charset: options ?? 'utf-8', contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder };
|
||||
}
|
||||
else {
|
||||
return { charset: options.charset ?? 'utf-8', contentEncoder: options.contentEncoder, contentTypeEncoder: options.contentTypeEncoder ?? (0, ral_1.default)().applicationJson.encoder };
|
||||
}
|
||||
}
|
||||
ResolvedMessageWriterOptions.fromOptions = fromOptions;
|
||||
})(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
|
||||
class WriteableStreamMessageWriter extends AbstractMessageWriter {
|
||||
writable;
|
||||
options;
|
||||
errorCount;
|
||||
writeSemaphore;
|
||||
constructor(writable, options) {
|
||||
super();
|
||||
this.writable = writable;
|
||||
this.options = ResolvedMessageWriterOptions.fromOptions(options);
|
||||
this.errorCount = 0;
|
||||
this.writeSemaphore = new semaphore_1.Semaphore(1);
|
||||
this.writable.onError((error) => this.fireError(error));
|
||||
this.writable.onClose(() => this.fireClose());
|
||||
}
|
||||
async write(msg) {
|
||||
return this.writeSemaphore.lock(async () => {
|
||||
const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
|
||||
if (this.options.contentEncoder !== undefined) {
|
||||
return this.options.contentEncoder.encode(buffer);
|
||||
}
|
||||
else {
|
||||
return buffer;
|
||||
}
|
||||
});
|
||||
return payload.then((buffer) => {
|
||||
const headers = [];
|
||||
headers.push(ContentLength, buffer.byteLength.toString(), CRLF);
|
||||
headers.push(CRLF);
|
||||
return this.doWrite(msg, headers, buffer);
|
||||
}, (error) => {
|
||||
this.fireError(error);
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
}
|
||||
async doWrite(msg, headers, data) {
|
||||
try {
|
||||
await this.writable.write(headers.join(''), 'ascii');
|
||||
return this.writable.write(data);
|
||||
}
|
||||
catch (error) {
|
||||
this.handleError(error, msg);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
}
|
||||
handleError(error, msg) {
|
||||
this.errorCount++;
|
||||
this.fireError(error, msg, this.errorCount);
|
||||
}
|
||||
end() {
|
||||
this.writable.end();
|
||||
}
|
||||
}
|
||||
exports.WriteableStreamMessageWriter = WriteableStreamMessageWriter;
|
||||
@@ -0,0 +1,3 @@
|
||||
These files are compiled dot templates from dot folder.
|
||||
|
||||
Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder.
|
||||
@@ -0,0 +1,238 @@
|
||||
import process from 'node:process';
|
||||
import fs from 'node:fs/promises';
|
||||
import path, { resolve } from 'node:path';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { x } from 'tinyexec';
|
||||
|
||||
const AGENTS = [
|
||||
"npm",
|
||||
"yarn",
|
||||
"yarn@berry",
|
||||
"pnpm",
|
||||
"pnpm@6",
|
||||
"bun",
|
||||
"deno"
|
||||
];
|
||||
const LOCKS = {
|
||||
"bun.lock": "bun",
|
||||
"bun.lockb": "bun",
|
||||
"deno.lock": "deno",
|
||||
"pnpm-lock.yaml": "pnpm",
|
||||
"pnpm-workspace.yaml": "pnpm",
|
||||
"yarn.lock": "yarn",
|
||||
"package-lock.json": "npm",
|
||||
"npm-shrinkwrap.json": "npm"
|
||||
};
|
||||
const INSTALL_METADATA = {
|
||||
"node_modules/.deno/": "deno",
|
||||
"node_modules/.pnpm/": "pnpm",
|
||||
"node_modules/.yarn-state.yml": "yarn",
|
||||
// yarn v2+ (node-modules)
|
||||
"node_modules/.yarn_integrity": "yarn",
|
||||
// yarn v1
|
||||
"node_modules/.package-lock.json": "npm",
|
||||
".pnp.cjs": "yarn",
|
||||
// yarn v3+ (pnp)
|
||||
".pnp.js": "yarn",
|
||||
// yarn v2 (pnp)
|
||||
"bun.lock": "bun",
|
||||
"bun.lockb": "bun"
|
||||
};
|
||||
|
||||
async function pathExists(path2, type) {
|
||||
try {
|
||||
const stat = await fs.stat(path2);
|
||||
return type === "file" ? stat.isFile() : stat.isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function* lookup(cwd = process.cwd()) {
|
||||
let directory = path.resolve(cwd);
|
||||
const { root } = path.parse(directory);
|
||||
while (directory && directory !== root) {
|
||||
yield directory;
|
||||
directory = path.dirname(directory);
|
||||
}
|
||||
}
|
||||
async function parsePackageJson(filepath, onUnknown) {
|
||||
return !filepath || !pathExists(filepath, "file") ? null : await handlePackageManager(filepath, onUnknown);
|
||||
}
|
||||
async function detect(options = {}) {
|
||||
const {
|
||||
cwd,
|
||||
strategies = ["lockfile", "packageManager-field", "devEngines-field"],
|
||||
onUnknown
|
||||
} = options;
|
||||
let stopDir;
|
||||
if (typeof options.stopDir === "string") {
|
||||
const resolved = path.resolve(options.stopDir);
|
||||
stopDir = (dir) => dir === resolved;
|
||||
} else {
|
||||
stopDir = options.stopDir;
|
||||
}
|
||||
for (const directory of lookup(cwd)) {
|
||||
for (const strategy of strategies) {
|
||||
switch (strategy) {
|
||||
case "lockfile": {
|
||||
for (const lock of Object.keys(LOCKS)) {
|
||||
if (await pathExists(path.join(directory, lock), "file")) {
|
||||
const name = LOCKS[lock];
|
||||
const result = await parsePackageJson(path.join(directory, "package.json"), onUnknown);
|
||||
if (result)
|
||||
return result;
|
||||
else
|
||||
return { name, agent: name };
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "packageManager-field":
|
||||
case "devEngines-field": {
|
||||
const result = await parsePackageJson(path.join(directory, "package.json"), onUnknown);
|
||||
if (result)
|
||||
return result;
|
||||
break;
|
||||
}
|
||||
case "install-metadata": {
|
||||
for (const metadata of Object.keys(INSTALL_METADATA)) {
|
||||
const fileOrDir = metadata.endsWith("/") ? "dir" : "file";
|
||||
if (await pathExists(path.join(directory, metadata), fileOrDir)) {
|
||||
const name = INSTALL_METADATA[metadata];
|
||||
const agent = name === "yarn" ? isMetadataYarnClassic(metadata) ? "yarn" : "yarn@berry" : name;
|
||||
return { name, agent };
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stopDir?.(directory))
|
||||
break;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function getNameAndVer(pkg) {
|
||||
const handelVer = (version) => version?.match(/\d+(\.\d+){0,2}/)?.[0] ?? version;
|
||||
if (typeof pkg.packageManager === "string") {
|
||||
const [name, ver] = pkg.packageManager.replace(/^\^/, "").split("@");
|
||||
return { name, ver: handelVer(ver) };
|
||||
}
|
||||
if (typeof pkg.devEngines?.packageManager?.name === "string") {
|
||||
return {
|
||||
name: pkg.devEngines.packageManager.name,
|
||||
ver: handelVer(pkg.devEngines.packageManager.version)
|
||||
};
|
||||
}
|
||||
return void 0;
|
||||
}
|
||||
async function handlePackageManager(filepath, onUnknown) {
|
||||
try {
|
||||
const pkg = JSON.parse(await fs.readFile(filepath, "utf8"));
|
||||
let agent;
|
||||
const nameAndVer = getNameAndVer(pkg);
|
||||
if (nameAndVer) {
|
||||
const name = nameAndVer.name;
|
||||
const ver = nameAndVer.ver;
|
||||
let version = ver;
|
||||
if (name === "yarn" && ver && Number.parseInt(ver) > 1) {
|
||||
agent = "yarn@berry";
|
||||
version = "berry";
|
||||
return { name, agent, version };
|
||||
} else if (name === "pnpm" && ver && Number.parseInt(ver) < 7) {
|
||||
agent = "pnpm@6";
|
||||
return { name, agent, version };
|
||||
} else if (AGENTS.includes(name)) {
|
||||
agent = name;
|
||||
return { name, agent, version };
|
||||
} else {
|
||||
return onUnknown?.(pkg.packageManager) ?? null;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function isMetadataYarnClassic(metadataPath) {
|
||||
return metadataPath.endsWith(".yarn_integrity");
|
||||
}
|
||||
|
||||
// src/detect.ts
|
||||
async function detectPackageManager(cwd = process.cwd()) {
|
||||
const result = await detect({
|
||||
cwd,
|
||||
onUnknown(packageManager) {
|
||||
console.warn("[@antfu/install-pkg] Unknown packageManager:", packageManager);
|
||||
return void 0;
|
||||
}
|
||||
});
|
||||
return result?.agent || null;
|
||||
}
|
||||
async function installPackage(names, options = {}) {
|
||||
const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm";
|
||||
const [agent] = detectedAgent.split("@");
|
||||
if (!Array.isArray(names))
|
||||
names = [names];
|
||||
const args = (typeof options.additionalArgs === "function" ? options.additionalArgs(agent, detectedAgent) : options.additionalArgs) || [];
|
||||
if (options.preferOffline) {
|
||||
if (detectedAgent === "yarn@berry")
|
||||
args.unshift("--cached");
|
||||
else
|
||||
args.unshift("--prefer-offline");
|
||||
}
|
||||
if (agent === "pnpm") {
|
||||
args.unshift(
|
||||
/**
|
||||
* Prevent pnpm from removing installed devDeps while `NODE_ENV` is `production`
|
||||
* @see https://pnpm.io/cli/install#--prod--p
|
||||
*/
|
||||
"--prod=false"
|
||||
);
|
||||
if (existsSync(resolve(options.cwd ?? process.cwd(), "pnpm-workspace.yaml"))) {
|
||||
args.unshift("-w");
|
||||
}
|
||||
}
|
||||
return x(
|
||||
agent,
|
||||
[
|
||||
agent === "yarn" ? "add" : "install",
|
||||
options.dev ? "-D" : "",
|
||||
...args,
|
||||
...names
|
||||
].filter(Boolean),
|
||||
{
|
||||
nodeOptions: {
|
||||
stdio: options.silent ? "ignore" : "inherit",
|
||||
cwd: options.cwd
|
||||
},
|
||||
throwOnError: true
|
||||
}
|
||||
);
|
||||
}
|
||||
async function uninstallPackage(names, options = {}) {
|
||||
const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm";
|
||||
const [agent] = detectedAgent.split("@");
|
||||
if (!Array.isArray(names))
|
||||
names = [names];
|
||||
const args = options.additionalArgs || [];
|
||||
if (agent === "pnpm" && existsSync(resolve(options.cwd ?? process.cwd(), "pnpm-workspace.yaml")))
|
||||
args.unshift("-w");
|
||||
return x(
|
||||
agent,
|
||||
[
|
||||
agent === "yarn" ? "remove" : "uninstall",
|
||||
options.dev ? "-D" : "",
|
||||
...args,
|
||||
...names
|
||||
].filter(Boolean),
|
||||
{
|
||||
nodeOptions: {
|
||||
stdio: options.silent ? "ignore" : "inherit",
|
||||
cwd: options.cwd
|
||||
},
|
||||
throwOnError: true
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export { detectPackageManager, installPackage, uninstallPackage };
|
||||
@@ -0,0 +1,55 @@
|
||||
declare function fromBig(n: bigint, le?: boolean): {
|
||||
h: number;
|
||||
l: number;
|
||||
};
|
||||
declare function split(lst: bigint[], le?: boolean): Uint32Array[];
|
||||
declare const toBig: (h: number, l: number) => bigint;
|
||||
declare const shrSH: (h: number, _l: number, s: number) => number;
|
||||
declare const shrSL: (h: number, l: number, s: number) => number;
|
||||
declare const rotrSH: (h: number, l: number, s: number) => number;
|
||||
declare const rotrSL: (h: number, l: number, s: number) => number;
|
||||
declare const rotrBH: (h: number, l: number, s: number) => number;
|
||||
declare const rotrBL: (h: number, l: number, s: number) => number;
|
||||
declare const rotr32H: (_h: number, l: number) => number;
|
||||
declare const rotr32L: (h: number, _l: number) => number;
|
||||
declare const rotlSH: (h: number, l: number, s: number) => number;
|
||||
declare const rotlSL: (h: number, l: number, s: number) => number;
|
||||
declare const rotlBH: (h: number, l: number, s: number) => number;
|
||||
declare const rotlBL: (h: number, l: number, s: number) => number;
|
||||
declare function add(Ah: number, Al: number, Bh: number, Bl: number): {
|
||||
h: number;
|
||||
l: number;
|
||||
};
|
||||
declare const add3L: (Al: number, Bl: number, Cl: number) => number;
|
||||
declare const add3H: (low: number, Ah: number, Bh: number, Ch: number) => number;
|
||||
declare const add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number;
|
||||
declare const add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number;
|
||||
declare const add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number;
|
||||
declare const add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number;
|
||||
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
|
||||
declare const u64: {
|
||||
fromBig: typeof fromBig;
|
||||
split: typeof split;
|
||||
toBig: (h: number, l: number) => bigint;
|
||||
shrSH: (h: number, _l: number, s: number) => number;
|
||||
shrSL: (h: number, l: number, s: number) => number;
|
||||
rotrSH: (h: number, l: number, s: number) => number;
|
||||
rotrSL: (h: number, l: number, s: number) => number;
|
||||
rotrBH: (h: number, l: number, s: number) => number;
|
||||
rotrBL: (h: number, l: number, s: number) => number;
|
||||
rotr32H: (_h: number, l: number) => number;
|
||||
rotr32L: (h: number, _l: number) => number;
|
||||
rotlSH: (h: number, l: number, s: number) => number;
|
||||
rotlSL: (h: number, l: number, s: number) => number;
|
||||
rotlBH: (h: number, l: number, s: number) => number;
|
||||
rotlBL: (h: number, l: number, s: number) => number;
|
||||
add: typeof add;
|
||||
add3L: (Al: number, Bl: number, Cl: number) => number;
|
||||
add3H: (low: number, Ah: number, Bh: number, Ch: number) => number;
|
||||
add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number;
|
||||
add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number;
|
||||
add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number;
|
||||
add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number;
|
||||
};
|
||||
export default u64;
|
||||
//# sourceMappingURL=_u64.d.ts.map
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,70 @@
|
||||
"use strict";
|
||||
/* --------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
* ------------------------------------------------------------------------------------------ */
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Encodings = void 0;
|
||||
var Encodings;
|
||||
(function (Encodings) {
|
||||
function getEncodingHeaderValue(encodings) {
|
||||
if (encodings.length === 1) {
|
||||
return encodings[0].name;
|
||||
}
|
||||
const distribute = encodings.length - 1;
|
||||
if (distribute > 1000) {
|
||||
throw new Error(`Quality value can only have three decimal digits but trying to distribute ${encodings.length} elements.`);
|
||||
}
|
||||
const digits = Math.ceil(Math.log10(distribute));
|
||||
const factor = Math.pow(10, digits);
|
||||
const diff = Math.floor((1 / distribute) * factor) / factor;
|
||||
const result = [];
|
||||
let q = 1;
|
||||
for (const encoding of encodings) {
|
||||
result.push(`${encoding.name};q=${q === 1 || q === 0 ? q.toFixed(0) : q.toFixed(digits)}`);
|
||||
q = q - diff;
|
||||
}
|
||||
return result.join(', ');
|
||||
}
|
||||
Encodings.getEncodingHeaderValue = getEncodingHeaderValue;
|
||||
function parseEncodingHeaderValue(value) {
|
||||
const map = new Map();
|
||||
const encodings = value.split(/\s*,\s*/);
|
||||
for (const value of encodings) {
|
||||
const [encoding, q] = parseEncoding(value);
|
||||
if (encoding === '*') {
|
||||
continue;
|
||||
}
|
||||
let values = map.get(q);
|
||||
if (values === undefined) {
|
||||
values = [];
|
||||
map.set(q, values);
|
||||
}
|
||||
values.push(encoding);
|
||||
}
|
||||
const keys = Array.from(map.keys());
|
||||
keys.sort((a, b) => b - a);
|
||||
const result = [];
|
||||
for (const key of keys) {
|
||||
result.push(...map.get(key));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
Encodings.parseEncodingHeaderValue = parseEncodingHeaderValue;
|
||||
function parseEncoding(value) {
|
||||
let q = 1;
|
||||
let encoding;
|
||||
const index = value.indexOf(';q=');
|
||||
if (index !== -1) {
|
||||
const parsed = parseFloat(value.substr(index));
|
||||
if (!Number.isNaN(parsed)) {
|
||||
q = parsed;
|
||||
}
|
||||
encoding = value.substr(0, index);
|
||||
}
|
||||
else {
|
||||
encoding = value;
|
||||
}
|
||||
return [encoding, q];
|
||||
}
|
||||
})(Encodings || (exports.Encodings = Encodings = {}));
|
||||
@@ -0,0 +1,23 @@
|
||||
'use strict';
|
||||
|
||||
const promisify = require('es6-promisify');
|
||||
const jayson = require('../../../');
|
||||
const promiseUtils = require('../utils');
|
||||
|
||||
/**
|
||||
* Constructor for a Jayson Promise Client Tcp
|
||||
* @see Client
|
||||
* @class PromiseClientTcp
|
||||
* @extends ClientTcp
|
||||
* @return {PromiseClientTcp}
|
||||
*/
|
||||
const PromiseClientTcp = function(options) {
|
||||
if(!(this instanceof PromiseClientTcp)) {
|
||||
return new PromiseClientTcp(options);
|
||||
}
|
||||
jayson.Client.tcp.apply(this, arguments);
|
||||
this.request = promiseUtils.wrapClientRequestMethod(this.request.bind(this));
|
||||
};
|
||||
require('util').inherits(PromiseClientTcp, jayson.Client.tcp);
|
||||
|
||||
module.exports = PromiseClientTcp;
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* @fileoverview Rule to flag variables that are never assigned
|
||||
* @author Jacob Bandes-Storch <https://github.com/jtbandes>
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "problem",
|
||||
|
||||
docs: {
|
||||
description:
|
||||
"Disallow `let` or `var` variables that are read but never assigned",
|
||||
dialects: ["JavaScript", "TypeScript"],
|
||||
recommended: true,
|
||||
url: "https://eslint.org/docs/latest/rules/no-unassigned-vars",
|
||||
},
|
||||
|
||||
schema: [],
|
||||
messages: {
|
||||
unassigned:
|
||||
"'{{name}}' is always 'undefined' because it's never assigned.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const sourceCode = context.sourceCode;
|
||||
let insideDeclareModule = false;
|
||||
|
||||
return {
|
||||
"TSModuleDeclaration[declare=true]"() {
|
||||
insideDeclareModule = true;
|
||||
},
|
||||
"TSModuleDeclaration[declare=true]:exit"() {
|
||||
insideDeclareModule = false;
|
||||
},
|
||||
VariableDeclarator(node) {
|
||||
/** @type {import('estree').VariableDeclaration} */
|
||||
const declaration = node.parent;
|
||||
const shouldSkip =
|
||||
node.init ||
|
||||
node.id.type !== "Identifier" ||
|
||||
declaration.kind === "const" ||
|
||||
declaration.declare ||
|
||||
insideDeclareModule;
|
||||
if (shouldSkip) {
|
||||
return;
|
||||
}
|
||||
const [variable] = sourceCode.getDeclaredVariables(node);
|
||||
if (!variable) {
|
||||
return;
|
||||
}
|
||||
let hasRead = false;
|
||||
for (const reference of variable.references) {
|
||||
if (reference.isWrite()) {
|
||||
return;
|
||||
}
|
||||
if (reference.isRead()) {
|
||||
hasRead = true;
|
||||
}
|
||||
}
|
||||
if (!hasRead) {
|
||||
// Variables that are never read should be flagged by no-unused-vars instead
|
||||
return;
|
||||
}
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unassigned",
|
||||
data: { name: node.id.name },
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const {promisify} = require('util');
|
||||
|
||||
const pAccess = promisify(fs.access);
|
||||
|
||||
module.exports = async path => {
|
||||
try {
|
||||
await pAccess(path);
|
||||
return true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports.sync = path => {
|
||||
try {
|
||||
fs.accessSync(path);
|
||||
return true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
'use strict'
|
||||
|
||||
const { EventEmitter } = require('events')
|
||||
const { parentPort } = require('worker_threads')
|
||||
|
||||
function createDestination (mode) {
|
||||
const destination = new EventEmitter()
|
||||
destination.writableEnded = false
|
||||
destination.writableNeedDrain = false
|
||||
|
||||
destination.write = function () {
|
||||
if (mode === 'drain') {
|
||||
destination.writableNeedDrain = true
|
||||
setTimeout(() => {
|
||||
destination.writableNeedDrain = false
|
||||
parentPort.postMessage({
|
||||
code: 'EVENT',
|
||||
name: 'destination-drain'
|
||||
})
|
||||
destination.emit('drain')
|
||||
}, 50)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
destination.end = function () {
|
||||
destination.writableEnded = true
|
||||
destination.emit('close')
|
||||
}
|
||||
|
||||
if (mode === 'flush') {
|
||||
destination.flush = function (cb) {
|
||||
setTimeout(() => {
|
||||
parentPort.postMessage({
|
||||
code: 'EVENT',
|
||||
name: 'destination-flushed'
|
||||
})
|
||||
cb()
|
||||
}, 50)
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === 'flush-sync') {
|
||||
destination.flushSync = function () {
|
||||
parentPort.postMessage({
|
||||
code: 'EVENT',
|
||||
name: 'destination-flush-sync'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === 'exit-on-flush') {
|
||||
destination.flush = function (_cb) {
|
||||
setTimeout(() => {
|
||||
process.exit(0)
|
||||
}, 20)
|
||||
}
|
||||
}
|
||||
|
||||
return destination
|
||||
}
|
||||
|
||||
async function run (opts) {
|
||||
return createDestination(opts.mode)
|
||||
}
|
||||
|
||||
module.exports = run
|
||||
@@ -0,0 +1,40 @@
|
||||
import { promises, existsSync } from 'node:fs';
|
||||
import { isAbsolute, resolve, dirname, join, basename } from 'pathe';
|
||||
|
||||
class NodeSnapshotEnvironment {
|
||||
constructor(options = {}) {
|
||||
this.options = options;
|
||||
}
|
||||
getVersion() {
|
||||
return "1";
|
||||
}
|
||||
getHeader() {
|
||||
return `// Snapshot v${this.getVersion()}`;
|
||||
}
|
||||
async resolveRawPath(testPath, rawPath) {
|
||||
return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath);
|
||||
}
|
||||
async resolvePath(filepath) {
|
||||
return join(join(dirname(filepath), this.options.snapshotsDirName ?? "__snapshots__"), `${basename(filepath)}.snap`);
|
||||
}
|
||||
async prepareDirectory(dirPath) {
|
||||
await promises.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
async saveSnapshotFile(filepath, snapshot) {
|
||||
await promises.mkdir(dirname(filepath), { recursive: true });
|
||||
await promises.writeFile(filepath, snapshot, "utf-8");
|
||||
}
|
||||
async readSnapshotFile(filepath) {
|
||||
if (!existsSync(filepath)) {
|
||||
return null;
|
||||
}
|
||||
return promises.readFile(filepath, "utf-8");
|
||||
}
|
||||
async removeSnapshotFile(filepath) {
|
||||
if (existsSync(filepath)) {
|
||||
await promises.unlink(filepath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { NodeSnapshotEnvironment };
|
||||
@@ -0,0 +1,217 @@
|
||||
import * as eslint from 'eslint';
|
||||
import { Rule, AST } from 'eslint';
|
||||
import * as estree from 'estree';
|
||||
|
||||
declare const READ: unique symbol;
|
||||
declare const CALL: unique symbol;
|
||||
declare const CONSTRUCT: unique symbol;
|
||||
declare const ESM: unique symbol;
|
||||
declare class ReferenceTracker {
|
||||
constructor(globalScope: Scope$2, options?: {
|
||||
mode?: "legacy" | "strict" | undefined;
|
||||
globalObjectNames?: string[] | undefined;
|
||||
} | undefined);
|
||||
private variableStack;
|
||||
private globalScope;
|
||||
private mode;
|
||||
private globalObjectNames;
|
||||
iterateGlobalReferences<T>(traceMap: TraceMap$2<T>): IterableIterator<TrackedReferences$2<T>>;
|
||||
iterateCjsReferences<T_1>(traceMap: TraceMap$2<T_1>): IterableIterator<TrackedReferences$2<T_1>>;
|
||||
iterateEsmReferences<T_2>(traceMap: TraceMap$2<T_2>): IterableIterator<TrackedReferences$2<T_2>>;
|
||||
iteratePropertyReferences<T_3>(node: Expression, traceMap: TraceMap$2<T_3>): IterableIterator<TrackedReferences$2<T_3>>;
|
||||
private _iterateVariableReferences;
|
||||
private _iteratePropertyReferences;
|
||||
private _iterateLhsReferences;
|
||||
private _iterateImportReferences;
|
||||
}
|
||||
declare namespace ReferenceTracker {
|
||||
export { READ };
|
||||
export { CALL };
|
||||
export { CONSTRUCT };
|
||||
export { ESM };
|
||||
}
|
||||
type Scope$2 = eslint.Scope.Scope;
|
||||
type Expression = estree.Expression;
|
||||
type TraceMap$2<T> = TraceMap$1<T>;
|
||||
type TrackedReferences$2<T> = TrackedReferences$1<T>;
|
||||
|
||||
type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1;
|
||||
type StaticValueProvided$1 = {
|
||||
optional?: undefined;
|
||||
value: unknown;
|
||||
};
|
||||
type StaticValueOptional$1 = {
|
||||
optional?: true;
|
||||
value: undefined;
|
||||
};
|
||||
type ReferenceTrackerOptions$1 = {
|
||||
globalObjectNames?: string[];
|
||||
mode?: "legacy" | "strict";
|
||||
};
|
||||
type TraceMap$1<T = unknown> = {
|
||||
[i: string]: TraceMapObject<T>;
|
||||
};
|
||||
type TraceMapObject<T> = {
|
||||
[i: string]: TraceMapObject<T>;
|
||||
[CALL]?: T;
|
||||
[CONSTRUCT]?: T;
|
||||
[READ]?: T;
|
||||
[ESM]?: boolean;
|
||||
};
|
||||
type TrackedReferences$1<T> = {
|
||||
info: T;
|
||||
node: Rule.Node;
|
||||
path: string[];
|
||||
type: typeof CALL | typeof CONSTRUCT | typeof READ;
|
||||
};
|
||||
type HasSideEffectOptions$1 = {
|
||||
considerGetters?: boolean;
|
||||
considerImplicitTypeConversion?: boolean;
|
||||
};
|
||||
type PunctuatorToken<Value extends string> = AST.Token & {
|
||||
type: "Punctuator";
|
||||
value: Value;
|
||||
};
|
||||
type ArrowToken$1 = PunctuatorToken<"=>">;
|
||||
type CommaToken$1 = PunctuatorToken<",">;
|
||||
type SemicolonToken$1 = PunctuatorToken<";">;
|
||||
type ColonToken$1 = PunctuatorToken<":">;
|
||||
type OpeningParenToken$1 = PunctuatorToken<"(">;
|
||||
type ClosingParenToken$1 = PunctuatorToken<")">;
|
||||
type OpeningBracketToken$1 = PunctuatorToken<"[">;
|
||||
type ClosingBracketToken$1 = PunctuatorToken<"]">;
|
||||
type OpeningBraceToken$1 = PunctuatorToken<"{">;
|
||||
type ClosingBraceToken$1 = PunctuatorToken<"}">;
|
||||
|
||||
declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null;
|
||||
type Scope$1 = eslint.Scope.Scope;
|
||||
type Variable = eslint.Scope.Variable;
|
||||
type Identifier = estree.Identifier;
|
||||
|
||||
declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null;
|
||||
type SourceCode$2 = eslint.SourceCode;
|
||||
type FunctionNode$1 = estree.Function;
|
||||
type SourceLocation = estree.SourceLocation;
|
||||
|
||||
declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string;
|
||||
type FunctionNode = estree.Function;
|
||||
|
||||
declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope;
|
||||
type Scope = eslint.Scope.Scope;
|
||||
type Node$4 = estree.Node;
|
||||
|
||||
declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined;
|
||||
type MemberExpression = estree.MemberExpression;
|
||||
type MethodDefinition = estree.MethodDefinition;
|
||||
type Property = estree.Property;
|
||||
type PropertyDefinition = estree.PropertyDefinition;
|
||||
|
||||
declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null;
|
||||
type StaticValue$1 = StaticValue$2;
|
||||
type Node$3 = estree.Node;
|
||||
|
||||
declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null;
|
||||
type Node$2 = estree.Node;
|
||||
|
||||
declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean;
|
||||
type Node$1 = estree.Node;
|
||||
type SourceCode$1 = eslint.SourceCode;
|
||||
|
||||
declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1;
|
||||
declare function isCommaToken(token: CommentOrToken): token is CommaToken$1;
|
||||
declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1;
|
||||
declare function isColonToken(token: CommentOrToken): token is ColonToken$1;
|
||||
declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1;
|
||||
declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1;
|
||||
declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1;
|
||||
declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1;
|
||||
declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1;
|
||||
declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1;
|
||||
declare function isCommentToken(token: CommentOrToken): token is estree.Comment;
|
||||
declare function isNotArrowToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotCommaToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotSemicolonToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotColonToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingParenToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotCommentToken(arg0: CommentOrToken): boolean;
|
||||
type Token = eslint.AST.Token;
|
||||
type Comment = estree.Comment;
|
||||
type CommentOrToken = Comment | Token;
|
||||
|
||||
declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean;
|
||||
type Node = estree.Node;
|
||||
type SourceCode = eslint.SourceCode;
|
||||
|
||||
declare class PatternMatcher {
|
||||
constructor(pattern: RegExp, options?: {
|
||||
escaped?: boolean | undefined;
|
||||
} | undefined);
|
||||
execAll(str: string): IterableIterator<RegExpExecArray>;
|
||||
test(str: string): boolean;
|
||||
[Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string;
|
||||
}
|
||||
|
||||
declare namespace _default {
|
||||
export { CALL };
|
||||
export { CONSTRUCT };
|
||||
export { ESM };
|
||||
export { findVariable };
|
||||
export { getFunctionHeadLocation };
|
||||
export { getFunctionNameWithKind };
|
||||
export { getInnermostScope };
|
||||
export { getPropertyName };
|
||||
export { getStaticValue };
|
||||
export { getStringIfConstant };
|
||||
export { hasSideEffect };
|
||||
export { isArrowToken };
|
||||
export { isClosingBraceToken };
|
||||
export { isClosingBracketToken };
|
||||
export { isClosingParenToken };
|
||||
export { isColonToken };
|
||||
export { isCommaToken };
|
||||
export { isCommentToken };
|
||||
export { isNotArrowToken };
|
||||
export { isNotClosingBraceToken };
|
||||
export { isNotClosingBracketToken };
|
||||
export { isNotClosingParenToken };
|
||||
export { isNotColonToken };
|
||||
export { isNotCommaToken };
|
||||
export { isNotCommentToken };
|
||||
export { isNotOpeningBraceToken };
|
||||
export { isNotOpeningBracketToken };
|
||||
export { isNotOpeningParenToken };
|
||||
export { isNotSemicolonToken };
|
||||
export { isOpeningBraceToken };
|
||||
export { isOpeningBracketToken };
|
||||
export { isOpeningParenToken };
|
||||
export { isParenthesized };
|
||||
export { isSemicolonToken };
|
||||
export { PatternMatcher };
|
||||
export { READ };
|
||||
export { ReferenceTracker };
|
||||
}
|
||||
|
||||
type StaticValue = StaticValue$2;
|
||||
type StaticValueOptional = StaticValueOptional$1;
|
||||
type StaticValueProvided = StaticValueProvided$1;
|
||||
type ReferenceTrackerOptions = ReferenceTrackerOptions$1;
|
||||
type TraceMap<T> = TraceMap$1<T>;
|
||||
type TrackedReferences<T> = TrackedReferences$1<T>;
|
||||
type HasSideEffectOptions = HasSideEffectOptions$1;
|
||||
type ArrowToken = ArrowToken$1;
|
||||
type CommaToken = CommaToken$1;
|
||||
type SemicolonToken = SemicolonToken$1;
|
||||
type ColonToken = ColonToken$1;
|
||||
type OpeningParenToken = OpeningParenToken$1;
|
||||
type ClosingParenToken = ClosingParenToken$1;
|
||||
type OpeningBracketToken = OpeningBracketToken$1;
|
||||
type ClosingBracketToken = ClosingBracketToken$1;
|
||||
type OpeningBraceToken = OpeningBraceToken$1;
|
||||
type ClosingBraceToken = ClosingBraceToken$1;
|
||||
|
||||
export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"name": "@solana/codecs-numbers",
|
||||
"version": "2.3.0",
|
||||
"description": "Codecs for numbers of different sizes and endianness",
|
||||
"exports": {
|
||||
"edge-light": {
|
||||
"import": "./dist/index.node.mjs",
|
||||
"require": "./dist/index.node.cjs"
|
||||
},
|
||||
"workerd": {
|
||||
"import": "./dist/index.node.mjs",
|
||||
"require": "./dist/index.node.cjs"
|
||||
},
|
||||
"browser": {
|
||||
"import": "./dist/index.browser.mjs",
|
||||
"require": "./dist/index.browser.cjs"
|
||||
},
|
||||
"node": {
|
||||
"import": "./dist/index.node.mjs",
|
||||
"require": "./dist/index.node.cjs"
|
||||
},
|
||||
"react-native": "./dist/index.native.mjs",
|
||||
"types": "./dist/types/index.d.ts"
|
||||
},
|
||||
"browser": {
|
||||
"./dist/index.node.cjs": "./dist/index.browser.cjs",
|
||||
"./dist/index.node.mjs": "./dist/index.browser.mjs"
|
||||
},
|
||||
"main": "./dist/index.node.cjs",
|
||||
"module": "./dist/index.node.mjs",
|
||||
"react-native": "./dist/index.native.mjs",
|
||||
"types": "./dist/types/index.d.ts",
|
||||
"type": "commonjs",
|
||||
"files": [
|
||||
"./dist/"
|
||||
],
|
||||
"sideEffects": false,
|
||||
"keywords": [
|
||||
"blockchain",
|
||||
"solana",
|
||||
"web3"
|
||||
],
|
||||
"author": "Solana Labs Maintainers <maintainers@solanalabs.com>",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/anza-xyz/kit"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/anza-xyz/kit/issues"
|
||||
},
|
||||
"browserslist": [
|
||||
"supports bigint and not dead",
|
||||
"maintained node versions"
|
||||
],
|
||||
"dependencies": {
|
||||
"@solana/codecs-core": "2.3.0",
|
||||
"@solana/errors": "2.3.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": ">=5.3.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.18.0"
|
||||
},
|
||||
"scripts": {
|
||||
"compile:docs": "typedoc",
|
||||
"compile:js": "tsup --config build-scripts/tsup.config.package.ts",
|
||||
"compile:typedefs": "tsc -p ./tsconfig.declarations.json",
|
||||
"dev": "jest -c ../../node_modules/@solana/test-config/jest-dev.config.ts --rootDir . --watch",
|
||||
"publish-impl": "npm view $npm_package_name@$npm_package_version > /dev/null 2>&1 || (pnpm publish --tag ${PUBLISH_TAG:-canary} --access public --no-git-checks && (([ \"$PUBLISH_TAG\" != \"canary\" ] && pnpm dist-tag add $npm_package_name@$npm_package_version latest) || true))",
|
||||
"publish-packages": "pnpm prepublishOnly && pnpm publish-impl",
|
||||
"style:fix": "pnpm eslint --fix src && pnpm prettier --log-level warn --ignore-unknown --write ./*",
|
||||
"test:lint": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-lint.config.ts --rootDir . --silent",
|
||||
"test:prettier": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-prettier.config.ts --rootDir . --silent",
|
||||
"test:treeshakability:browser": "agadoo dist/index.browser.mjs",
|
||||
"test:treeshakability:native": "agadoo dist/index.native.mjs",
|
||||
"test:treeshakability:node": "agadoo dist/index.node.mjs",
|
||||
"test:typecheck": "tsc --noEmit",
|
||||
"test:unit:browser": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-unit.config.browser.ts --rootDir . --silent",
|
||||
"test:unit:node": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-unit.config.node.ts --rootDir . --silent"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { Diagnostic, Program, SourceFile } from 'typescript';
|
||||
export interface SemanticOrSyntacticError extends Diagnostic {
|
||||
message: string;
|
||||
}
|
||||
/**
|
||||
* By default, diagnostics from the TypeScript compiler contain all errors - regardless of whether
|
||||
* they are related to generic ECMAScript standards, or TypeScript-specific constructs.
|
||||
*
|
||||
* Therefore, we filter out all diagnostics, except for the ones we explicitly want to consider when
|
||||
* the user opts in to throwing errors on semantic issues.
|
||||
*/
|
||||
export declare function getFirstSemanticOrSyntacticError(program: Program, ast: SourceFile): SemanticOrSyntacticError | undefined;
|
||||
@@ -0,0 +1,30 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = function ({ key, objectKey }) {
|
||||
// special case for parsers
|
||||
const isParser =
|
||||
objectKey === "parser" && (key === "parse" || key === "parseForESLint");
|
||||
const parserMessage = `
|
||||
This typically happens when you're using a custom parser that does not
|
||||
provide a "meta" property, which is how ESLint determines the serialized
|
||||
representation. Please open an issue with the maintainer of the custom parser
|
||||
and share this link:
|
||||
|
||||
https://eslint.org/docs/latest/extend/custom-parsers#meta-data-in-custom-parsers
|
||||
`.trim();
|
||||
|
||||
return `
|
||||
The requested operation requires ESLint to serialize configuration data,
|
||||
but the configuration key "${objectKey}.${key}" contains a function value,
|
||||
which cannot be serialized.
|
||||
|
||||
${
|
||||
isParser
|
||||
? parserMessage
|
||||
: "Please double-check your configuration for errors."
|
||||
}
|
||||
|
||||
If you still have problems, please stop by https://eslint.org/chat/help to chat
|
||||
with the team.
|
||||
`.trimStart();
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
export type MessageIds = 'preferReadonly';
|
||||
export type Options = [
|
||||
{
|
||||
onlyInlineLambdas?: boolean;
|
||||
}
|
||||
];
|
||||
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferReadonly", Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,33 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
/// <reference no-default-lib="true"/>
|
||||
|
||||
/////////////////////////////
|
||||
/// Worker Async Iterable APIs
|
||||
/////////////////////////////
|
||||
|
||||
interface FileSystemDirectoryHandle {
|
||||
[Symbol.asyncIterator](): AsyncIterableIterator<[string, FileSystemHandle]>;
|
||||
entries(): AsyncIterableIterator<[string, FileSystemHandle]>;
|
||||
keys(): AsyncIterableIterator<string>;
|
||||
values(): AsyncIterableIterator<FileSystemHandle>;
|
||||
}
|
||||
|
||||
interface ReadableStream<R = any> {
|
||||
[Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): AsyncIterableIterator<R>;
|
||||
values(options?: ReadableStreamIteratorOptions): AsyncIterableIterator<R>;
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
"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: 'no-unnecessary-type-arguments',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description: 'Disallow type arguments that are equal to the default',
|
||||
recommended: 'strict',
|
||||
requiresTypeChecking: true,
|
||||
},
|
||||
fixable: 'code',
|
||||
messages: {
|
||||
unnecessaryTypeParameter: 'This is the default value for this type parameter, so it can be omitted.',
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
defaultOptions: [],
|
||||
create(context) {
|
||||
const services = (0, util_1.getParserServices)(context);
|
||||
const checker = services.program.getTypeChecker();
|
||||
function getTypeForComparison(type) {
|
||||
if ((0, util_1.isTypeReferenceType)(type)) {
|
||||
return {
|
||||
type: type.target,
|
||||
typeArguments: checker.getTypeArguments(type),
|
||||
};
|
||||
}
|
||||
return {
|
||||
type,
|
||||
typeArguments: [],
|
||||
};
|
||||
}
|
||||
function checkTSArgsAndParameters(esParameters, typeParameters) {
|
||||
// Just check the last one. Must specify previous type parameters if the last one is specified.
|
||||
const i = esParameters.params.length - 1;
|
||||
const arg = esParameters.params[i];
|
||||
const param = typeParameters.at(i);
|
||||
if (!param?.default) {
|
||||
return;
|
||||
}
|
||||
// TODO: would like checker.areTypesEquivalent. https://github.com/Microsoft/TypeScript/issues/13502
|
||||
const defaultType = checker.getTypeAtLocation(param.default);
|
||||
const argType = services.getTypeAtLocation(arg);
|
||||
// this check should handle some of the most simple cases of like strings, numbers, etc
|
||||
if (defaultType !== argType) {
|
||||
// For more complex types (like aliases to generic object types) - TS won't always create a
|
||||
// global shared type object for the type - so we need to resort to manually comparing the
|
||||
// reference type and the passed type arguments.
|
||||
// Also - in case there are aliases - we need to resolve them before we do checks
|
||||
const defaultTypeResolved = getTypeForComparison(defaultType);
|
||||
const argTypeResolved = getTypeForComparison(argType);
|
||||
if (
|
||||
// ensure the resolved type AND all the parameters are the same
|
||||
defaultTypeResolved.type !== argTypeResolved.type ||
|
||||
defaultTypeResolved.typeArguments.length !==
|
||||
argTypeResolved.typeArguments.length ||
|
||||
defaultTypeResolved.typeArguments.some((t, i) => t !== argTypeResolved.typeArguments[i])) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
context.report({
|
||||
node: arg,
|
||||
messageId: 'unnecessaryTypeParameter',
|
||||
fix: fixer => fixer.removeRange(i === 0
|
||||
? esParameters.range
|
||||
: [esParameters.params[i - 1].range[1], arg.range[1]]),
|
||||
});
|
||||
}
|
||||
return {
|
||||
TSTypeParameterInstantiation(node) {
|
||||
// TypeScript does not apply default type parameters in instantiation
|
||||
// expressions, so explicit type args here are always meaningful.
|
||||
if (node.parent.type === utils_1.AST_NODE_TYPES.TSInstantiationExpression) {
|
||||
return;
|
||||
}
|
||||
const expression = services.esTreeNodeToTSNodeMap.get(node);
|
||||
const typeParameters = getTypeParametersFromNode(node, expression, checker);
|
||||
if (typeParameters) {
|
||||
checkTSArgsAndParameters(node, typeParameters);
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
function getTypeParametersFromNode(node, tsNode, checker) {
|
||||
if (ts.isExpressionWithTypeArguments(tsNode)) {
|
||||
return getTypeParametersFromType(node, tsNode.expression, checker);
|
||||
}
|
||||
if (ts.isTypeReferenceNode(tsNode)) {
|
||||
return getTypeParametersFromType(node, tsNode.typeName, checker);
|
||||
}
|
||||
if (ts.isCallExpression(tsNode) ||
|
||||
ts.isNewExpression(tsNode) ||
|
||||
ts.isTaggedTemplateExpression(tsNode) ||
|
||||
ts.isJsxOpeningElement(tsNode) ||
|
||||
ts.isJsxSelfClosingElement(tsNode)) {
|
||||
return getTypeParametersFromCall(node, tsNode, checker);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
function getTypeParametersFromType(node, type, checker) {
|
||||
const symAtLocation = checker.getSymbolAtLocation(type);
|
||||
if (!symAtLocation) {
|
||||
return undefined;
|
||||
}
|
||||
const sym = getAliasedSymbol(symAtLocation, checker);
|
||||
const declarations = sym.getDeclarations();
|
||||
if (!declarations) {
|
||||
return undefined;
|
||||
}
|
||||
const sortedDeclarations = sortDeclarationsByTypeValueContext(node, declarations);
|
||||
return (0, util_1.findFirstResult)(sortedDeclarations, decl => {
|
||||
if (ts.isTypeAliasDeclaration(decl) ||
|
||||
ts.isInterfaceDeclaration(decl) ||
|
||||
ts.isClassLike(decl)) {
|
||||
return decl.typeParameters;
|
||||
}
|
||||
if (ts.isVariableDeclaration(decl)) {
|
||||
return getConstructSignatureDeclaration(symAtLocation, checker)
|
||||
?.typeParameters;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
function getTypeParametersFromCall(node, tsNode, checker) {
|
||||
const sig = checker.getResolvedSignature(tsNode);
|
||||
const sigDecl = sig?.getDeclaration();
|
||||
if (!sigDecl) {
|
||||
return ts.isNewExpression(tsNode)
|
||||
? getTypeParametersFromType(node, tsNode.expression, checker)
|
||||
: undefined;
|
||||
}
|
||||
return sigDecl.typeParameters;
|
||||
}
|
||||
function getAliasedSymbol(symbol, checker) {
|
||||
return tsutils.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias)
|
||||
? checker.getAliasedSymbol(symbol)
|
||||
: symbol;
|
||||
}
|
||||
function isInTypeContext(node) {
|
||||
return (node.parent.type === utils_1.AST_NODE_TYPES.TSInterfaceHeritage ||
|
||||
node.parent.type === utils_1.AST_NODE_TYPES.TSTypeReference ||
|
||||
node.parent.type === utils_1.AST_NODE_TYPES.TSClassImplements);
|
||||
}
|
||||
function isTypeContextDeclaration(decl) {
|
||||
return ts.isTypeAliasDeclaration(decl) || ts.isInterfaceDeclaration(decl);
|
||||
}
|
||||
function typeFirstCompare(declA, declB) {
|
||||
const aIsType = isTypeContextDeclaration(declA);
|
||||
const bIsType = isTypeContextDeclaration(declB);
|
||||
return Number(bIsType) - Number(aIsType);
|
||||
}
|
||||
function sortDeclarationsByTypeValueContext(node, declarations) {
|
||||
const sorted = [...declarations].sort(typeFirstCompare);
|
||||
if (isInTypeContext(node)) {
|
||||
return sorted;
|
||||
}
|
||||
return sorted.reverse();
|
||||
}
|
||||
function getConstructSignatureDeclaration(symbol, checker) {
|
||||
const type = checker.getTypeOfSymbol(symbol);
|
||||
const sig = type.getConstructSignatures();
|
||||
return sig.at(0)?.getDeclaration();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* This is a compatibility ruleset that:
|
||||
* - disables rules from eslint:recommended which are already handled by TypeScript.
|
||||
* - enables rules that make sense due to TS's typechecking / transpilation.
|
||||
*/
|
||||
declare const _default: {
|
||||
overrides: {
|
||||
files: string[];
|
||||
rules: Record<string, 'error' | 'off' | 'warn'>;
|
||||
}[];
|
||||
};
|
||||
export = _default;
|
||||
Reference in New Issue
Block a user