WIP: bootstrap and partial real Solana watcher implementation

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

View File

@@ -0,0 +1,9 @@
{{# def.definitions }}
{{# def.setupKeyword }}
{{ var $comment = it.util.toQuotedString($schema); }}
{{? it.opts.$comment === true }}
console.log({{=$comment}});
{{?? typeof it.opts.$comment == 'function' }}
self._opts.$comment({{=$comment}}, {{=it.util.toQuotedString($errSchemaPath)}}, validate.root.schema);
{{?}}

View File

@@ -0,0 +1,4 @@
// zzz
export function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}

View File

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

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"file":"scriptTarget.js","sourceRoot":"","sources":["../../src/enums/scriptTarget.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,IAAI,YAAiB,CAAC;AAC7B,CAAC,UAAU,YAAY;IACnB,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC;IACpD,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC;IACpD,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC;IACpD,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC;IACpD,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC;IACpD,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC;IACpD,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC;IACpD,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC;IACpD,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,GAAG,QAAQ,CAAC;IACrD,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,GAAG,QAAQ,CAAC;IACrD,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,GAAG,QAAQ,CAAC;IACrD,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,GAAG,QAAQ,CAAC;IACrD,YAAY,CAAC,YAAY,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC,GAAG,MAAM,CAAC;IAClD,YAAY,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,GAAG,QAAQ,CAAC;AACzD,CAAC,CAAC,CAAC,YAAY,IAAI,CAAC,YAAY,GAAG,EAAE,CAAC,CAAC,CAAC"}

View File

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

View File

@@ -0,0 +1,4 @@
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"duplicateValue", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,775 @@
import { plugins, createDOMElementFilter, format as format$1 } from '@vitest/pretty-format';
const ansiColors = {
bold: ['1', '22'],
dim: ['2', '22'],
italic: ['3', '23'],
underline: ['4', '24'],
// 5 & 6 are blinking
inverse: ['7', '27'],
hidden: ['8', '28'],
strike: ['9', '29'],
// 10-20 are fonts
// 21-29 are resets for 1-9
black: ['30', '39'],
red: ['31', '39'],
green: ['32', '39'],
yellow: ['33', '39'],
blue: ['34', '39'],
magenta: ['35', '39'],
cyan: ['36', '39'],
white: ['37', '39'],
brightblack: ['30;1', '39'],
brightred: ['31;1', '39'],
brightgreen: ['32;1', '39'],
brightyellow: ['33;1', '39'],
brightblue: ['34;1', '39'],
brightmagenta: ['35;1', '39'],
brightcyan: ['36;1', '39'],
brightwhite: ['37;1', '39'],
grey: ['90', '39'],
};
const styles = {
special: 'cyan',
number: 'yellow',
bigint: 'yellow',
boolean: 'yellow',
undefined: 'grey',
null: 'bold',
string: 'green',
symbol: 'green',
date: 'magenta',
regexp: 'red',
};
const truncator = '…';
function colorise(value, styleType) {
const color = ansiColors[styles[styleType]] || ansiColors[styleType] || '';
if (!color) {
return String(value);
}
return `\u001b[${color[0]}m${String(value)}\u001b[${color[1]}m`;
}
function normaliseOptions({ showHidden = false, depth = 2, colors = false, customInspect = true, showProxy = false, maxArrayLength = Infinity, breakLength = Infinity, seen = [],
// eslint-disable-next-line no-shadow
truncate = Infinity, stylize = String, } = {}, inspect) {
const options = {
showHidden: Boolean(showHidden),
depth: Number(depth),
colors: Boolean(colors),
customInspect: Boolean(customInspect),
showProxy: Boolean(showProxy),
maxArrayLength: Number(maxArrayLength),
breakLength: Number(breakLength),
truncate: Number(truncate),
seen,
inspect,
stylize,
};
if (options.colors) {
options.stylize = colorise;
}
return options;
}
function isHighSurrogate(char) {
return char >= '\ud800' && char <= '\udbff';
}
function truncate(string, length, tail = truncator) {
string = String(string);
const tailLength = tail.length;
const stringLength = string.length;
if (tailLength > length && stringLength > tailLength) {
return tail;
}
if (stringLength > length && stringLength > tailLength) {
let end = length - tailLength;
if (end > 0 && isHighSurrogate(string[end - 1])) {
end = end - 1;
}
return `${string.slice(0, end)}${tail}`;
}
return string;
}
// eslint-disable-next-line complexity
function inspectList(list, options, inspectItem, separator = ', ') {
inspectItem = inspectItem || options.inspect;
const size = list.length;
if (size === 0)
return '';
const originalLength = options.truncate;
let output = '';
let peek = '';
let truncated = '';
for (let i = 0; i < size; i += 1) {
const last = i + 1 === list.length;
const secondToLast = i + 2 === list.length;
truncated = `${truncator}(${list.length - i})`;
const value = list[i];
// If there is more than one remaining we need to account for a separator of `, `
options.truncate = originalLength - output.length - (last ? 0 : separator.length);
const string = peek || inspectItem(value, options) + (last ? '' : separator);
const nextLength = output.length + string.length;
const truncatedLength = nextLength + truncated.length;
// If this is the last element, and adding it would
// take us over length, but adding the truncator wouldn't - then break now
if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) {
break;
}
// If this isn't the last or second to last element to scan,
// but the string is already over length then break here
if (!last && !secondToLast && truncatedLength > originalLength) {
break;
}
// Peek at the next string to determine if we should
// break early before adding this item to the output
peek = last ? '' : inspectItem(list[i + 1], options) + (secondToLast ? '' : separator);
// If we have one element left, but this element and
// the next takes over length, the break early
if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) {
break;
}
output += string;
// If the next element takes us to length -
// but there are more after that, then we should truncate now
if (!last && !secondToLast && nextLength + peek.length >= originalLength) {
truncated = `${truncator}(${list.length - i - 1})`;
break;
}
truncated = '';
}
return `${output}${truncated}`;
}
function quoteComplexKey(key) {
if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) {
return key;
}
return JSON.stringify(key)
.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
}
function inspectProperty([key, value], options) {
options.truncate -= 2;
if (typeof key === 'string') {
key = quoteComplexKey(key);
}
else if (typeof key !== 'number') {
key = `[${options.inspect(key, options)}]`;
}
options.truncate -= key.length;
value = options.inspect(value, options);
return `${key}: ${value}`;
}
function inspectArray(array, options) {
// Object.keys will always output the Array indices first, so we can slice by
// `array.length` to get non-index properties
const nonIndexProperties = Object.keys(array).slice(array.length);
if (!array.length && !nonIndexProperties.length)
return '[]';
options.truncate -= 4;
const listContents = inspectList(array, options);
options.truncate -= listContents.length;
let propertyContents = '';
if (nonIndexProperties.length) {
propertyContents = inspectList(nonIndexProperties.map(key => [key, array[key]]), options, inspectProperty);
}
return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ''} ]`;
}
const getArrayName = (array) => {
// We need to special case Node.js' Buffers, which report to be Uint8Array
// @ts-ignore
if (typeof Buffer === 'function' && array instanceof Buffer) {
return 'Buffer';
}
if (array[Symbol.toStringTag]) {
return array[Symbol.toStringTag];
}
return array.constructor.name;
};
function inspectTypedArray(array, options) {
const name = getArrayName(array);
options.truncate -= name.length + 4;
// Object.keys will always output the Array indices first, so we can slice by
// `array.length` to get non-index properties
const nonIndexProperties = Object.keys(array).slice(array.length);
if (!array.length && !nonIndexProperties.length)
return `${name}[]`;
// As we know TypedArrays only contain Unsigned Integers, we can skip inspecting each one and simply
// stylise the toString() value of them
let output = '';
for (let i = 0; i < array.length; i++) {
const string = `${options.stylize(truncate(array[i], options.truncate), 'number')}${i === array.length - 1 ? '' : ', '}`;
options.truncate -= string.length;
if (array[i] !== array.length && options.truncate <= 3) {
output += `${truncator}(${array.length - array[i] + 1})`;
break;
}
output += string;
}
let propertyContents = '';
if (nonIndexProperties.length) {
propertyContents = inspectList(nonIndexProperties.map(key => [key, array[key]]), options, inspectProperty);
}
return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ''} ]`;
}
function inspectDate(dateObject, options) {
const stringRepresentation = dateObject.toJSON();
if (stringRepresentation === null) {
return 'Invalid Date';
}
const split = stringRepresentation.split('T');
const date = split[0];
// If we need to - truncate the time portion, but never the date
return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, 'date');
}
function inspectFunction(func, options) {
const functionType = func[Symbol.toStringTag] || 'Function';
const name = func.name;
if (!name) {
return options.stylize(`[${functionType}]`, 'special');
}
return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, 'special');
}
function inspectMapEntry([key, value], options) {
options.truncate -= 4;
key = options.inspect(key, options);
options.truncate -= key.length;
value = options.inspect(value, options);
return `${key} => ${value}`;
}
// IE11 doesn't support `map.entries()`
function mapToEntries(map) {
const entries = [];
map.forEach((value, key) => {
entries.push([key, value]);
});
return entries;
}
function inspectMap(map, options) {
if (map.size === 0)
return 'Map{}';
options.truncate -= 7;
return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }`;
}
const isNaN = Number.isNaN || (i => i !== i); // eslint-disable-line no-self-compare
function inspectNumber(number, options) {
if (isNaN(number)) {
return options.stylize('NaN', 'number');
}
if (number === Infinity) {
return options.stylize('Infinity', 'number');
}
if (number === -Infinity) {
return options.stylize('-Infinity', 'number');
}
if (number === 0) {
return options.stylize(1 / number === Infinity ? '+0' : '-0', 'number');
}
return options.stylize(truncate(String(number), options.truncate), 'number');
}
function inspectBigInt(number, options) {
let nums = truncate(number.toString(), options.truncate - 1);
if (nums !== truncator)
nums += 'n';
return options.stylize(nums, 'bigint');
}
function inspectRegExp(value, options) {
const flags = value.toString().split('/')[2];
const sourceLength = options.truncate - (2 + flags.length);
const source = value.source;
return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, 'regexp');
}
// IE11 doesn't support `Array.from(set)`
function arrayFromSet(set) {
const values = [];
set.forEach(value => {
values.push(value);
});
return values;
}
function inspectSet(set, options) {
if (set.size === 0)
return 'Set{}';
options.truncate -= 7;
return `Set{ ${inspectList(arrayFromSet(set), options)} }`;
}
const stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5" +
'\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]', 'g');
const escapeCharacters = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
"'": "\\'",
'\\': '\\\\',
};
const hex = 16;
function escape(char) {
return (escapeCharacters[char] ||
`\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-4)}`);
}
function inspectString(string, options) {
if (stringEscapeChars.test(string)) {
string = string.replace(stringEscapeChars, escape);
}
return options.stylize(`'${truncate(string, options.truncate - 2)}'`, 'string');
}
function inspectSymbol(value) {
if ('description' in Symbol.prototype) {
return value.description ? `Symbol(${value.description})` : 'Symbol()';
}
return value.toString();
}
const getPromiseValue = () => 'Promise{…}';
function inspectObject$1(object, options) {
const properties = Object.getOwnPropertyNames(object);
const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : [];
if (properties.length === 0 && symbols.length === 0) {
return '{}';
}
options.truncate -= 4;
options.seen = options.seen || [];
if (options.seen.includes(object)) {
return '[Circular]';
}
options.seen.push(object);
const propertyContents = inspectList(properties.map(key => [key, object[key]]), options, inspectProperty);
const symbolContents = inspectList(symbols.map(key => [key, object[key]]), options, inspectProperty);
options.seen.pop();
let sep = '';
if (propertyContents && symbolContents) {
sep = ', ';
}
return `{ ${propertyContents}${sep}${symbolContents} }`;
}
const toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag ? Symbol.toStringTag : false;
function inspectClass(value, options) {
let name = '';
if (toStringTag && toStringTag in value) {
name = value[toStringTag];
}
name = name || value.constructor.name;
// Babel transforms anonymous classes to the name `_class`
if (!name || name === '_class') {
name = '<Anonymous Class>';
}
options.truncate -= name.length;
return `${name}${inspectObject$1(value, options)}`;
}
function inspectArguments(args, options) {
if (args.length === 0)
return 'Arguments[]';
options.truncate -= 13;
return `Arguments[ ${inspectList(args, options)} ]`;
}
const errorKeys = [
'stack',
'line',
'column',
'name',
'message',
'fileName',
'lineNumber',
'columnNumber',
'number',
'description',
'cause',
];
function inspectObject(error, options) {
const properties = Object.getOwnPropertyNames(error).filter(key => errorKeys.indexOf(key) === -1);
const name = error.name;
options.truncate -= name.length;
let message = '';
if (typeof error.message === 'string') {
message = truncate(error.message, options.truncate);
}
else {
properties.unshift('message');
}
message = message ? `: ${message}` : '';
options.truncate -= message.length + 5;
options.seen = options.seen || [];
if (options.seen.includes(error)) {
return '[Circular]';
}
options.seen.push(error);
const propertyContents = inspectList(properties.map(key => [key, error[key]]), options, inspectProperty);
return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ''}`;
}
function inspectAttribute([key, value], options) {
options.truncate -= 3;
if (!value) {
return `${options.stylize(String(key), 'yellow')}`;
}
return `${options.stylize(String(key), 'yellow')}=${options.stylize(`"${value}"`, 'string')}`;
}
function inspectNodeCollection(collection, options) {
return inspectList(collection, options, inspectNode, '\n');
}
function inspectNode(node, options) {
switch (node.nodeType) {
case 1:
return inspectHTML(node, options);
case 3:
return options.inspect(node.data, options);
default:
return options.inspect(node, options);
}
}
// @ts-ignore (Deno doesn't have Element)
function inspectHTML(element, options) {
const properties = element.getAttributeNames();
const name = element.tagName.toLowerCase();
const head = options.stylize(`<${name}`, 'special');
const headClose = options.stylize(`>`, 'special');
const tail = options.stylize(`</${name}>`, 'special');
options.truncate -= name.length * 2 + 5;
let propertyContents = '';
if (properties.length > 0) {
propertyContents += ' ';
propertyContents += inspectList(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute, ' ');
}
options.truncate -= propertyContents.length;
const truncate = options.truncate;
let children = inspectNodeCollection(element.children, options);
if (children && children.length > truncate) {
children = `${truncator}(${element.children.length})`;
}
return `${head}${propertyContents}${headClose}${children}${tail}`;
}
/* !
* loupe
* Copyright(c) 2013 Jake Luer <jake@alogicalparadox.com>
* MIT Licensed
*/
const symbolsSupported = typeof Symbol === 'function' && typeof Symbol.for === 'function';
const chaiInspect = symbolsSupported ? Symbol.for('chai/inspect') : '@@chai/inspect';
const nodeInspect = Symbol.for('nodejs.util.inspect.custom');
const constructorMap = new WeakMap();
const stringTagMap = {};
const baseTypesMap = {
undefined: (value, options) => options.stylize('undefined', 'undefined'),
null: (value, options) => options.stylize('null', 'null'),
boolean: (value, options) => options.stylize(String(value), 'boolean'),
Boolean: (value, options) => options.stylize(String(value), 'boolean'),
number: inspectNumber,
Number: inspectNumber,
bigint: inspectBigInt,
BigInt: inspectBigInt,
string: inspectString,
String: inspectString,
function: inspectFunction,
Function: inspectFunction,
symbol: inspectSymbol,
// A Symbol polyfill will return `Symbol` not `symbol` from typedetect
Symbol: inspectSymbol,
Array: inspectArray,
Date: inspectDate,
Map: inspectMap,
Set: inspectSet,
RegExp: inspectRegExp,
Promise: getPromiseValue,
// WeakSet, WeakMap are totally opaque to us
WeakSet: (value, options) => options.stylize('WeakSet{…}', 'special'),
WeakMap: (value, options) => options.stylize('WeakMap{…}', 'special'),
Arguments: inspectArguments,
Int8Array: inspectTypedArray,
Uint8Array: inspectTypedArray,
Uint8ClampedArray: inspectTypedArray,
Int16Array: inspectTypedArray,
Uint16Array: inspectTypedArray,
Int32Array: inspectTypedArray,
Uint32Array: inspectTypedArray,
Float32Array: inspectTypedArray,
Float64Array: inspectTypedArray,
Generator: () => '',
DataView: () => '',
ArrayBuffer: () => '',
Error: inspectObject,
HTMLCollection: inspectNodeCollection,
NodeList: inspectNodeCollection,
};
// eslint-disable-next-line complexity
const inspectCustom = (value, options, type, inspectFn) => {
if (chaiInspect in value && typeof value[chaiInspect] === 'function') {
return value[chaiInspect](options);
}
if (nodeInspect in value && typeof value[nodeInspect] === 'function') {
return value[nodeInspect](options.depth, options, inspectFn);
}
if ('inspect' in value && typeof value.inspect === 'function') {
return value.inspect(options.depth, options);
}
if ('constructor' in value && constructorMap.has(value.constructor)) {
return constructorMap.get(value.constructor)(value, options);
}
if (stringTagMap[type]) {
return stringTagMap[type](value, options);
}
return '';
};
const toString = Object.prototype.toString;
// eslint-disable-next-line complexity
function inspect$1(value, opts = {}) {
const options = normaliseOptions(opts, inspect$1);
const { customInspect } = options;
let type = value === null ? 'null' : typeof value;
if (type === 'object') {
type = toString.call(value).slice(8, -1);
}
// If it is a base value that we already support, then use Loupe's inspector
if (type in baseTypesMap) {
return baseTypesMap[type](value, options);
}
// If `options.customInspect` is set to true then try to use the custom inspector
if (customInspect && value) {
const output = inspectCustom(value, options, type, inspect$1);
if (output) {
if (typeof output === 'string')
return output;
return inspect$1(output, options);
}
}
const proto = value ? Object.getPrototypeOf(value) : false;
// If it's a plain Object then use Loupe's inspector
if (proto === Object.prototype || proto === null) {
return inspectObject$1(value, options);
}
// Specifically account for HTMLElements
// @ts-ignore
if (value && typeof HTMLElement === 'function' && value instanceof HTMLElement) {
return inspectHTML(value, options);
}
if ('constructor' in value) {
// If it is a class, inspect it like an object but add the constructor name
if (value.constructor !== Object) {
return inspectClass(value, options);
}
// If it is an object with an anonymous prototype, display it as an object.
return inspectObject$1(value, options);
}
// last chance to check if it's an object
if (value === Object(value)) {
return inspectObject$1(value, options);
}
// We have run out of options! Just stringify the value
return options.stylize(String(value), type);
}
const { AsymmetricMatcher, DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent } = plugins;
const PLUGINS = [
ReactTestComponent,
ReactElement,
DOMElement,
DOMCollection,
Immutable,
AsymmetricMatcher
];
function stringify(object, maxDepth = 10, { maxLength, filterNode, ...options } = {}) {
const MAX_LENGTH = maxLength ?? 1e4;
let result;
// Convert string selector to filter function
const filterFn = typeof filterNode === "string" ? createNodeFilterFromSelector(filterNode) : filterNode;
const plugins = filterFn ? [
ReactTestComponent,
ReactElement,
createDOMElementFilter(filterFn),
DOMCollection,
Immutable,
AsymmetricMatcher
] : PLUGINS;
try {
result = format$1(object, {
maxDepth,
escapeString: false,
plugins,
...options
});
} catch {
result = format$1(object, {
callToJSON: false,
maxDepth,
escapeString: false,
plugins,
...options
});
}
// Prevents infinite loop https://github.com/vitest-dev/vitest/issues/7249
return result.length >= MAX_LENGTH && maxDepth > 1 ? stringify(object, Math.floor(Math.min(maxDepth, Number.MAX_SAFE_INTEGER) / 2), {
maxLength,
filterNode,
...options
}) : result;
}
function createNodeFilterFromSelector(selector) {
const ELEMENT_NODE = 1;
const COMMENT_NODE = 8;
return (node) => {
// Filter out comments
if (node.nodeType === COMMENT_NODE) {
return false;
}
// Filter out elements matching the selector
if (node.nodeType === ELEMENT_NODE && node.matches) {
try {
return !node.matches(selector);
} catch {
return true;
}
}
return true;
};
}
const formatRegExp = /%[sdjifoOc%]/g;
function baseFormat(args, options = {}) {
const formatArg = (item, inspecOptions) => {
if (options.prettifyObject) {
return stringify(item, undefined, {
printBasicPrototype: false,
escapeString: false
});
}
return inspect(item, inspecOptions);
};
if (typeof args[0] !== "string") {
const objects = [];
for (let i = 0; i < args.length; i++) {
objects.push(formatArg(args[i], {
depth: 0,
colors: false
}));
}
return objects.join(" ");
}
const len = args.length;
let i = 1;
const template = args[0];
let str = String(template).replace(formatRegExp, (x) => {
if (x === "%%") {
return "%";
}
if (i >= len) {
return x;
}
switch (x) {
case "%s": {
const value = args[i++];
if (typeof value === "bigint") {
return `${value.toString()}n`;
}
if (typeof value === "number" && value === 0 && 1 / value < 0) {
return "-0";
}
if (typeof value === "object" && value !== null) {
if (typeof value.toString === "function" && value.toString !== Object.prototype.toString) {
return value.toString();
}
return formatArg(value, {
depth: 0,
colors: false
});
}
return String(value);
}
case "%d": {
const value = args[i++];
if (typeof value === "bigint") {
return `${value.toString()}n`;
}
if (typeof value === "symbol") {
return "NaN";
}
return Number(value).toString();
}
case "%i": {
const value = args[i++];
if (typeof value === "bigint") {
return `${value.toString()}n`;
}
return Number.parseInt(String(value)).toString();
}
case "%f": return Number.parseFloat(String(args[i++])).toString();
case "%o": return formatArg(args[i++], {
showHidden: true,
showProxy: true
});
case "%O": return formatArg(args[i++]);
case "%c": {
i++;
return "";
}
case "%j": try {
return JSON.stringify(args[i++]);
} catch (err) {
const m = err.message;
if (m.includes("circular structure") || m.includes("cyclic structures") || m.includes("cyclic object")) {
return "[Circular]";
}
throw err;
}
default: return x;
}
});
for (let x = args[i]; i < len; x = args[++i]) {
if (x === null || typeof x !== "object") {
str += ` ${typeof x === "symbol" ? x.toString() : x}`;
} else {
str += ` ${formatArg(x)}`;
}
}
return str;
}
function format(...args) {
return baseFormat(args);
}
function browserFormat(...args) {
return baseFormat(args, { prettifyObject: true });
}
function inspect(obj, options = {}) {
if (options.truncate === 0) {
options.truncate = Number.POSITIVE_INFINITY;
}
return inspect$1(obj, options);
}
function objDisplay(obj, options = {}) {
if (typeof options.truncate === "undefined") {
options.truncate = 40;
}
const str = inspect(obj, options);
const type = Object.prototype.toString.call(obj);
if (options.truncate && str.length >= options.truncate) {
if (type === "[object Function]") {
const fn = obj;
return !fn.name ? "[Function]" : `[Function: ${fn.name}]`;
} else if (type === "[object Array]") {
return `[ Array(${obj.length}) ]`;
} else if (type === "[object Object]") {
const keys = Object.keys(obj);
const kstr = keys.length > 2 ? `${keys.splice(0, 2).join(", ")}, ...` : keys.join(", ");
return `{ Object (${kstr}) }`;
} else {
return str;
}
}
return str;
}
export { browserFormat, format, formatRegExp, inspect, objDisplay, stringify };

View File

@@ -0,0 +1,9 @@
var arrayLikeToArray = require("./arrayLikeToArray.js");
function _unsupportedIterableToArray(r, a) {
if (r) {
if ("string" == typeof r) return arrayLikeToArray(r, a);
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? arrayLikeToArray(r, a) : void 0;
}
}
module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,17 @@
import type * as ts from 'typescript';
declare module 'typescript' {
interface AssertClause extends ts.ImportAttributes {
}
interface AssertEntry extends ts.ImportAttribute {
}
interface SatisfiesExpression extends ts.Node {
}
interface JsxNamespacedName extends ts.Node {
}
interface ImportAttribute extends ts.Node {
}
interface ImportAttributes extends ts.Node {
}
}
export type TSToken = ts.Token<ts.SyntaxKind>;
export type TSNode = ts.ArrayBindingPattern | ts.ArrayLiteralExpression | ts.ArrayTypeNode | ts.ArrowFunction | ts.AsExpression | ts.AssertClause | ts.AssertEntry | ts.AwaitExpression | ts.BigIntLiteral | ts.BinaryExpression | ts.BindingElement | ts.Block | ts.BooleanLiteral | ts.BreakStatement | ts.Bundle | ts.CallExpression | ts.CallSignatureDeclaration | ts.CaseBlock | ts.CaseClause | ts.CatchClause | ts.ClassDeclaration | ts.ClassExpression | ts.ClassStaticBlockDeclaration | ts.CommaListExpression | ts.ComputedPropertyName | ts.ConditionalExpression | ts.ConditionalTypeNode | ts.ConstructorDeclaration | ts.ConstructorTypeNode | ts.ConstructSignatureDeclaration | ts.ContinueStatement | ts.DebuggerStatement | ts.Decorator | ts.DefaultClause | ts.DeleteExpression | ts.DoStatement | ts.ElementAccessExpression | ts.EmptyStatement | ts.EnumDeclaration | ts.EnumMember | ts.ExportAssignment | ts.ExportDeclaration | ts.ExportSpecifier | ts.ExpressionStatement | ts.ExpressionWithTypeArguments | ts.ExternalModuleReference | ts.ForInStatement | ts.ForOfStatement | ts.ForStatement | ts.FunctionDeclaration | ts.FunctionExpression | ts.FunctionTypeNode | ts.GetAccessorDeclaration | ts.HeritageClause | ts.Identifier | ts.IfStatement | ts.ImportAttribute | ts.ImportAttributes | ts.ImportClause | ts.ImportDeclaration | ts.ImportEqualsDeclaration | ts.ImportExpression | ts.ImportSpecifier | ts.ImportTypeNode | ts.IndexedAccessTypeNode | ts.IndexSignatureDeclaration | ts.InferTypeNode | ts.InterfaceDeclaration | ts.IntersectionTypeNode | ts.JSDoc | ts.JSDocAllType | ts.JSDocAugmentsTag | ts.JSDocAuthorTag | ts.JSDocCallbackTag | ts.JSDocClassTag | ts.JSDocEnumTag | ts.JSDocFunctionType | ts.JSDocNonNullableType | ts.JSDocNullableType | ts.JSDocOptionalType | ts.JSDocParameterTag | ts.JSDocPropertyTag | ts.JSDocReturnTag | ts.JSDocSignature | ts.JSDocTemplateTag | ts.JSDocThisTag | ts.JSDocTypedefTag | ts.JSDocTypeExpression | ts.JSDocTypeLiteral | ts.JSDocTypeTag | ts.JSDocUnknownTag | ts.JSDocUnknownType | ts.JSDocVariadicType | ts.JsonMinusNumericLiteral | ts.JsxAttribute | ts.JsxClosingElement | ts.JsxClosingFragment | ts.JsxElement | ts.JsxExpression | ts.JsxFragment | ts.JsxNamespacedName | ts.JsxOpeningElement | ts.JsxOpeningFragment | ts.JsxSelfClosingElement | ts.JsxSpreadAttribute | ts.JsxText | ts.KeywordTypeNode | ts.LabeledStatement | ts.LiteralTypeNode | ts.MappedTypeNode | ts.MetaProperty | ts.MethodDeclaration | ts.MethodSignature | ts.MissingDeclaration | ts.Modifier | ts.ModuleBlock | ts.ModuleDeclaration | ts.NamedExports | ts.NamedImports | ts.NamedTupleMember | ts.NamespaceExportDeclaration | ts.NamespaceImport | ts.NewExpression | ts.NonNullExpression | ts.NoSubstitutionTemplateLiteral | ts.NotEmittedStatement | ts.NullLiteral | ts.NumericLiteral | ts.ObjectBindingPattern | ts.ObjectLiteralExpression | ts.OmittedExpression | ts.OptionalTypeNode | ts.ParameterDeclaration | ts.ParenthesizedExpression | ts.ParenthesizedTypeNode | ts.PartiallyEmittedExpression | ts.PostfixUnaryExpression | ts.PrefixUnaryExpression | ts.PrivateIdentifier | ts.PropertyAccessExpression | ts.PropertyAssignment | ts.PropertyDeclaration | ts.PropertySignature | ts.QualifiedName | ts.RegularExpressionLiteral | ts.RestTypeNode | ts.ReturnStatement | ts.SatisfiesExpression | ts.SemicolonClassElement | ts.SetAccessorDeclaration | ts.ShorthandPropertyAssignment | ts.SourceFile | ts.SpreadAssignment | ts.SpreadElement | ts.StringLiteral | ts.SuperExpression | ts.SwitchStatement | ts.SyntheticExpression | ts.TaggedTemplateExpression | ts.TemplateExpression | ts.TemplateHead | ts.TemplateLiteralTypeNode | ts.TemplateMiddle | ts.TemplateSpan | ts.TemplateTail | ts.ThisExpression | ts.ThisTypeNode | ts.ThrowStatement | ts.TryStatement | ts.TupleTypeNode | ts.TypeAliasDeclaration | ts.TypeAssertion | ts.TypeLiteralNode | ts.TypeOfExpression | ts.TypeOperatorNode | ts.TypeParameterDeclaration | ts.TypePredicateNode | ts.TypeQueryNode | ts.TypeReferenceNode | ts.UnionTypeNode | ts.VariableDeclaration | ts.VariableDeclarationList | ts.VariableStatement | ts.VoidExpression | ts.WhileStatement | ts.WithStatement | ts.YieldExpression;

View File

@@ -0,0 +1,155 @@
# Master
# 4.2.5
* remove old try/catch performance hacks, modern runtimes do not require these tricks
# 4.2.4
* [Fixes #305] Confuse webpack
# 4.2.3
* Cleanup testem related build configuration
* Use `prepublishOnly` instead of `prepublish` (thanks @rhysd)
* Add Node.js 9, 8 to testing matrix
* drop now unused s3 deployment files
* internal cleanup (thanks to @bekzod, @mariusschulz)
* Fixup Changelog
# 4.2.2
* Ensure PROMISE_ID works correctly
* internal cleanup (thanks yo @mariusschulz)
# 4.2.1
* drop bower support
# 4.2.0
* drop `dist` from git repo
* add `Promise.prototype.finally`
* update various build related dependencies
* add CDN links
# 4.1.0
* [BUGFIX] Fix memory leak [#269]
* [BUGFIX] Auto Bundles within an AMD Environment [#263]
# 4.0.5
* fix require('es6-promise/auto') for Node < 4
# 4.0.4
* fix asap when using https://github.com/Kinvey/titanium-sdk
# 4.0.3
* fix Readme links
# 4.0.2
* fix require('es6-promise/auto');
# 4.0.0
* no longer polyfill automatically, if needed one can still invoke
`require('es6-promise/auto')` directly.
# 3.3.1
* fix links in readme
# 3.3.0
* support polyfil on WebMAF (playstation env)
* fix tampering related bug global `constructor` was referenced by mistake.
* provide TS Typings
* increase compatibliity with sinon.useFakeTimers();
* update build tools (use rollup)
* directly export promise;
# 3.2.2
* IE8: use isArray
* update build dependencies
# 3.2.1
* fix race tampering issue
* use eslint
* fix Promise.all tampering
* remove unused code
* fix issues with NWJS/electron
# 3.2.0
* improve tamper resistence of Promise.all Promise.race and
Promise.prototype.then (note, this isn't complete, but addresses an exception
when used \w core-js, follow up work will address entirely)
* remove spec incompatible then chaining fast-path
* add eslint
* update build deps
# 3.1.2
* fix node detection issues with NWJS/electron
# 3.1.0
* improve performance of Promise.all when it encounters a non-promise input object input
* then/resolve tamper protection
* reduce AST size of promise constructor, to facilitate more inlining
* Update README.md with details about PhantomJS requirement for running tests
* Mangle and compress the minified version
# 3.0.2
* correctly bump both bower and package.json versions
# 3.0.1
* no longer include dist/test in npm releases
# 3.0.0
* use nextTick() instead of setImmediate() to schedule microtasks with node 0.10. Later versions of
nodes are not affected as they were already using nextTick(). Note that using nextTick() might
trigger a depreciation warning on 0.10 as described at https://github.com/cujojs/when/issues/410.
The reason why nextTick() is preferred is that is setImmediate() would schedule a macrotask
instead of a microtask and might result in a different scheduling.
If needed you can revert to the former behavior as follow:
var Promise = require('es6-promise').Promise;
Promise._setScheduler(setImmediate);
# 2.3.0
* #121: Ability to override the internal asap implementation
* #120: Use an ascii character for an apostrophe, for source maps
# 2.2.0
* #116: Expose asap() and a way to override the scheduling mechanism on Promise
* Lock to v0.2.3 of ember-cli
# 2.1.1
* Fix #100 via #105: tell browserify to ignore vertx require
* Fix #101 via #102: "follow thenable state, not own state"
# 2.1.0
* #59: Automatic polyfill. No need to invoke `ES6Promise.polyfill()` anymore.
* ... (see the commit log)
# 2.0.0
* re-sync with RSVP. Many large performance improvements and bugfixes.
# 1.0.0
* first subset of RSVP

View File

@@ -0,0 +1,16 @@
export declare enum OuterExpressionKinds {
Parentheses = 1,
TypeAssertions = 2,
NonNullAssertions = 4,
PartiallyEmittedExpressions = 8,
ExpressionsWithTypeArguments = 16,
Satisfies = 32,
ExcludeJSDocTypeAssertion = 64,
Assignments = 128,
Comma = 256,
Assertions = 38,
All = 63,
AllExceptAssertionsOrExpressionsWithTypeArguments = 9,
ExpressionTypePassthrough = 385
}
//# sourceMappingURL=outerExpressionKinds.enum.d.ts.map

View File

@@ -0,0 +1,75 @@
import { FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';
/**
* Returns an encoder for 8-bit signed integers (`i8`).
*
* This encoder serializes `i8` values using 1 byte.
* Values can be provided as either `number` or `bigint`.
*
* For more details, see {@link getI8Codec}.
*
* @returns A `FixedSizeEncoder<number | bigint, 1>` for encoding `i8` values.
*
* @example
* Encoding an `i8` value.
* ```ts
* const encoder = getI8Encoder();
* const bytes = encoder.encode(-42); // 0xd6
* ```
*
* @see {@link getI8Codec}
*/
export declare const getI8Encoder: () => FixedSizeEncoder<bigint | number, 1>;
/**
* Returns a decoder for 8-bit signed integers (`i8`).
*
* This decoder deserializes `i8` values from 1 byte.
* The decoded value is always a `number`.
*
* For more details, see {@link getI8Codec}.
*
* @returns A `FixedSizeDecoder<number, 1>` for decoding `i8` values.
*
* @example
* Decoding an `i8` value.
* ```ts
* const decoder = getI8Decoder();
* const value = decoder.decode(new Uint8Array([0xd6])); // -42
* ```
*
* @see {@link getI8Codec}
*/
export declare const getI8Decoder: () => FixedSizeDecoder<number, 1>;
/**
* Returns a codec for encoding and decoding 8-bit signed integers (`i8`).
*
* This codec serializes `i8` values using 1 byte.
* Values can be provided as either `number` or `bigint`, but the decoded value is always a `number`.
*
* @returns A `FixedSizeCodec<number | bigint, number, 1>` for encoding and decoding `i8` values.
*
* @example
* Encoding and decoding an `i8` value.
* ```ts
* const codec = getI8Codec();
* const bytes = codec.encode(-42); // 0xd6
* const value = codec.decode(bytes); // -42
* ```
*
* @remarks
* This codec supports values between `-2^7` (`-128`) and `2^7 - 1` (`127`).
*
* - If you need a larger signed integer, consider using {@link getI16Codec}.
* - If you need an unsigned integer, consider using {@link getU8Codec}.
*
* Separate {@link getI8Encoder} and {@link getI8Decoder} functions are available.
*
* ```ts
* const bytes = getI8Encoder().encode(-42);
* const value = getI8Decoder().decode(bytes);
* ```
*
* @see {@link getI8Encoder}
* @see {@link getI8Decoder}
*/
export declare const getI8Codec: () => FixedSizeCodec<bigint | number, number, 1>;
//# sourceMappingURL=i8.d.ts.map

View File

@@ -0,0 +1,10 @@
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}

View File

@@ -0,0 +1,474 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2018.intl" />
declare namespace Intl {
/**
* A string that is a valid [Unicode BCP 47 Locale Identifier](https://unicode.org/reports/tr35/#Unicode_locale_identifier).
*
* For example: "fa", "es-MX", "zh-Hant-TW".
*
* See [MDN - Intl - locales argument](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
*/
type UnicodeBCP47LocaleIdentifier = string;
/**
* Unit to use in the relative time internationalized message.
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format#Parameters).
*/
type RelativeTimeFormatUnit =
| "year"
| "years"
| "quarter"
| "quarters"
| "month"
| "months"
| "week"
| "weeks"
| "day"
| "days"
| "hour"
| "hours"
| "minute"
| "minutes"
| "second"
| "seconds";
/**
* Value of the `unit` property in objects returned by
* `Intl.RelativeTimeFormat.prototype.formatToParts()`. `formatToParts` and
* `format` methods accept either singular or plural unit names as input,
* but `formatToParts` only outputs singular (e.g. "day") not plural (e.g.
* "days").
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts).
*/
type RelativeTimeFormatUnitSingular =
| "year"
| "quarter"
| "month"
| "week"
| "day"
| "hour"
| "minute"
| "second";
/**
* The locale matching algorithm to use.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation).
*/
type RelativeTimeFormatLocaleMatcher = "lookup" | "best fit";
/**
* The format of output message.
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters).
*/
type RelativeTimeFormatNumeric = "always" | "auto";
/**
* The length of the internationalized message.
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters).
*/
type RelativeTimeFormatStyle = "long" | "short" | "narrow";
/**
* The locale or locales to use
*
* See [MDN - Intl - locales argument](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
*/
type LocalesArgument = UnicodeBCP47LocaleIdentifier | Locale | readonly (UnicodeBCP47LocaleIdentifier | Locale)[] | undefined;
/**
* An object with some or all of properties of `options` parameter
* of `Intl.RelativeTimeFormat` constructor.
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters).
*/
interface RelativeTimeFormatOptions {
/** The locale matching algorithm to use. For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). */
localeMatcher?: RelativeTimeFormatLocaleMatcher;
/** The format of output message. */
numeric?: RelativeTimeFormatNumeric;
/** The length of the internationalized message. */
style?: RelativeTimeFormatStyle;
}
/**
* An object with properties reflecting the locale
* and formatting options computed during initialization
* of the `Intl.RelativeTimeFormat` object
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions#Description).
*/
interface ResolvedRelativeTimeFormatOptions {
locale: UnicodeBCP47LocaleIdentifier;
style: RelativeTimeFormatStyle;
numeric: RelativeTimeFormatNumeric;
numberingSystem: string;
}
/**
* An object representing the relative time format in parts
* that can be used for custom locale-aware formatting.
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts).
*/
type RelativeTimeFormatPart =
| {
type: "literal";
value: string;
}
| {
type: Exclude<NumberFormatPartTypes, "literal">;
value: string;
unit: RelativeTimeFormatUnitSingular;
};
interface RelativeTimeFormat {
/**
* Formats a value and a unit according to the locale
* and formatting options of the given
* [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat)
* object.
*
* While this method automatically provides the correct plural forms,
* the grammatical form is otherwise as neutral as possible.
*
* It is the caller's responsibility to handle cut-off logic
* such as deciding between displaying "in 7 days" or "in 1 week".
* This API does not support relative dates involving compound units.
* e.g "in 5 days and 4 hours".
*
* @param value - Numeric value to use in the internationalized relative time message
*
* @param unit - [Unit](https://tc39.es/ecma402/#sec-singularrelativetimeunit) to use in the relative time internationalized message.
*
* @throws `RangeError` if `unit` was given something other than `unit` possible values
*
* @returns {string} Internationalized relative time message as string
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format).
*/
format(value: number, unit: RelativeTimeFormatUnit): string;
/**
* Returns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting.
*
* @param value - Numeric value to use in the internationalized relative time message
*
* @param unit - [Unit](https://tc39.es/ecma402/#sec-singularrelativetimeunit) to use in the relative time internationalized message.
*
* @throws `RangeError` if `unit` was given something other than `unit` possible values
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts).
*/
formatToParts(value: number, unit: RelativeTimeFormatUnit): RelativeTimeFormatPart[];
/**
* Provides access to the locale and options computed during initialization of this `Intl.RelativeTimeFormat` object.
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions).
*/
resolvedOptions(): ResolvedRelativeTimeFormatOptions;
}
/**
* The [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat)
* object is a constructor for objects that enable language-sensitive relative time formatting.
*
* [Compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat#Browser_compatibility).
*/
const RelativeTimeFormat: {
/**
* Creates [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) objects
*
* @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
* For the general form and interpretation of the locales argument,
* see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
*
* @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters)
* with some or all of options of `RelativeTimeFormatOptions`.
*
* @returns [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) object.
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat).
*/
new (
locales?: LocalesArgument,
options?: RelativeTimeFormatOptions,
): RelativeTimeFormat;
/**
* Returns an array containing those of the provided locales
* that are supported in date and time formatting
* without having to fall back to the runtime's default locale.
*
* @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
* For the general form and interpretation of the locales argument,
* see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
*
* @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters)
* with some or all of options of the formatting.
*
* @returns An array containing those of the provided locales
* that are supported in date and time formatting
* without having to fall back to the runtime's default locale.
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/supportedLocalesOf).
*/
supportedLocalesOf(
locales?: LocalesArgument,
options?: RelativeTimeFormatOptions,
): UnicodeBCP47LocaleIdentifier[];
};
interface NumberFormatOptionsStyleRegistry {
unit: never;
}
interface NumberFormatOptionsCurrencyDisplayRegistry {
narrowSymbol: never;
}
interface NumberFormatOptionsSignDisplayRegistry {
auto: never;
never: never;
always: never;
exceptZero: never;
}
type NumberFormatOptionsSignDisplay = keyof NumberFormatOptionsSignDisplayRegistry;
interface NumberFormatOptions {
numberingSystem?: string | undefined;
compactDisplay?: "short" | "long" | undefined;
notation?: "standard" | "scientific" | "engineering" | "compact" | undefined;
signDisplay?: NumberFormatOptionsSignDisplay | undefined;
unit?: string | undefined;
unitDisplay?: "short" | "long" | "narrow" | undefined;
currencySign?: "standard" | "accounting" | undefined;
}
interface ResolvedNumberFormatOptions {
compactDisplay?: "short" | "long";
notation: "standard" | "scientific" | "engineering" | "compact";
signDisplay: NumberFormatOptionsSignDisplay;
unit?: string;
unitDisplay?: "short" | "long" | "narrow";
currencySign?: "standard" | "accounting";
}
interface NumberFormatPartTypeRegistry {
compact: never;
exponentInteger: never;
exponentMinusSign: never;
exponentSeparator: never;
unit: never;
unknown: never;
}
interface DateTimeFormatOptions {
calendar?: string | undefined;
dayPeriod?: "narrow" | "short" | "long" | undefined;
numberingSystem?: string | undefined;
dateStyle?: "full" | "long" | "medium" | "short" | undefined;
timeStyle?: "full" | "long" | "medium" | "short" | undefined;
hourCycle?: "h11" | "h12" | "h23" | "h24" | undefined;
}
type LocaleHourCycleKey = "h12" | "h23" | "h11" | "h24";
type LocaleCollationCaseFirst = "upper" | "lower" | "false";
interface LocaleOptions {
/** A string containing the language, and the script and region if available. */
baseName?: string;
/** The part of the Locale that indicates the locale's calendar era. */
calendar?: string;
/** Flag that defines whether case is taken into account for the locale's collation rules. */
caseFirst?: LocaleCollationCaseFirst;
/** The collation type used for sorting */
collation?: string;
/** The time keeping format convention used by the locale. */
hourCycle?: LocaleHourCycleKey;
/** The primary language subtag associated with the locale. */
language?: string;
/** The numeral system used by the locale. */
numberingSystem?: string;
/** Flag that defines whether the locale has special collation handling for numeric characters. */
numeric?: boolean;
/** The region of the world (usually a country) associated with the locale. Possible values are region codes as defined by ISO 3166-1. */
region?: string;
/** The script used for writing the particular language used in the locale. Possible values are script codes as defined by ISO 15924. */
script?: string;
}
interface Locale extends LocaleOptions {
/** A string containing the language, and the script and region if available. */
baseName: string;
/** The primary language subtag associated with the locale. */
language: string;
/** Gets the most likely values for the language, script, and region of the locale based on existing values. */
maximize(): Locale;
/** Attempts to remove information about the locale that would be added by calling `Locale.maximize()`. */
minimize(): Locale;
/** Returns the locale's full locale identifier string. */
toString(): UnicodeBCP47LocaleIdentifier;
}
/**
* Constructor creates [Intl.Locale](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale)
* objects
*
* @param tag - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646).
* For the general form and interpretation of the locales argument,
* see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
*
* @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/Locale#Parameters) with some or all of options of the locale.
*
* @returns [Intl.Locale](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale) object.
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale).
*/
const Locale: {
new (tag: UnicodeBCP47LocaleIdentifier | Locale, options?: LocaleOptions): Locale;
};
type DisplayNamesFallback =
| "code"
| "none";
type DisplayNamesType =
| "language"
| "region"
| "script"
| "calendar"
| "dateTimeField"
| "currency";
type DisplayNamesLanguageDisplay =
| "dialect"
| "standard";
interface DisplayNamesOptions {
localeMatcher?: RelativeTimeFormatLocaleMatcher;
style?: RelativeTimeFormatStyle;
type: DisplayNamesType;
languageDisplay?: DisplayNamesLanguageDisplay;
fallback?: DisplayNamesFallback;
}
interface ResolvedDisplayNamesOptions {
locale: UnicodeBCP47LocaleIdentifier;
style: RelativeTimeFormatStyle;
type: DisplayNamesType;
fallback: DisplayNamesFallback;
languageDisplay?: DisplayNamesLanguageDisplay;
}
interface DisplayNames {
/**
* Receives a code and returns a string based on the locale and options provided when instantiating
* [`Intl.DisplayNames()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames)
*
* @param code The `code` to provide depends on the `type` passed to display name during creation:
* - If the type is `"region"`, code should be either an [ISO-3166 two letters region code](https://www.iso.org/iso-3166-country-codes.html),
* or a [three digits UN M49 Geographic Regions](https://unstats.un.org/unsd/methodology/m49/).
* - If the type is `"script"`, code should be an [ISO-15924 four letters script code](https://unicode.org/iso15924/iso15924-codes.html).
* - If the type is `"language"`, code should be a `languageCode` ["-" `scriptCode`] ["-" `regionCode` ] *("-" `variant` )
* subsequence of the unicode_language_id grammar in [UTS 35's Unicode Language and Locale Identifiers grammar](https://unicode.org/reports/tr35/#Unicode_language_identifier).
* `languageCode` is either a two letters ISO 639-1 language code or a three letters ISO 639-2 language code.
* - If the type is `"currency"`, code should be a [3-letter ISO 4217 currency code](https://www.iso.org/iso-4217-currency-codes.html).
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/of).
*/
of(code: string): string | undefined;
/**
* Returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current
* [`Intl/DisplayNames`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) object.
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/resolvedOptions).
*/
resolvedOptions(): ResolvedDisplayNamesOptions;
}
/**
* The [`Intl.DisplayNames()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames)
* object enables the consistent translation of language, region and script display names.
*
* [Compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames#browser_compatibility).
*/
const DisplayNames: {
prototype: DisplayNames;
/**
* @param locales A string with a BCP 47 language tag, or an array of such strings.
* For the general form and interpretation of the `locales` argument, see the [Intl](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation)
* page.
*
* @param options An object for setting up a display name.
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/DisplayNames).
*/
new (locales: LocalesArgument, options: DisplayNamesOptions): DisplayNames;
/**
* Returns an array containing those of the provided locales that are supported in display names without having to fall back to the runtime's default locale.
*
* @param locales A string with a BCP 47 language tag, or an array of such strings.
* For the general form and interpretation of the `locales` argument, see the [Intl](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation)
* page.
*
* @param options An object with a locale matcher.
*
* @returns An array of strings representing a subset of the given locale tags that are supported in display names without having to fall back to the runtime's default locale.
*
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/supportedLocalesOf).
*/
supportedLocalesOf(locales?: LocalesArgument, options?: { localeMatcher?: RelativeTimeFormatLocaleMatcher; }): UnicodeBCP47LocaleIdentifier[];
};
interface CollatorConstructor {
new (locales?: LocalesArgument, options?: CollatorOptions): Collator;
(locales?: LocalesArgument, options?: CollatorOptions): Collator;
supportedLocalesOf(locales: LocalesArgument, options?: CollatorOptions): string[];
}
interface DateTimeFormatConstructor {
new (locales?: LocalesArgument, options?: DateTimeFormatOptions): DateTimeFormat;
(locales?: LocalesArgument, options?: DateTimeFormatOptions): DateTimeFormat;
supportedLocalesOf(locales: LocalesArgument, options?: DateTimeFormatOptions): string[];
}
interface NumberFormatConstructor {
new (locales?: LocalesArgument, options?: NumberFormatOptions): NumberFormat;
(locales?: LocalesArgument, options?: NumberFormatOptions): NumberFormat;
supportedLocalesOf(locales: LocalesArgument, options?: NumberFormatOptions): string[];
}
interface PluralRulesConstructor {
new (locales?: LocalesArgument, options?: PluralRulesOptions): PluralRules;
(locales?: LocalesArgument, options?: PluralRulesOptions): PluralRules;
supportedLocalesOf(locales: LocalesArgument, options?: { localeMatcher?: "lookup" | "best fit"; }): string[];
}
}

View File

@@ -0,0 +1,52 @@
'use strict';
const path = require('path');
const which = require('which');
const getPathKey = require('path-key');
function resolveCommandAttempt(parsed, withoutPathExt) {
const env = parsed.options.env || process.env;
const cwd = process.cwd();
const hasCustomCwd = parsed.options.cwd != null;
// Worker threads do not have process.chdir()
const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
// If a custom `cwd` was specified, we need to change the process cwd
// because `which` will do stat calls but does not support a custom cwd
if (shouldSwitchCwd) {
try {
process.chdir(parsed.options.cwd);
} catch (err) {
/* Empty */
}
}
let resolved;
try {
resolved = which.sync(parsed.command, {
path: env[getPathKey({ env })],
pathExt: withoutPathExt ? path.delimiter : undefined,
});
} catch (e) {
/* Empty */
} finally {
if (shouldSwitchCwd) {
process.chdir(cwd);
}
}
// If we successfully resolved, ensure that an absolute path is returned
// Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
if (resolved) {
resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
}
return resolved;
}
function resolveCommand(parsed) {
return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
}
module.exports = resolveCommand;

View File

@@ -0,0 +1,37 @@
{
"name": "atomic-sleep",
"version": "1.0.0",
"description": "Zero CPU overhead, zero dependency, true event-loop blocking sleep",
"main": "index.js",
"scripts": {
"test": "tap -R classic- -j1 test",
"lint": "standard",
"ci": "npm run lint && npm test"
},
"keywords": [
"sleep",
"pause",
"wait",
"performance",
"atomics"
],
"engines": {
"node": ">=8.0.0"
},
"author": "David Mark Clements (@davidmarkclem)",
"license": "MIT",
"devDependencies": {
"standard": "^14.3.1",
"tap": "^14.10.6",
"tape": "^4.13.2"
},
"dependencies": {},
"repository": {
"type": "git",
"url": "git+https://github.com/davidmarkclements/atomic-sleep.git"
},
"bugs": {
"url": "https://github.com/davidmarkclements/atomic-sleep/issues"
},
"homepage": "https://github.com/davidmarkclements/atomic-sleep#readme"
}

View File

@@ -0,0 +1,214 @@
'use strict'
const test = require('node:test')
const http = require('node:http')
const os = require('node:os')
const tspl = require('@matteo.collina/tspl')
const { sink, once } = require('./helper')
const pino = require('../')
const { pid } = process
const hostname = os.hostname()
test('http request support', async (t) => {
const plan = tspl(t, { plan: 3 })
let originalReq
const instance = pino(sink((chunk, enc) => {
plan.ok(new Date(chunk.time) <= new Date(), 'time is greater than Date.now()')
delete chunk.time
plan.deepEqual(chunk, {
pid,
hostname,
level: 30,
msg: 'my request',
req: {
method: originalReq.method,
url: originalReq.url,
headers: originalReq.headers,
remoteAddress: originalReq.socket.remoteAddress,
remotePort: originalReq.socket.remotePort
}
})
}))
const server = http.createServer((req, res) => {
originalReq = req
instance.info(req, 'my request')
res.end('hello')
})
server.unref()
server.listen()
const err = await once(server, 'listening')
plan.equal(err, undefined)
const res = await once(http.get('http://localhost:' + server.address().port), 'response')
res.resume()
server.close()
await plan
})
test('http request support via serializer', async (t) => {
const plan = tspl(t, { plan: 3 })
let originalReq
const instance = pino({
serializers: {
req: pino.stdSerializers.req
}
}, sink((chunk, enc) => {
plan.ok(new Date(chunk.time) <= new Date(), 'time is greater than Date.now()')
delete chunk.time
plan.deepEqual(chunk, {
pid,
hostname,
level: 30,
msg: 'my request',
req: {
method: originalReq.method,
url: originalReq.url,
headers: originalReq.headers,
remoteAddress: originalReq.socket.remoteAddress,
remotePort: originalReq.socket.remotePort
}
})
}))
const server = http.createServer(function (req, res) {
originalReq = req
instance.info({ req }, 'my request')
res.end('hello')
})
server.unref()
server.listen()
const err = await once(server, 'listening')
plan.equal(err, undefined)
const res = await once(http.get('http://localhost:' + server.address().port), 'response')
res.resume()
server.close()
await plan
})
test('http response support', async (t) => {
const plan = tspl(t, { plan: 3 })
let originalRes
const instance = pino(sink((chunk, enc) => {
plan.ok(new Date(chunk.time) <= new Date(), 'time is greater than Date.now()')
delete chunk.time
plan.deepEqual(chunk, {
pid,
hostname,
level: 30,
msg: 'my response',
res: {
statusCode: originalRes.statusCode,
headers: originalRes.getHeaders()
}
})
}))
const server = http.createServer(function (req, res) {
originalRes = res
res.end('hello')
instance.info(res, 'my response')
})
server.unref()
server.listen()
const err = await once(server, 'listening')
plan.equal(err, undefined)
const res = await once(http.get('http://localhost:' + server.address().port), 'response')
res.resume()
server.close()
await plan
})
test('http response support via a serializer', async (t) => {
const plan = tspl(t, { plan: 3 })
const instance = pino({
serializers: {
res: pino.stdSerializers.res
}
}, sink((chunk, enc) => {
plan.ok(new Date(chunk.time) <= new Date(), 'time is greater than Date.now()')
delete chunk.time
plan.deepEqual(chunk, {
pid,
hostname,
level: 30,
msg: 'my response',
res: {
statusCode: 200,
headers: {
'x-single': 'y',
'x-multi': [1, 2]
}
}
})
}))
const server = http.createServer(function (req, res) {
res.setHeader('x-single', 'y')
res.setHeader('x-multi', [1, 2])
res.end('hello')
instance.info({ res }, 'my response')
})
server.unref()
server.listen()
const err = await once(server, 'listening')
plan.equal(err, undefined)
const res = await once(http.get('http://localhost:' + server.address().port), 'response')
res.resume()
server.close()
await plan
})
test('http request support via serializer in a child', async (t) => {
const plan = tspl(t, { plan: 3 })
let originalReq
const instance = pino({
serializers: {
req: pino.stdSerializers.req
}
}, sink((chunk, enc) => {
plan.ok(new Date(chunk.time) <= new Date(), 'time is greater than Date.now()')
delete chunk.time
plan.deepEqual(chunk, {
pid,
hostname,
level: 30,
msg: 'my request',
req: {
method: originalReq.method,
url: originalReq.url,
headers: originalReq.headers,
remoteAddress: originalReq.socket.remoteAddress,
remotePort: originalReq.socket.remotePort
}
})
}))
const server = http.createServer(function (req, res) {
originalReq = req
const child = instance.child({ req })
child.info('my request')
res.end('hello')
})
server.unref()
server.listen()
const err = await once(server, 'listening')
plan.equal(err, undefined)
const res = await once(http.get('http://localhost:' + server.address().port), 'response')
res.resume()
server.close()
await plan
})

View File

@@ -0,0 +1,174 @@
### esutils [![Build Status](https://secure.travis-ci.org/estools/esutils.svg)](http://travis-ci.org/estools/esutils)
esutils ([esutils](http://github.com/estools/esutils)) is
utility box for ECMAScript language tools.
### API
### ast
#### ast.isExpression(node)
Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section
[11](https://es5.github.io/#x11).
#### ast.isStatement(node)
Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section
[12](https://es5.github.io/#x12).
#### ast.isIterationStatement(node)
Returns true if `node` is an IterationStatement as defined in ECMA262 edition
5.1 section [12.6](https://es5.github.io/#x12.6).
#### ast.isSourceElement(node)
Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1
section [14](https://es5.github.io/#x14).
#### ast.trailingStatement(node)
Returns `Statement?` if `node` has trailing `Statement`.
```js
if (cond)
consequent;
```
When taking this `IfStatement`, returns `consequent;` statement.
#### ast.isProblematicIfStatement(node)
Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code.
```js
{
type: 'IfStatement',
consequent: {
type: 'WithStatement',
body: {
type: 'IfStatement',
consequent: {type: 'EmptyStatement'}
}
},
alternate: {type: 'EmptyStatement'}
}
```
The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`.
### code
#### code.isDecimalDigit(code)
Return true if provided code is decimal digit.
#### code.isHexDigit(code)
Return true if provided code is hexadecimal digit.
#### code.isOctalDigit(code)
Return true if provided code is octal digit.
#### code.isWhiteSpace(code)
Return true if provided code is white space. White space characters are formally defined in ECMA262.
#### code.isLineTerminator(code)
Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262.
#### code.isIdentifierStart(code)
Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262.
#### code.isIdentifierPart(code)
Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262.
### keyword
#### keyword.isKeywordES5(id, strict)
Returns `true` if provided identifier string is a Keyword or Future Reserved Word
in ECMA262 edition 5.1. They are formally defined in ECMA262 sections
[7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2),
respectively. If the `strict` flag is truthy, this function additionally checks whether
`id` is a Keyword or Future Reserved Word under strict mode.
#### keyword.isKeywordES6(id, strict)
Returns `true` if provided identifier string is a Keyword or Future Reserved Word
in ECMA262 edition 6. They are formally defined in ECMA262 sections
[11.6.2.1](http://ecma-international.org/ecma-262/6.0/#sec-keywords) and
[11.6.2.2](http://ecma-international.org/ecma-262/6.0/#sec-future-reserved-words),
respectively. If the `strict` flag is truthy, this function additionally checks whether
`id` is a Keyword or Future Reserved Word under strict mode.
#### keyword.isReservedWordES5(id, strict)
Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1.
They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1).
If the `strict` flag is truthy, this function additionally checks whether `id`
is a Reserved Word under strict mode.
#### keyword.isReservedWordES6(id, strict)
Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6.
They are formally defined in ECMA262 section [11.6.2](http://ecma-international.org/ecma-262/6.0/#sec-reserved-words).
If the `strict` flag is truthy, this function additionally checks whether `id`
is a Reserved Word under strict mode.
#### keyword.isRestrictedWord(id)
Returns `true` if provided identifier string is one of `eval` or `arguments`.
They are restricted in strict mode code throughout ECMA262 edition 5.1 and
in ECMA262 edition 6 section [12.1.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors).
#### keyword.isIdentifierNameES5(id)
Return true if provided identifier string is an IdentifierName as specified in
ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6).
#### keyword.isIdentifierNameES6(id)
Return true if provided identifier string is an IdentifierName as specified in
ECMA262 edition 6 section [11.6](http://ecma-international.org/ecma-262/6.0/#sec-names-and-keywords).
#### keyword.isIdentifierES5(id, strict)
Return true if provided identifier string is an Identifier as specified in
ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict`
flag is truthy, this function additionally checks whether `id` is an Identifier
under strict mode.
#### keyword.isIdentifierES6(id, strict)
Return true if provided identifier string is an Identifier as specified in
ECMA262 edition 6 section [12.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers).
If the `strict` flag is truthy, this function additionally checks whether `id`
is an Identifier under strict mode.
### License
Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation)
(twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,116 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string; verb: string }> = {
string: { unit: "caratteri", verb: "avere" },
file: { unit: "byte", verb: "avere" },
array: { unit: "elementi", verb: "avere" },
set: { unit: "elementi", verb: "avere" },
};
function getSizing(origin: string): { unit: string; verb: string } | null {
return Sizable[origin] ?? null;
}
const FormatDictionary: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "input",
email: "indirizzo email",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "data e ora ISO",
date: "data ISO",
time: "ora ISO",
duration: "durata ISO",
ipv4: "indirizzo IPv4",
ipv6: "indirizzo IPv6",
cidrv4: "intervallo IPv4",
cidrv6: "intervallo IPv6",
base64: "stringa codificata in base64",
base64url: "URL codificata in base64",
json_string: "stringa JSON",
e164: "numero E.164",
jwt: "JWT",
template_literal: "input",
};
const TypeDictionary: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
} = {
nan: "NaN",
number: "numero",
array: "vettore",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `Input non valido: atteso instanceof ${issue.expected}, ricevuto ${received}`;
}
return `Input non valido: atteso ${expected}, ricevuto ${received}`;
}
case "invalid_value":
if (issue.values.length === 1) return `Input non valido: atteso ${util.stringifyPrimitive(issue.values[0])}`;
return `Opzione non valida: atteso uno tra ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Troppo grande: ${issue.origin ?? "valore"} deve avere ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementi"}`;
return `Troppo grande: ${issue.origin ?? "valore"} deve essere ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Troppo piccolo: ${issue.origin} deve avere ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Troppo piccolo: ${issue.origin} deve essere ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with") return `Stringa non valida: deve iniziare con "${_issue.prefix}"`;
if (_issue.format === "ends_with") return `Stringa non valida: deve terminare con "${_issue.suffix}"`;
if (_issue.format === "includes") return `Stringa non valida: deve includere "${_issue.includes}"`;
if (_issue.format === "regex") return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
return `Input non valido: ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Numero non valido: deve essere un multiplo di ${issue.divisor}`;
case "unrecognized_keys":
return `Chiav${issue.keys.length > 1 ? "i" : "e"} non riconosciut${issue.keys.length > 1 ? "e" : "a"}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Chiave non valida in ${issue.origin}`;
case "invalid_union":
return "Input non valido";
case "invalid_element":
return `Valore non valido in ${issue.origin}`;
default:
return `Input non valido`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,614 @@
import type { JSONSchema4 } from '../json-schema';
import type { ParserServices, TSESTree } from '../ts-estree';
import type { AST } from './AST';
import type { FlatConfig } from './Config';
import type { Linter } from './Linter';
import type { Scope } from './Scope';
import type { SourceCode } from './SourceCode';
export type RuleRecommendation = 'recommended' | 'strict' | 'stylistic';
export interface RuleRecommendationAcrossConfigs<Options extends readonly unknown[]> {
recommended?: true;
strict: Partial<Options>;
}
export interface RuleMetaDataDocs {
/**
* Concise description of the rule.
*/
description: string;
/**
* The URL of the rule's docs.
*/
url?: string;
/**
* Mark this rule as feature-frozen.
*/
frozen?: boolean;
}
export interface ExternalSpecifier {
/**
* Name of the referenced plugin / rule.
*/
name?: string;
/**
* URL pointing to documentation for the plugin / rule.
*/
url?: string;
}
export interface ReplacedByInfo {
/**
* General message presented to the user, e.g. how to replace the rule
*/
message?: string;
/**
* URL to more information about this replacement in general
*/
url?: string;
/**
* Name should be "eslint" if the replacement is an ESLint core rule. Omit
* the property if the replacement is in the same plugin.
*/
plugin?: ExternalSpecifier;
/**
* Name and documentation of the replacement rule
*/
rule?: ExternalSpecifier;
}
export interface DeprecatedInfo {
/**
* General message presented to the user, e.g. for the key rule why the rule
* is deprecated or for info how to replace the rule.
*/
message?: string;
/**
* URL to more information about this deprecation in general.
*/
url?: string;
/**
* An empty array explicitly states that there is no replacement.
*/
replacedBy?: ReplacedByInfo[];
/**
* The package version since when the rule is deprecated (should use full
* semver without a leading "v").
*/
deprecatedSince?: string;
/**
* The estimated version when the rule is removed (probably the next major
* version). null means the rule is "frozen" (will be available but will not
* be changed).
*/
availableUntil?: string | null;
}
export interface RuleMetaData<MessageIds extends string, PluginDocs = unknown, Options extends readonly unknown[] = []> {
/**
* True if the rule is deprecated, false otherwise
*/
deprecated?: boolean | DeprecatedInfo;
/**
* Documentation for the rule
*/
docs?: PluginDocs & RuleMetaDataDocs;
/**
* The fixer category. Omit if there is no fixer
*/
fixable?: 'code' | 'whitespace';
/**
* Specifies whether rules can return suggestions. Omit if there is no suggestions
*/
hasSuggestions?: boolean;
/**
* A map of messages which the rule can report.
* The key is the messageId, and the string is the parameterized error string.
* See: https://eslint.org/docs/developer-guide/working-with-rules#messageids
*/
messages: Record<MessageIds, string>;
/**
* The name of the rule this rule was replaced by, if it was deprecated.
*
* @deprecated since eslint 9.21.0, in favor of `RuleMetaData#deprecated.replacedBy`
*/
replacedBy?: readonly string[];
/**
* The options schema. Supply an empty array if there are no options.
*/
schema: JSONSchema4 | readonly JSONSchema4[];
/**
* The type of rule.
* - `"problem"` means the rule is identifying code that either will cause an error or may cause a confusing behavior. Developers should consider this a high priority to resolve.
* - `"suggestion"` means the rule is identifying something that could be done in a better way but no errors will occur if the code isnt changed.
* - `"layout"` means the rule cares primarily about whitespace, semicolons, commas, and parentheses, all the parts of the program that determine how the code looks rather than how it executes. These rules work on parts of the code that arent specified in the AST.
*/
type: 'layout' | 'problem' | 'suggestion';
/**
* Specifies default options for the rule. If present, any user-provided options in their config will be merged on top of them recursively.
* This merging will be applied directly to `context.options`.
* If you want backwards-compatible support for earlier ESLint version, consider using the top-level `defaultOptions` instead.
*
* since ESLint 9.15.0
*/
defaultOptions?: Options;
}
export interface RuleMetaDataWithDocs<MessageIds extends string, PluginDocs = unknown, Options extends readonly unknown[] = []> extends RuleMetaData<MessageIds, PluginDocs, Options> {
/**
* Documentation for the rule
*/
docs: PluginDocs & RuleMetaDataDocs;
}
export interface RuleFix {
range: Readonly<AST.Range>;
text: string;
}
export interface RuleFixer {
insertTextAfter(nodeOrToken: TSESTree.Node | TSESTree.Token, text: string): RuleFix;
insertTextAfterRange(range: Readonly<AST.Range>, text: string): RuleFix;
insertTextBefore(nodeOrToken: TSESTree.Node | TSESTree.Token, text: string): RuleFix;
insertTextBeforeRange(range: Readonly<AST.Range>, text: string): RuleFix;
remove(nodeOrToken: TSESTree.Node | TSESTree.Token): RuleFix;
removeRange(range: Readonly<AST.Range>): RuleFix;
replaceText(nodeOrToken: TSESTree.Node | TSESTree.Token, text: string): RuleFix;
replaceTextRange(range: Readonly<AST.Range>, text: string): RuleFix;
}
export interface SuggestionReportDescriptor<MessageIds extends string> extends Omit<ReportDescriptorBase<MessageIds>, 'fix'> {
readonly fix: ReportFixFunction;
}
export type ReportFixFunction = (fixer: RuleFixer) => IterableIterator<RuleFix> | readonly RuleFix[] | RuleFix | null;
export type ReportSuggestionArray<MessageIds extends string> = SuggestionReportDescriptor<MessageIds>[];
export type ReportDescriptorMessageData = Readonly<Record<string, unknown>>;
interface ReportDescriptorBase<MessageIds extends string> {
/**
* The parameters for the message string associated with `messageId`.
*/
readonly data?: ReportDescriptorMessageData;
/**
* The fixer function.
*/
readonly fix?: ReportFixFunction | null;
/**
* The messageId which is being reported.
*/
readonly messageId: MessageIds;
}
interface ReportDescriptorWithSuggestion<MessageIds extends string> extends ReportDescriptorBase<MessageIds> {
/**
* 6.7's Suggestions API
*/
readonly suggest?: Readonly<ReportSuggestionArray<MessageIds>> | null;
}
interface ReportDescriptorNodeOptionalLoc {
/**
* An override of the location of the report
*/
readonly loc?: Readonly<TSESTree.Position> | Readonly<TSESTree.SourceLocation>;
/**
* The Node or AST Token which the report is being attached to
*/
readonly node: TSESTree.Node | TSESTree.Token;
}
interface ReportDescriptorLocOnly {
/**
* An override of the location of the report
*/
loc: Readonly<TSESTree.Position> | Readonly<TSESTree.SourceLocation>;
}
export type ReportDescriptor<MessageIds extends string> = (ReportDescriptorLocOnly | ReportDescriptorNodeOptionalLoc) & ReportDescriptorWithSuggestion<MessageIds>;
/**
* Plugins can add their settings using declaration
* merging against this interface.
*/
export interface SharedConfigurationSettings {
[name: string]: unknown;
}
export interface RuleContext<MessageIds extends string, Options extends readonly unknown[]> {
/**
* The rule ID.
*/
id: string;
/**
* The language options configured for this run
*/
languageOptions: FlatConfig.LanguageOptions & {
parserOptions: FlatConfig.ParserOptions;
};
/**
* An array of the configured options for this rule.
* This array does not include the rule severity.
*/
options: Options;
/**
* The parser options configured for this run
* @deprecated This was deprecated in ESLint 9 and removed in ESLint 10.
*/
parserOptions: Linter.ParserOptions;
/**
* The name of the parser from configuration, if in eslintrc (legacy) config.
* @deprecated This was deprecated in ESLint 9 and removed in ESLint 10.
*/
parserPath: string | undefined;
/**
* An object containing parser-provided services for rules
*
* @deprecated in favor of `SourceCode#parserServices`
*/
parserServices?: ParserServices;
/**
* The shared settings from configuration.
* We do not have any shared settings in this plugin.
*/
settings: SharedConfigurationSettings;
/**
* Returns an array of the ancestors of the currently-traversed node, starting at
* the root of the AST and continuing through the direct parent of the current node.
* This array does not include the currently-traversed node itself.
*
* @deprecated in favor of `SourceCode#getAncestors`
*/
getAncestors(): TSESTree.Node[];
/**
* Returns a list of variables declared by the given node.
* This information can be used to track references to variables.
*
* @deprecated in favor of `SourceCode#getDeclaredVariables`
*/
getDeclaredVariables(node: TSESTree.Node): readonly Scope.Variable[];
/**
* Returns the current working directory passed to Linter.
* It is a path to a directory that should be considered as the current working directory.
* @deprecated in favor of `RuleContext#cwd`
*/
getCwd(): string;
/**
* The current working directory passed to Linter.
* It is a path to a directory that should be considered as the current working directory.
*/
cwd: string;
/**
* Returns the filename associated with the source.
*
* @deprecated in favor of `RuleContext#filename`
*/
getFilename(): string;
/**
* The filename associated with the source.
*/
filename: string;
/**
* Returns the full path of the file on disk without any code block information (unlike `getFilename()`).
* @deprecated in favor of `RuleContext#physicalFilename`
*/
getPhysicalFilename(): string;
/**
* The full path of the file on disk without any code block information (unlike `filename`).
*/
physicalFilename: string;
/**
* Returns the scope of the currently-traversed node.
* This information can be used track references to variables.
*
* @deprecated in favor of `SourceCode#getScope`
*/
getScope(): Scope.Scope;
/**
* Returns a SourceCode object that you can use to work with the source that
* was passed to ESLint.
*
* @deprecated in favor of `RuleContext#sourceCode`
*/
getSourceCode(): Readonly<SourceCode>;
/**
* A SourceCode object that you can use to work with the source that
* was passed to ESLint.
*/
sourceCode: Readonly<SourceCode>;
/**
* Marks a variable with the given name in the current scope as used.
* This affects the no-unused-vars rule.
*
* @deprecated in favor of `SourceCode#markVariableAsUsed`
*/
markVariableAsUsed(name: string): boolean;
/**
* Reports a problem in the code.
*/
report(descriptor: ReportDescriptor<MessageIds>): void;
}
/**
* Part of the code path analysis feature of ESLint:
* https://eslint.org/docs/latest/extend/code-path-analysis
*
* These are used in the `onCodePath*` methods. (Note that the `node` parameter
* of these methods is intentionally omitted.)
*
* @see https://github.com/typescript-eslint/typescript-eslint/issues/6993
*/
export interface CodePath {
/** Code paths of functions this code path contains. */
childCodePaths: CodePath[];
/**
* Segments of the current traversal position.
*
* @deprecated
*/
currentSegments: CodePathSegment[];
/** The final segments which includes both returned and thrown. */
finalSegments: CodePathSegment[];
/**
* A unique string. Respective rules can use `id` to save additional
* information for each code path.
*/
id: string;
initialSegment: CodePathSegment;
/** The final segments which includes only returned. */
returnedSegments: CodePathSegment[];
/** The final segments which includes only thrown. */
thrownSegments: CodePathSegment[];
/** The code path of the upper function/global scope. */
upper: CodePath | null;
}
/**
* Part of the code path analysis feature of ESLint:
* https://eslint.org/docs/latest/extend/code-path-analysis
*
* These are used in the `onCodePath*` methods. (Note that the `node` parameter
* of these methods is intentionally omitted.)
*
* @see https://github.com/typescript-eslint/typescript-eslint/issues/6993
*/
export interface CodePathSegment {
/**
* A unique string. Respective rules can use `id` to save additional
* information for each segment.
*/
id: string;
/**
* The next segments. If forking, there are two or more. If final, there is
* nothing.
*/
nextSegments: CodePathSegment[];
/**
* The previous segments. If merging, there are two or more. If initial, there
* is nothing.
*/
prevSegments: CodePathSegment[];
/**
* A flag which shows whether it is reachable. This becomes `false` when
* preceded by `return`, `throw`, `break`, or `continue`.
*/
reachable: boolean;
}
/**
* Part of the code path analysis feature of ESLint:
* https://eslint.org/docs/latest/extend/code-path-analysis
*
* This type is unused in the `typescript-eslint` codebase since putting it on
* the `nodeSelector` for `RuleListener` would break the existing definition.
* However, it is exported here for the purposes of manual type-assertion.
*
* @see https://github.com/typescript-eslint/typescript-eslint/issues/6993
*/
export type CodePathFunction = ((codePath: CodePath, node: TSESTree.Node) => void) | ((fromSegment: CodePathSegment, toSegment: CodePathSegment, node: TSESTree.Node) => void) | ((segment: CodePathSegment, node: TSESTree.Node) => void);
export type RuleFunction<T extends TSESTree.NodeOrTokenData = never> = (node: T) => void;
interface RuleListenerBaseSelectors {
AccessorProperty?: RuleFunction<TSESTree.AccessorProperty>;
ArrayExpression?: RuleFunction<TSESTree.ArrayExpression>;
ArrayPattern?: RuleFunction<TSESTree.ArrayPattern>;
ArrowFunctionExpression?: RuleFunction<TSESTree.ArrowFunctionExpression>;
AssignmentExpression?: RuleFunction<TSESTree.AssignmentExpression>;
AssignmentPattern?: RuleFunction<TSESTree.AssignmentPattern>;
AwaitExpression?: RuleFunction<TSESTree.AwaitExpression>;
BinaryExpression?: RuleFunction<TSESTree.BinaryExpression>;
BlockStatement?: RuleFunction<TSESTree.BlockStatement>;
BreakStatement?: RuleFunction<TSESTree.BreakStatement>;
CallExpression?: RuleFunction<TSESTree.CallExpression>;
CatchClause?: RuleFunction<TSESTree.CatchClause>;
ChainExpression?: RuleFunction<TSESTree.ChainExpression>;
ClassBody?: RuleFunction<TSESTree.ClassBody>;
ClassDeclaration?: RuleFunction<TSESTree.ClassDeclaration>;
ClassExpression?: RuleFunction<TSESTree.ClassExpression>;
ConditionalExpression?: RuleFunction<TSESTree.ConditionalExpression>;
ContinueStatement?: RuleFunction<TSESTree.ContinueStatement>;
DebuggerStatement?: RuleFunction<TSESTree.DebuggerStatement>;
Decorator?: RuleFunction<TSESTree.Decorator>;
DoWhileStatement?: RuleFunction<TSESTree.DoWhileStatement>;
EmptyStatement?: RuleFunction<TSESTree.EmptyStatement>;
ExportAllDeclaration?: RuleFunction<TSESTree.ExportAllDeclaration>;
ExportDefaultDeclaration?: RuleFunction<TSESTree.ExportDefaultDeclaration>;
ExportNamedDeclaration?: RuleFunction<TSESTree.ExportNamedDeclaration>;
ExportSpecifier?: RuleFunction<TSESTree.ExportSpecifier>;
ExpressionStatement?: RuleFunction<TSESTree.ExpressionStatement>;
ForInStatement?: RuleFunction<TSESTree.ForInStatement>;
ForOfStatement?: RuleFunction<TSESTree.ForOfStatement>;
ForStatement?: RuleFunction<TSESTree.ForStatement>;
FunctionDeclaration?: RuleFunction<TSESTree.FunctionDeclaration>;
FunctionExpression?: RuleFunction<TSESTree.FunctionExpression>;
Identifier?: RuleFunction<TSESTree.Identifier>;
IfStatement?: RuleFunction<TSESTree.IfStatement>;
ImportAttribute?: RuleFunction<TSESTree.ImportAttribute>;
ImportDeclaration?: RuleFunction<TSESTree.ImportDeclaration>;
ImportDefaultSpecifier?: RuleFunction<TSESTree.ImportDefaultSpecifier>;
ImportExpression?: RuleFunction<TSESTree.ImportExpression>;
ImportNamespaceSpecifier?: RuleFunction<TSESTree.ImportNamespaceSpecifier>;
ImportSpecifier?: RuleFunction<TSESTree.ImportSpecifier>;
JSXAttribute?: RuleFunction<TSESTree.JSXAttribute>;
JSXClosingElement?: RuleFunction<TSESTree.JSXClosingElement>;
JSXClosingFragment?: RuleFunction<TSESTree.JSXClosingFragment>;
JSXElement?: RuleFunction<TSESTree.JSXElement>;
JSXEmptyExpression?: RuleFunction<TSESTree.JSXEmptyExpression>;
JSXExpressionContainer?: RuleFunction<TSESTree.JSXExpressionContainer>;
JSXFragment?: RuleFunction<TSESTree.JSXFragment>;
JSXIdentifier?: RuleFunction<TSESTree.JSXIdentifier>;
JSXMemberExpression?: RuleFunction<TSESTree.JSXMemberExpression>;
JSXNamespacedName?: RuleFunction<TSESTree.JSXNamespacedName>;
JSXOpeningElement?: RuleFunction<TSESTree.JSXOpeningElement>;
JSXOpeningFragment?: RuleFunction<TSESTree.JSXOpeningFragment>;
JSXSpreadAttribute?: RuleFunction<TSESTree.JSXSpreadAttribute>;
JSXSpreadChild?: RuleFunction<TSESTree.JSXSpreadChild>;
JSXText?: RuleFunction<TSESTree.JSXText>;
LabeledStatement?: RuleFunction<TSESTree.LabeledStatement>;
Literal?: RuleFunction<TSESTree.Literal>;
LogicalExpression?: RuleFunction<TSESTree.LogicalExpression>;
MemberExpression?: RuleFunction<TSESTree.MemberExpression>;
MetaProperty?: RuleFunction<TSESTree.MetaProperty>;
MethodDefinition?: RuleFunction<TSESTree.MethodDefinition>;
NewExpression?: RuleFunction<TSESTree.NewExpression>;
ObjectExpression?: RuleFunction<TSESTree.ObjectExpression>;
ObjectPattern?: RuleFunction<TSESTree.ObjectPattern>;
PrivateIdentifier?: RuleFunction<TSESTree.PrivateIdentifier>;
Program?: RuleFunction<TSESTree.Program>;
Property?: RuleFunction<TSESTree.Property>;
PropertyDefinition?: RuleFunction<TSESTree.PropertyDefinition>;
RestElement?: RuleFunction<TSESTree.RestElement>;
ReturnStatement?: RuleFunction<TSESTree.ReturnStatement>;
SequenceExpression?: RuleFunction<TSESTree.SequenceExpression>;
SpreadElement?: RuleFunction<TSESTree.SpreadElement>;
StaticBlock?: RuleFunction<TSESTree.StaticBlock>;
Super?: RuleFunction<TSESTree.Super>;
SwitchCase?: RuleFunction<TSESTree.SwitchCase>;
SwitchStatement?: RuleFunction<TSESTree.SwitchStatement>;
TaggedTemplateExpression?: RuleFunction<TSESTree.TaggedTemplateExpression>;
TemplateElement?: RuleFunction<TSESTree.TemplateElement>;
TemplateLiteral?: RuleFunction<TSESTree.TemplateLiteral>;
ThisExpression?: RuleFunction<TSESTree.ThisExpression>;
ThrowStatement?: RuleFunction<TSESTree.ThrowStatement>;
TryStatement?: RuleFunction<TSESTree.TryStatement>;
TSAbstractAccessorProperty?: RuleFunction<TSESTree.TSAbstractAccessorProperty>;
TSAbstractKeyword?: RuleFunction<TSESTree.TSAbstractKeyword>;
TSAbstractMethodDefinition?: RuleFunction<TSESTree.TSAbstractMethodDefinition>;
TSAbstractPropertyDefinition?: RuleFunction<TSESTree.TSAbstractPropertyDefinition>;
TSAnyKeyword?: RuleFunction<TSESTree.TSAnyKeyword>;
TSArrayType?: RuleFunction<TSESTree.TSArrayType>;
TSAsExpression?: RuleFunction<TSESTree.TSAsExpression>;
TSAsyncKeyword?: RuleFunction<TSESTree.TSAsyncKeyword>;
TSBigIntKeyword?: RuleFunction<TSESTree.TSBigIntKeyword>;
TSBooleanKeyword?: RuleFunction<TSESTree.TSBooleanKeyword>;
TSCallSignatureDeclaration?: RuleFunction<TSESTree.TSCallSignatureDeclaration>;
TSClassImplements?: RuleFunction<TSESTree.TSClassImplements>;
TSConditionalType?: RuleFunction<TSESTree.TSConditionalType>;
TSConstructorType?: RuleFunction<TSESTree.TSConstructorType>;
TSConstructSignatureDeclaration?: RuleFunction<TSESTree.TSConstructSignatureDeclaration>;
TSDeclareFunction?: RuleFunction<TSESTree.TSDeclareFunction>;
TSDeclareKeyword?: RuleFunction<TSESTree.TSDeclareKeyword>;
TSEmptyBodyFunctionExpression?: RuleFunction<TSESTree.TSEmptyBodyFunctionExpression>;
TSEnumBody?: RuleFunction<TSESTree.TSEnumBody>;
TSEnumDeclaration?: RuleFunction<TSESTree.TSEnumDeclaration>;
TSEnumMember?: RuleFunction<TSESTree.TSEnumMember>;
TSExportAssignment?: RuleFunction<TSESTree.TSExportAssignment>;
TSExportKeyword?: RuleFunction<TSESTree.TSExportKeyword>;
TSExternalModuleReference?: RuleFunction<TSESTree.TSExternalModuleReference>;
TSFunctionType?: RuleFunction<TSESTree.TSFunctionType>;
TSImportEqualsDeclaration?: RuleFunction<TSESTree.TSImportEqualsDeclaration>;
TSImportType?: RuleFunction<TSESTree.TSImportType>;
TSIndexedAccessType?: RuleFunction<TSESTree.TSIndexedAccessType>;
TSIndexSignature?: RuleFunction<TSESTree.TSIndexSignature>;
TSInferType?: RuleFunction<TSESTree.TSInferType>;
TSInstantiationExpression?: RuleFunction<TSESTree.TSInstantiationExpression>;
TSInterfaceBody?: RuleFunction<TSESTree.TSInterfaceBody>;
TSInterfaceDeclaration?: RuleFunction<TSESTree.TSInterfaceDeclaration>;
TSInterfaceHeritage?: RuleFunction<TSESTree.TSInterfaceHeritage>;
TSIntersectionType?: RuleFunction<TSESTree.TSIntersectionType>;
TSIntrinsicKeyword?: RuleFunction<TSESTree.TSIntrinsicKeyword>;
TSLiteralType?: RuleFunction<TSESTree.TSLiteralType>;
TSMappedType?: RuleFunction<TSESTree.TSMappedType>;
TSMethodSignature?: RuleFunction<TSESTree.TSMethodSignature>;
TSModuleBlock?: RuleFunction<TSESTree.TSModuleBlock>;
TSModuleDeclaration?: RuleFunction<TSESTree.TSModuleDeclaration>;
TSNamedTupleMember?: RuleFunction<TSESTree.TSNamedTupleMember>;
TSNamespaceExportDeclaration?: RuleFunction<TSESTree.TSNamespaceExportDeclaration>;
TSNeverKeyword?: RuleFunction<TSESTree.TSNeverKeyword>;
TSNonNullExpression?: RuleFunction<TSESTree.TSNonNullExpression>;
TSNullKeyword?: RuleFunction<TSESTree.TSNullKeyword>;
TSNumberKeyword?: RuleFunction<TSESTree.TSNumberKeyword>;
TSObjectKeyword?: RuleFunction<TSESTree.TSObjectKeyword>;
TSOptionalType?: RuleFunction<TSESTree.TSOptionalType>;
TSParameterProperty?: RuleFunction<TSESTree.TSParameterProperty>;
TSPrivateKeyword?: RuleFunction<TSESTree.TSPrivateKeyword>;
TSPropertySignature?: RuleFunction<TSESTree.TSPropertySignature>;
TSProtectedKeyword?: RuleFunction<TSESTree.TSProtectedKeyword>;
TSPublicKeyword?: RuleFunction<TSESTree.TSPublicKeyword>;
TSQualifiedName?: RuleFunction<TSESTree.TSQualifiedName>;
TSReadonlyKeyword?: RuleFunction<TSESTree.TSReadonlyKeyword>;
TSRestType?: RuleFunction<TSESTree.TSRestType>;
TSSatisfiesExpression?: RuleFunction<TSESTree.TSSatisfiesExpression>;
TSStaticKeyword?: RuleFunction<TSESTree.TSStaticKeyword>;
TSStringKeyword?: RuleFunction<TSESTree.TSStringKeyword>;
TSSymbolKeyword?: RuleFunction<TSESTree.TSSymbolKeyword>;
TSTemplateLiteralType?: RuleFunction<TSESTree.TSTemplateLiteralType>;
TSThisType?: RuleFunction<TSESTree.TSThisType>;
TSTupleType?: RuleFunction<TSESTree.TSTupleType>;
TSTypeAliasDeclaration?: RuleFunction<TSESTree.TSTypeAliasDeclaration>;
TSTypeAnnotation?: RuleFunction<TSESTree.TSTypeAnnotation>;
TSTypeAssertion?: RuleFunction<TSESTree.TSTypeAssertion>;
TSTypeLiteral?: RuleFunction<TSESTree.TSTypeLiteral>;
TSTypeOperator?: RuleFunction<TSESTree.TSTypeOperator>;
TSTypeParameter?: RuleFunction<TSESTree.TSTypeParameter>;
TSTypeParameterDeclaration?: RuleFunction<TSESTree.TSTypeParameterDeclaration>;
TSTypeParameterInstantiation?: RuleFunction<TSESTree.TSTypeParameterInstantiation>;
TSTypePredicate?: RuleFunction<TSESTree.TSTypePredicate>;
TSTypeQuery?: RuleFunction<TSESTree.TSTypeQuery>;
TSTypeReference?: RuleFunction<TSESTree.TSTypeReference>;
TSUndefinedKeyword?: RuleFunction<TSESTree.TSUndefinedKeyword>;
TSUnionType?: RuleFunction<TSESTree.TSUnionType>;
TSUnknownKeyword?: RuleFunction<TSESTree.TSUnknownKeyword>;
TSVoidKeyword?: RuleFunction<TSESTree.TSVoidKeyword>;
UnaryExpression?: RuleFunction<TSESTree.UnaryExpression>;
UpdateExpression?: RuleFunction<TSESTree.UpdateExpression>;
VariableDeclaration?: RuleFunction<TSESTree.VariableDeclaration>;
VariableDeclarator?: RuleFunction<TSESTree.VariableDeclarator>;
WhileStatement?: RuleFunction<TSESTree.WhileStatement>;
WithStatement?: RuleFunction<TSESTree.WithStatement>;
YieldExpression?: RuleFunction<TSESTree.YieldExpression>;
}
type RuleListenerExitSelectors = {
[K in keyof RuleListenerBaseSelectors as `${K}:exit`]: RuleListenerBaseSelectors[K];
};
type RuleListenerCatchAllBaseCase = Record<string, RuleFunction | undefined>;
export interface RuleListenerExtension {
}
export type RuleListener = RuleListenerBaseSelectors & RuleListenerCatchAllBaseCase & RuleListenerExitSelectors;
export interface RuleModule<MessageIds extends string, Options extends readonly unknown[] = [], Docs = unknown, ExtendedRuleListener extends RuleListener = RuleListener> {
/**
* Function which returns an object with methods that ESLint calls to “visit”
* nodes while traversing the abstract syntax tree.
*/
create(context: Readonly<RuleContext<MessageIds, Options>>): ExtendedRuleListener;
/**
* @deprecated Use meta.defaultOptions instead
* Default options the rule will be run with
*/
defaultOptions?: Options;
/**
* Metadata about the rule
*/
meta: RuleMetaData<MessageIds, Docs, Options>;
/**
* Rule name
*/
name?: string;
}
export type AnyRuleModule = RuleModule<string, readonly unknown[]>;
export interface RuleModuleWithMetaDocs<MessageIds extends string, Options extends readonly unknown[] = [], Docs = unknown, ExtendedRuleListener extends RuleListener = RuleListener> extends RuleModule<MessageIds, Options, Docs, ExtendedRuleListener> {
/**
* Metadata about the rule
*/
meta: RuleMetaDataWithDocs<MessageIds, Docs, Options>;
}
export type AnyRuleModuleWithMetaDocs = RuleModuleWithMetaDocs<string, unknown[]>;
/**
* A loose definition of the RuleModule type for use with configs. This type is
* intended to relax validation of types so that we can have basic validation
* without being overly strict about nitty gritty details matching.
*
* For example the plugin might be declared using an old version of our types or
* they might use the DefinitelyTyped eslint types. Ultimately we don't need
* super strict validation in a config - a loose shape match is "good enough" to
* help validate the config is correct.
*
* @see {@link LooseParserModule}, {@link LooseProcessorModule}
*/
export type LooseRuleDefinition = LooseRuleCreateFunction | {
create: LooseRuleCreateFunction;
meta?: object | undefined;
};
export type LooseRuleCreateFunction = (context: any) => Record<string, Function | undefined>;
export type RuleCreateFunction<MessageIds extends string = never, Options extends readonly unknown[] = unknown[]> = (context: Readonly<RuleContext<MessageIds, Options>>) => RuleListener;
export type AnyRuleCreateFunction = RuleCreateFunction<string, readonly unknown[]>;
export {};

View File

@@ -0,0 +1,4 @@
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"missingAwait" | "removeAsync", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;