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,19 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.es2017_sharedmemory = void 0;
const base_config_1 = require("./base-config");
const es2015_symbol_1 = require("./es2015.symbol");
const es2015_symbol_wellknown_1 = require("./es2015.symbol.wellknown");
exports.es2017_sharedmemory = {
libs: [es2015_symbol_1.es2015_symbol, es2015_symbol_wellknown_1.es2015_symbol_wellknown],
variables: [
['SharedArrayBuffer', base_config_1.TYPE_VALUE],
['SharedArrayBufferConstructor', base_config_1.TYPE],
['ArrayBufferTypes', base_config_1.TYPE],
['Atomics', base_config_1.TYPE_VALUE],
],
};

View File

@@ -0,0 +1,22 @@
{
"nickyout/fast-stable-stringify": {
"chrome 26": {
"Windows 2008": {
"opsPerSec": 6.025,
"percentage": 6.76,
"numSamples": 50,
"cumStrLength": 94425969
}
}
},
"substack/json-stable-stringify": {
"chrome 26": {
"Windows 2008": {
"opsPerSec": 4.114,
"percentage": 1.05,
"numSamples": 50,
"cumStrLength": 61301724
}
}
}
}

View File

@@ -0,0 +1,44 @@
/*! *****************************************************************************
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.
***************************************************************************** */
interface SymbolConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Symbol;
/**
* Returns a new unique Symbol value.
* @param description Description of the new Symbol object.
*/
(description?: string | number): symbol;
/**
* Returns a Symbol object from the global symbol registry matching the given key if found.
* Otherwise, returns a new symbol with this key.
* @param key key to search for.
*/
for(key: string): symbol;
/**
* Returns a key from the global symbol registry matching the given Symbol if found.
* Otherwise, returns undefined.
* @param sym Symbol to find the key for.
*/
keyFor(sym: symbol): string | undefined;
}
declare var Symbol: SymbolConstructor;

View File

@@ -0,0 +1,153 @@
/**
* @fileoverview Rule to flag use of an empty block statement
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
hasSuggestions: true,
type: "suggestion",
defaultOptions: [
{
allowEmptyCatch: false,
},
],
docs: {
description: "Disallow empty block statements",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-empty",
},
schema: [
{
type: "object",
properties: {
allowEmptyCatch: {
type: "boolean",
},
},
additionalProperties: false,
},
],
messages: {
unexpected: "Empty {{type}} statement.",
suggestComment: "Add comment inside empty {{type}} statement.",
},
},
create(context) {
const [{ allowEmptyCatch }] = context.options;
const sourceCode = context.sourceCode;
return {
BlockStatement(node) {
// if the body is not empty, we can just return immediately
if (node.body.length !== 0) {
return;
}
// a function is generally allowed to be empty
if (astUtils.isFunction(node.parent)) {
return;
}
if (allowEmptyCatch && node.parent.type === "CatchClause") {
return;
}
// any other block is only allowed to be empty, if it contains a comment
if (sourceCode.getCommentsInside(node).length > 0) {
return;
}
context.report({
node,
messageId: "unexpected",
data: { type: "block" },
suggest: [
{
messageId: "suggestComment",
data: { type: "block" },
fix(fixer) {
const range = [
node.range[0] + 1,
node.range[1] - 1,
];
return fixer.replaceTextRange(
range,
" /* empty */ ",
);
},
},
],
});
},
SwitchStatement(node) {
if (
typeof node.cases === "undefined" ||
node.cases.length === 0
) {
const openingBrace = sourceCode.getTokenAfter(
node.discriminant,
astUtils.isOpeningBraceToken,
);
const closingBrace = sourceCode.getLastToken(node);
if (
sourceCode.commentsExistBetween(
openingBrace,
closingBrace,
)
) {
return;
}
context.report({
node,
loc: {
start: openingBrace.loc.start,
end: closingBrace.loc.end,
},
messageId: "unexpected",
data: { type: "switch" },
suggest: [
{
messageId: "suggestComment",
data: { type: "switch" },
fix(fixer) {
const range = [
openingBrace.range[1],
closingBrace.range[0],
];
return fixer.replaceTextRange(
range,
" /* empty */ ",
);
},
},
],
});
}
},
};
},
};

View File

@@ -0,0 +1,29 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface String {
/**
* Returns true if all leading surrogates and trailing surrogates appear paired and in order.
*/
isWellFormed(): boolean;
/**
* Returns a string where all lone or out-of-order surrogates have been replaced by the Unicode replacement character (U+FFFD).
*/
toWellFormed(): string;
}

View File

@@ -0,0 +1,6 @@
function _getPrototypeOf(t) {
return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
return t.__proto__ || Object.getPrototypeOf(t);
}, _getPrototypeOf(t);
}
export { _getPrototypeOf as default };

View File

@@ -0,0 +1,9 @@
import { M as ModuleMockerInterceptor, a as ModuleMockerCompilerHints, b as ModuleMocker } from './mocker.d-QEntlm6J.js';
import '@vitest/spy';
import './types.d-BjI5eAwu.js';
import './index.d-B41z0AuW.js';
declare function registerModuleMocker(interceptor: (accessor: string) => ModuleMockerInterceptor): ModuleMockerCompilerHints;
declare function registerNativeFactoryResolver(mocker: ModuleMocker): void;
export { registerModuleMocker, registerNativeFactoryResolver };

View File

@@ -0,0 +1,165 @@
/**
* @fileoverview Rule to flag use of duplicate keys in an object.
* @author Ian Christian Myers
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const GET_KIND = /^(?:init|get)$/u;
const SET_KIND = /^(?:init|set)$/u;
/**
* The class which stores properties' information of an object.
*/
class ObjectInfo {
/**
* @param {ObjectInfo|null} upper The information of the outer object.
* @param {ASTNode} node The ObjectExpression node of this information.
*/
constructor(upper, node) {
this.upper = upper;
this.node = node;
this.properties = new Map();
}
/**
* Gets the information of the given Property node.
* @param {ASTNode} node The Property node to get.
* @returns {{get: boolean, set: boolean}} The information of the property.
*/
getPropertyInfo(node) {
const name = astUtils.getStaticPropertyName(node);
if (!this.properties.has(name)) {
this.properties.set(name, { get: false, set: false });
}
return this.properties.get(name);
}
/**
* Checks whether the given property has been defined already or not.
* @param {ASTNode} node The Property node to check.
* @returns {boolean} `true` if the property has been defined.
*/
isPropertyDefined(node) {
const entry = this.getPropertyInfo(node);
return (
(GET_KIND.test(node.kind) && entry.get) ||
(SET_KIND.test(node.kind) && entry.set)
);
}
/**
* Defines the given property.
* @param {ASTNode} node The Property node to define.
* @returns {void}
*/
defineProperty(node) {
const entry = this.getPropertyInfo(node);
if (GET_KIND.test(node.kind)) {
entry.get = true;
}
if (SET_KIND.test(node.kind)) {
entry.set = true;
}
}
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
docs: {
description: "Disallow duplicate keys in object literals",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-dupe-keys",
},
schema: [],
messages: {
unexpected: "Duplicate key '{{name}}'.",
},
},
create(context) {
let info = null;
return {
ObjectExpression(node) {
info = new ObjectInfo(info, node);
},
"ObjectExpression:exit"() {
info = info.upper;
},
Property(node) {
const name = astUtils.getStaticPropertyName(node);
// Skip destructuring.
if (node.parent.type !== "ObjectExpression") {
return;
}
// Skip if the name is not static.
if (name === null) {
return;
}
/*
* Skip if the property node is a proto setter.
* Proto setter is a special syntax that sets
* object's prototype instead of creating a property.
* It can be in one of the following forms:
*
* __proto__: <expression>
* '__proto__': <expression>
* "__proto__": <expression>
*
* Duplicate proto setters produce parsing errors,
* so we can just skip them to not interfere with
* regular properties named "__proto__".
*/
if (
name === "__proto__" &&
node.kind === "init" &&
!node.computed &&
!node.shorthand &&
!node.method
) {
return;
}
// Reports if the name is defined already.
if (info.isPropertyDefined(node)) {
context.report({
node: info.node,
loc: node.key.loc,
messageId: "unexpected",
data: { name },
});
}
// Update info.
info.defineProperty(node);
},
};
},
};

View File

@@ -0,0 +1,36 @@
export declare enum NodeBuilderFlags {
None = 0,
NoTruncation = 1,
WriteArrayAsGenericType = 2,
GenerateNamesForShadowedTypeParams = 4,
UseStructuralFallback = 8,
ForbidIndexedAccessSymbolReferences = 16,
WriteTypeArgumentsOfSignature = 32,
UseFullyQualifiedType = 64,
UseOnlyExternalAliasing = 128,
SuppressAnyReturnType = 256,
WriteTypeParametersInQualifiedName = 512,
MultilineObjectLiterals = 1024,
WriteClassExpressionAsTypeLiteral = 2048,
UseTypeOfFunction = 4096,
OmitParameterModifiers = 8192,
UseAliasDefinedOutsideCurrentScope = 16384,
UseSingleQuotesForStringLiteralType = 268435456,
NoTypeReduction = 536870912,
UseInstantiationExpressions = 1073741824,
OmitThisParameter = 33554432,
WriteCallStyleSignature = 134217728,
AllowThisInObjectLiteral = 32768,
AllowQualifiedNameInPlaceOfIdentifier = 65536,
AllowAnonymousIdentifier = 131072,
AllowEmptyUnionOrIntersection = 262144,
AllowEmptyTuple = 524288,
AllowUniqueESSymbolType = 1048576,
AllowEmptyIndexInfoType = 2097152,
AllowNodeModulesRelativePaths = 67108864,
IgnoreErrors = 70221824,
InObjectTypeLiteral = 4194304,
InTypeAlias = 8388608,
InInitialEntityName = 16777216
}
//# sourceMappingURL=nodeBuilderFlags.enum.d.ts.map

View File

@@ -0,0 +1,7 @@
language: node_js
node_js:
- '4'
- 'lts/*'
- 'node'
env:
- PGUSER=postgres

View File

@@ -0,0 +1,146 @@
/**
* @fileoverview Prefers Object.hasOwn() instead of Object.prototype.hasOwnProperty.call()
* @author Nitin Kumar
* @author Gautam Arora
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks if the given node is considered to be an access to a property of `Object.prototype`.
* @param {ASTNode} node `MemberExpression` node to evaluate.
* @returns {boolean} `true` if `node.object` is `Object`, `Object.prototype`, or `{}` (empty 'ObjectExpression' node).
*/
function hasLeftHandObject(node) {
/*
* ({}).hasOwnProperty.call(obj, prop) - `true`
* ({ foo }.hasOwnProperty.call(obj, prop)) - `false`, object literal should be empty
*/
if (
node.object.type === "ObjectExpression" &&
node.object.properties.length === 0
) {
return true;
}
const objectNodeToCheck =
node.object.type === "MemberExpression" &&
astUtils.getStaticPropertyName(node.object) === "prototype"
? node.object.object
: node.object;
if (
objectNodeToCheck.type === "Identifier" &&
objectNodeToCheck.name === "Object"
) {
return true;
}
return false;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description:
"Disallow use of `Object.prototype.hasOwnProperty.call()` and prefer use of `Object.hasOwn()`",
recommended: false,
url: "https://eslint.org/docs/latest/rules/prefer-object-has-own",
},
schema: [],
messages: {
useHasOwn:
"Use 'Object.hasOwn()' instead of 'Object.prototype.hasOwnProperty.call()'.",
},
fixable: "code",
},
create(context) {
const sourceCode = context.sourceCode;
return {
CallExpression(node) {
if (!(
node.callee.type === "MemberExpression" &&
node.callee.object.type === "MemberExpression"
)) {
return;
}
const calleePropertyName = astUtils.getStaticPropertyName(
node.callee,
);
const objectPropertyName = astUtils.getStaticPropertyName(
node.callee.object,
);
const isObject = hasLeftHandObject(node.callee.object);
// check `Object` scope
const scope = sourceCode.getScope(node);
const variable = astUtils.getVariableByName(scope, "Object");
if (
calleePropertyName === "call" &&
objectPropertyName === "hasOwnProperty" &&
isObject &&
variable &&
variable.scope.type === "global"
) {
context.report({
node,
messageId: "useHasOwn",
fix(fixer) {
if (
sourceCode.getCommentsInside(node.callee)
.length > 0
) {
return null;
}
const tokenJustBeforeNode =
sourceCode.getTokenBefore(node.callee, {
includeComments: true,
});
// for https://github.com/eslint/eslint/pull/15346#issuecomment-991417335
if (
tokenJustBeforeNode &&
tokenJustBeforeNode.range[1] ===
node.callee.range[0] &&
!astUtils.canTokensBeAdjacent(
tokenJustBeforeNode,
"Object.hasOwn",
)
) {
return fixer.replaceText(
node.callee,
" Object.hasOwn",
);
}
return fixer.replaceText(
node.callee,
"Object.hasOwn",
);
},
});
}
},
};
},
};

View File

@@ -0,0 +1,63 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Awaitable = void 0;
exports.needsToBeAwaited = needsToBeAwaited;
const type_utils_1 = require("@typescript-eslint/type-utils");
const tsutils = __importStar(require("ts-api-utils"));
const getConstraintInfo_1 = require("./getConstraintInfo");
var Awaitable;
(function (Awaitable) {
Awaitable[Awaitable["Always"] = 0] = "Always";
Awaitable[Awaitable["Never"] = 1] = "Never";
Awaitable[Awaitable["May"] = 2] = "May";
})(Awaitable || (exports.Awaitable = Awaitable = {}));
function needsToBeAwaited(checker, node, type) {
const { constraintType, isTypeParameter } = (0, getConstraintInfo_1.getConstraintInfo)(checker, type);
// unconstrained generic types should be treated as unknown
if (isTypeParameter && constraintType == null) {
return Awaitable.May;
}
// `any` and `unknown` types may need to be awaited
if ((0, type_utils_1.isTypeAnyType)(constraintType) || (0, type_utils_1.isTypeUnknownType)(constraintType)) {
return Awaitable.May;
}
// 'thenable' values should always be be awaited
if (tsutils.isThenableType(checker, node, constraintType)) {
return Awaitable.Always;
}
// anything else should not be awaited
return Awaitable.Never;
}

View File

@@ -0,0 +1,85 @@
import { FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';
import { NumberCodecConfig } from './common';
/**
* Returns an encoder for 16-bit unsigned integers (`u16`).
*
* This encoder serializes `u16` values using two bytes in little-endian format by default.
* You may specify big-endian storage using the `endian` option.
*
* For more details, see {@link getU16Codec}.
*
* @param config - Optional settings for endianness.
* @returns A `FixedSizeEncoder<number | bigint, 2>` for encoding `u16` values.
*
* @example
* Encoding a `u16` value.
* ```ts
* const encoder = getU16Encoder();
* const bytes = encoder.encode(42); // 0x2a00
* ```
*
* @see {@link getU16Codec}
*/
export declare const getU16Encoder: (config?: NumberCodecConfig) => FixedSizeEncoder<bigint | number, 2>;
/**
* Returns a decoder for 16-bit unsigned integers (`u16`).
*
* This decoder deserializes `u16` values from two bytes in little-endian format by default.
* You may specify big-endian storage using the `endian` option.
*
* For more details, see {@link getU16Codec}.
*
* @param config - Optional settings for endianness.
* @returns A `FixedSizeDecoder<number, 2>` for decoding `u16` values.
*
* @example
* Decoding a `u16` value.
* ```ts
* const decoder = getU16Decoder();
* const value = decoder.decode(new Uint8Array([0x2a, 0x00])); // 42
* ```
*
* @see {@link getU16Codec}
*/
export declare const getU16Decoder: (config?: NumberCodecConfig) => FixedSizeDecoder<number, 2>;
/**
* Returns a codec for encoding and decoding 16-bit unsigned integers (`u16`).
*
* This codec serializes `u16` values using two bytes in little-endian format by default.
* You may specify big-endian storage using the `endian` option.
*
* @param config - Optional settings for endianness.
* @returns A `FixedSizeCodec<number | bigint, number, 2>` for encoding and decoding `u16` values.
*
* @example
* Encoding and decoding a `u16` value.
* ```ts
* const codec = getU16Codec();
* const bytes = codec.encode(42); // 0x2a00 (little-endian)
* const value = codec.decode(bytes); // 42
* ```
*
* @example
* Storing values in big-endian format.
* ```ts
* const codec = getU16Codec({ endian: Endian.Big });
* const bytes = codec.encode(42); // 0x002a
* ```
*
* @remarks
* This codec supports values between `0` and `2^16 - 1`.
* If you need a larger range, consider using {@link getU32Codec} or {@link getU64Codec}.
* For signed integers, use {@link getI16Codec}.
*
* Separate {@link getU16Encoder} and {@link getU16Decoder} functions are available.
*
* ```ts
* const bytes = getU16Encoder().encode(42);
* const value = getU16Decoder().decode(bytes);
* ```
*
* @see {@link getU16Encoder}
* @see {@link getU16Decoder}
*/
export declare const getU16Codec: (config?: NumberCodecConfig) => FixedSizeCodec<bigint | number, number, 2>;
//# sourceMappingURL=u16.d.ts.map

View File

@@ -0,0 +1,12 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{# def.numberKeyword }}
{{ var $op = $keyword == 'maxProperties' ? '>' : '<'; }}
if ({{# def.$dataNotType:'number' }} Object.keys({{=$data}}).length {{=$op}} {{=$schemaValue}}) {
{{ var $errorKeyword = $keyword; }}
{{# def.error:'_limitProperties' }}
} {{? $breakOnError }} else { {{?}}

View File

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

View File

@@ -0,0 +1,13 @@
/* eslint-disable no-console */
'use strict'
let printed = {}
module.exports = function warnOnce(message) {
if (printed[message]) return
printed[message] = true
if (typeof console !== 'undefined' && console.warn) {
console.warn(message)
}
}

View File

@@ -0,0 +1,210 @@
# type-check [![Build Status](https://travis-ci.org/gkz/type-check.png?branch=master)](https://travis-ci.org/gkz/type-check)
<a name="type-check" />
`type-check` is a library which allows you to check the types of JavaScript values at runtime with a Haskell like type syntax. It is great for checking external input, for testing, or even for adding a bit of safety to your internal code. It is a major component of [levn](https://github.com/gkz/levn). MIT license. Version 0.4.0. Check out the [demo](http://gkz.github.io/type-check/).
For updates on `type-check`, [follow me on twitter](https://twitter.com/gkzahariev).
npm install type-check
## Quick Examples
```js
// Basic types:
var typeCheck = require('type-check').typeCheck;
typeCheck('Number', 1); // true
typeCheck('Number', 'str'); // false
typeCheck('Error', new Error); // true
typeCheck('Undefined', undefined); // true
// Comment
typeCheck('count::Number', 1); // true
// One type OR another type:
typeCheck('Number | String', 2); // true
typeCheck('Number | String', 'str'); // true
// Wildcard, matches all types:
typeCheck('*', 2) // true
// Array, all elements of a single type:
typeCheck('[Number]', [1, 2, 3]); // true
typeCheck('[Number]', [1, 'str', 3]); // false
// Tuples, or fixed length arrays with elements of different types:
typeCheck('(String, Number)', ['str', 2]); // true
typeCheck('(String, Number)', ['str']); // false
typeCheck('(String, Number)', ['str', 2, 5]); // false
// Object properties:
typeCheck('{x: Number, y: Boolean}', {x: 2, y: false}); // true
typeCheck('{x: Number, y: Boolean}', {x: 2}); // false
typeCheck('{x: Number, y: Maybe Boolean}', {x: 2}); // true
typeCheck('{x: Number, y: Boolean}', {x: 2, y: false, z: 3}); // false
typeCheck('{x: Number, y: Boolean, ...}', {x: 2, y: false, z: 3}); // true
// A particular type AND object properties:
typeCheck('RegExp{source: String, ...}', /re/i); // true
typeCheck('RegExp{source: String, ...}', {source: 're'}); // false
// Custom types:
var opt = {customTypes:
{Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; }}}};
typeCheck('Even', 2, opt); // true
// Nested:
var type = '{a: (String, [Number], {y: Array, ...}), b: Error{message: String, ...}}'
typeCheck(type, {a: ['hi', [1, 2, 3], {y: [1, 'ms']}], b: new Error('oh no')}); // true
```
Check out the [type syntax format](#syntax) and [guide](#guide).
## Usage
`require('type-check');` returns an object that exposes four properties. `VERSION` is the current version of the library as a string. `typeCheck`, `parseType`, and `parsedTypeCheck` are functions.
```js
// typeCheck(type, input, options);
typeCheck('Number', 2); // true
// parseType(type);
var parsedType = parseType('Number'); // object
// parsedTypeCheck(parsedType, input, options);
parsedTypeCheck(parsedType, 2); // true
```
### typeCheck(type, input, options)
`typeCheck` checks a JavaScript value `input` against `type` written in the [type format](#type-format) (and taking account the optional `options`) and returns whether the `input` matches the `type`.
##### arguments
* type - `String` - the type written in the [type format](#type-format) which to check against
* input - `*` - any JavaScript value, which is to be checked against the type
* options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types)
##### returns
`Boolean` - whether the input matches the type
##### example
```js
typeCheck('Number', 2); // true
```
### parseType(type)
`parseType` parses string `type` written in the [type format](#type-format) into an object representing the parsed type.
##### arguments
* type - `String` - the type written in the [type format](#type-format) which to parse
##### returns
`Object` - an object in the parsed type format representing the parsed type
##### example
```js
parseType('Number'); // [{type: 'Number'}]
```
### parsedTypeCheck(parsedType, input, options)
`parsedTypeCheck` checks a JavaScript value `input` against parsed `type` in the parsed type format (and taking account the optional `options`) and returns whether the `input` matches the `type`. Use this in conjunction with `parseType` if you are going to use a type more than once.
##### arguments
* type - `Object` - the type in the parsed type format which to check against
* input - `*` - any JavaScript value, which is to be checked against the type
* options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types)
##### returns
`Boolean` - whether the input matches the type
##### example
```js
parsedTypeCheck([{type: 'Number'}], 2); // true
var parsedType = parseType('String');
parsedTypeCheck(parsedType, 'str'); // true
```
<a name="type-format" />
## Type Format
### Syntax
White space is ignored. The root node is a __Types__.
* __Identifier__ = `[\$\w]+` - a group of any lower or upper case letters, numbers, underscores, or dollar signs - eg. `String`
* __Type__ = an `Identifier`, an `Identifier` followed by a `Structure`, just a `Structure`, or a wildcard `*` - eg. `String`, `Object{x: Number}`, `{x: Number}`, `Array{0: String, 1: Boolean, length: Number}`, `*`
* __Types__ = optionally a comment (an `Identifier` followed by a `::`), optionally the identifier `Maybe`, one or more `Type`, separated by `|` - eg. `Number`, `String | Date`, `Maybe Number`, `Maybe Boolean | String`
* __Structure__ = `Fields`, or a `Tuple`, or an `Array` - eg. `{x: Number}`, `(String, Number)`, `[Date]`
* __Fields__ = a `{`, followed one or more `Field` separated by a comma `,` (trailing comma `,` is permitted), optionally an `...` (always preceded by a comma `,`), followed by a `}` - eg. `{x: Number, y: String}`, `{k: Function, ...}`
* __Field__ = an `Identifier`, followed by a colon `:`, followed by `Types` - eg. `x: Date | String`, `y: Boolean`
* __Tuple__ = a `(`, followed by one or more `Types` separated by a comma `,` (trailing comma `,` is permitted), followed by a `)` - eg `(Date)`, `(Number, Date)`
* __Array__ = a `[` followed by exactly one `Types` followed by a `]` - eg. `[Boolean]`, `[Boolean | Null]`
### Guide
`type-check` uses `Object.toString` to find out the basic type of a value. Specifically,
```js
{}.toString.call(VALUE).slice(8, -1)
{}.toString.call(true).slice(8, -1) // 'Boolean'
```
A basic type, eg. `Number`, uses this check. This is much more versatile than using `typeof` - for example, with `document`, `typeof` produces `'object'` which isn't that useful, and our technique produces `'HTMLDocument'`.
You may check for multiple types by separating types with a `|`. The checker proceeds from left to right, and passes if the value is any of the types - eg. `String | Boolean` first checks if the value is a string, and then if it is a boolean. If it is none of those, then it returns false.
Adding a `Maybe` in front of a list of multiple types is the same as also checking for `Null` and `Undefined` - eg. `Maybe String` is equivalent to `Undefined | Null | String`.
You may add a comment to remind you of what the type is for by following an identifier with a `::` before a type (or multiple types). The comment is simply thrown out.
The wildcard `*` matches all types.
There are three types of structures for checking the contents of a value: 'fields', 'tuple', and 'array'.
If used by itself, a 'fields' structure will pass with any type of object as long as it is an instance of `Object` and the properties pass - this allows for duck typing - eg. `{x: Boolean}`.
To check if the properties pass, and the value is of a certain type, you can specify the type - eg. `Error{message: String}`.
If you want to make a field optional, you can simply use `Maybe` - eg. `{x: Boolean, y: Maybe String}` will still pass if `y` is undefined (or null).
If you don't care if the value has properties beyond what you have specified, you can use the 'etc' operator `...` - eg. `{x: Boolean, ...}` will match an object with an `x` property that is a boolean, and with zero or more other properties.
For an array, you must specify one or more types (separated by `|`) - it will pass for something of any length as long as each element passes the types provided - eg. `[Number]`, `[Number | String]`.
A tuple checks for a fixed number of elements, each of a potentially different type. Each element is separated by a comma - eg. `(String, Number)`.
An array and tuple structure check that the value is of type `Array` by default, but if another type is specified, they will check for that instead - eg. `Int32Array[Number]`. You can use the wildcard `*` to search for any type at all.
Check out the [type precedence](https://github.com/zaboco/type-precedence) library for type-check.
## Options
Options is an object. It is an optional parameter to the `typeCheck` and `parsedTypeCheck` functions. The only current option is `customTypes`.
<a name="custom-types" />
### Custom Types
__Example:__
```js
var options = {
customTypes: {
Even: {
typeOf: 'Number',
validate: function(x) {
return x % 2 === 0;
}
}
}
};
typeCheck('Even', 2, options); // true
typeCheck('Even', 3, options); // false
```
`customTypes` allows you to set up custom types for validation. The value of this is an object. The keys of the object are the types you will be matching. Each value of the object will be an object having a `typeOf` property - a string, and `validate` property - a function.
The `typeOf` property is the type the value should be (optional - if not set only `validate` will be used), and `validate` is a function which should return true if the value is of that type. `validate` receives one parameter, which is the value that we are checking.
## Technical About
`type-check` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It also uses the [prelude.ls](http://preludels.com/) library.

View File

@@ -0,0 +1,291 @@
/**
* @fileoverview Checks for unreachable code due to return, throws, break, and continue.
* @author Joel Feenstra
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const { isAnySegmentReachable } = require("./utils/code-path-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* @typedef {Object} ConstructorInfo
* @property {ConstructorInfo | null} upper Info about the constructor that encloses this constructor.
* @property {boolean} hasSuperCall The flag about having `super()` expressions.
*/
/**
* Checks whether or not a given variable declarator has the initializer.
* @param {ASTNode} node A VariableDeclarator node to check.
* @returns {boolean} `true` if the node has the initializer.
*/
function isInitialized(node) {
return Boolean(node.init);
}
/**
* The class to distinguish consecutive unreachable statements.
*/
class ConsecutiveRange {
constructor(sourceCode) {
this.sourceCode = sourceCode;
this.startNode = null;
this.endNode = null;
}
/**
* The location object of this range.
* @type {Object}
*/
get location() {
return {
start: this.startNode.loc.start,
end: this.endNode.loc.end,
};
}
/**
* `true` if this range is empty.
* @type {boolean}
*/
get isEmpty() {
return !(this.startNode && this.endNode);
}
/**
* Checks whether the given node is inside of this range.
* @param {ASTNode|Token} node The node to check.
* @returns {boolean} `true` if the node is inside of this range.
*/
contains(node) {
return (
node.range[0] >= this.startNode.range[0] &&
node.range[1] <= this.endNode.range[1]
);
}
/**
* Checks whether the given node is consecutive to this range.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is consecutive to this range.
*/
isConsecutive(node) {
return this.contains(this.sourceCode.getTokenBefore(node));
}
/**
* Merges the given node to this range.
* @param {ASTNode} node The node to merge.
* @returns {void}
*/
merge(node) {
this.endNode = node;
}
/**
* Resets this range by the given node or null.
* @param {ASTNode|null} node The node to reset, or null.
* @returns {void}
*/
reset(node) {
this.startNode = this.endNode = node;
}
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
docs: {
description:
"Disallow unreachable code after `return`, `throw`, `continue`, and `break` statements",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-unreachable",
},
schema: [],
messages: {
unreachableCode: "Unreachable code.",
},
},
create(context) {
/** @type {ConstructorInfo | null} */
let constructorInfo = null;
/** @type {ConsecutiveRange} */
const range = new ConsecutiveRange(context.sourceCode);
/** @type {Array<Set<CodePathSegment>>} */
const codePathSegments = [];
/** @type {Set<CodePathSegment>} */
let currentCodePathSegments = new Set();
/**
* Reports a given node if it's unreachable.
* @param {ASTNode} node A statement node to report.
* @returns {void}
*/
function reportIfUnreachable(node) {
let nextNode = null;
if (
node &&
(node.type === "PropertyDefinition" ||
!isAnySegmentReachable(currentCodePathSegments))
) {
// Store this statement to distinguish consecutive statements.
if (range.isEmpty) {
range.reset(node);
return;
}
// Skip if this statement is inside of the current range.
if (range.contains(node)) {
return;
}
// Merge if this statement is consecutive to the current range.
if (range.isConsecutive(node)) {
range.merge(node);
return;
}
nextNode = node;
}
/*
* Report the current range since this statement is reachable or is
* not consecutive to the current range.
*/
if (!range.isEmpty) {
context.report({
messageId: "unreachableCode",
loc: range.location,
node: range.startNode,
});
}
// Update the current range.
range.reset(nextNode);
}
return {
// Manages the current code path.
onCodePathStart() {
codePathSegments.push(currentCodePathSegments);
currentCodePathSegments = new Set();
},
onCodePathEnd() {
currentCodePathSegments = codePathSegments.pop();
},
onUnreachableCodePathSegmentStart(segment) {
currentCodePathSegments.add(segment);
},
onUnreachableCodePathSegmentEnd(segment) {
currentCodePathSegments.delete(segment);
},
onCodePathSegmentEnd(segment) {
currentCodePathSegments.delete(segment);
},
onCodePathSegmentStart(segment) {
currentCodePathSegments.add(segment);
},
// Registers for all statement nodes (excludes FunctionDeclaration).
BlockStatement: reportIfUnreachable,
BreakStatement: reportIfUnreachable,
ClassDeclaration: reportIfUnreachable,
ContinueStatement: reportIfUnreachable,
DebuggerStatement: reportIfUnreachable,
DoWhileStatement: reportIfUnreachable,
ExpressionStatement: reportIfUnreachable,
ForInStatement: reportIfUnreachable,
ForOfStatement: reportIfUnreachable,
ForStatement: reportIfUnreachable,
IfStatement: reportIfUnreachable,
ImportDeclaration: reportIfUnreachable,
LabeledStatement: reportIfUnreachable,
ReturnStatement: reportIfUnreachable,
SwitchStatement: reportIfUnreachable,
ThrowStatement: reportIfUnreachable,
TryStatement: reportIfUnreachable,
VariableDeclaration(node) {
if (
node.kind !== "var" ||
node.declarations.some(isInitialized)
) {
reportIfUnreachable(node);
}
},
WhileStatement: reportIfUnreachable,
WithStatement: reportIfUnreachable,
ExportNamedDeclaration: reportIfUnreachable,
ExportDefaultDeclaration: reportIfUnreachable,
ExportAllDeclaration: reportIfUnreachable,
"Program:exit"() {
reportIfUnreachable();
},
/*
* Instance fields defined in a subclass are never created if the constructor of the subclass
* doesn't call `super()`, so their definitions are unreachable code.
*/
"MethodDefinition[kind='constructor']"() {
constructorInfo = {
upper: constructorInfo,
hasSuperCall: false,
};
},
"MethodDefinition[kind='constructor']:exit"(node) {
const { hasSuperCall } = constructorInfo;
constructorInfo = constructorInfo.upper;
// skip typescript constructors without the body
if (!node.value.body) {
return;
}
const classDefinition = node.parent.parent;
if (classDefinition.superClass && !hasSuperCall) {
for (const element of classDefinition.body.body) {
if (
element.type === "PropertyDefinition" &&
!element.static
) {
reportIfUnreachable(element);
}
}
}
},
"CallExpression > Super.callee"() {
if (constructorInfo) {
constructorInfo.hasSuperCall = true;
}
},
};
},
};

View File

@@ -0,0 +1,203 @@
'use strict';
const { tokenChars } = require('./validation');
/**
* Adds an offer to the map of extension offers or a parameter to the map of
* parameters.
*
* @param {Object} dest The map of extension offers or parameters
* @param {String} name The extension or parameter name
* @param {(Object|Boolean|String)} elem The extension parameters or the
* parameter value
* @private
*/
function push(dest, name, elem) {
if (dest[name] === undefined) dest[name] = [elem];
else dest[name].push(elem);
}
/**
* Parses the `Sec-WebSocket-Extensions` header into an object.
*
* @param {String} header The field value of the header
* @return {Object} The parsed object
* @public
*/
function parse(header) {
const offers = Object.create(null);
let params = Object.create(null);
let mustUnescape = false;
let isEscaping = false;
let inQuotes = false;
let extensionName;
let paramName;
let start = -1;
let code = -1;
let end = -1;
let i = 0;
for (; i < header.length; i++) {
code = header.charCodeAt(i);
if (extensionName === undefined) {
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (
i !== 0 &&
(code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
) {
if (end === -1 && start !== -1) end = i;
} else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
const name = header.slice(start, end);
if (code === 0x2c) {
push(offers, name, params);
params = Object.create(null);
} else {
extensionName = name;
}
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else if (paramName === undefined) {
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (code === 0x20 || code === 0x09) {
if (end === -1 && start !== -1) end = i;
} else if (code === 0x3b || code === 0x2c) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
push(params, header.slice(start, end), true);
if (code === 0x2c) {
push(offers, extensionName, params);
params = Object.create(null);
extensionName = undefined;
}
start = end = -1;
} else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
paramName = header.slice(start, i);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else {
//
// The value of a quoted-string after unescaping must conform to the
// token ABNF, so only token characters are valid.
// Ref: https://tools.ietf.org/html/rfc6455#section-9.1
//
if (isEscaping) {
if (tokenChars[code] !== 1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (start === -1) start = i;
else if (!mustUnescape) mustUnescape = true;
isEscaping = false;
} else if (inQuotes) {
if (tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (code === 0x22 /* '"' */ && start !== -1) {
inQuotes = false;
end = i;
} else if (code === 0x5c /* '\' */) {
isEscaping = true;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
inQuotes = true;
} else if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (start !== -1 && (code === 0x20 || code === 0x09)) {
if (end === -1) end = i;
} else if (code === 0x3b || code === 0x2c) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
let value = header.slice(start, end);
if (mustUnescape) {
value = value.replace(/\\/g, '');
mustUnescape = false;
}
push(params, paramName, value);
if (code === 0x2c) {
push(offers, extensionName, params);
params = Object.create(null);
extensionName = undefined;
}
paramName = undefined;
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
}
}
if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {
throw new SyntaxError('Unexpected end of input');
}
if (end === -1) end = i;
const token = header.slice(start, end);
if (extensionName === undefined) {
push(offers, token, params);
} else {
if (paramName === undefined) {
push(params, token, true);
} else if (mustUnescape) {
push(params, paramName, token.replace(/\\/g, ''));
} else {
push(params, paramName, token);
}
push(offers, extensionName, params);
}
return offers;
}
/**
* Builds the `Sec-WebSocket-Extensions` header field value.
*
* @param {Object} extensions The map of extensions and parameters to format
* @return {String} A string representing the given object
* @public
*/
function format(extensions) {
return Object.keys(extensions)
.map((extension) => {
let configurations = extensions[extension];
if (!Array.isArray(configurations)) configurations = [configurations];
return configurations
.map((params) => {
return [extension]
.concat(
Object.keys(params).map((k) => {
let values = params[k];
if (!Array.isArray(values)) values = [values];
return values
.map((v) => (v === true ? k : `${k}=${v}`))
.join('; ');
})
)
.join('; ');
})
.join(', ');
})
.join(', ');
}
module.exports = { format, parse };

View File

@@ -0,0 +1,5 @@
import type * as errors from "../core/errors.js";
/** @deprecated Use `km` instead. */
export default function (): {
localeError: errors.$ZodErrorMap;
};

View File

@@ -0,0 +1,89 @@
const nodeCrypto = require('crypto')
module.exports = {
postgresMd5PasswordHash,
randomBytes,
deriveKey,
sha256,
hashByName,
hmacSha256,
md5,
}
/**
* The Web Crypto API - grabbed from the Node.js library or the global
* @type Crypto
*/
// eslint-disable-next-line no-undef
const webCrypto = nodeCrypto.webcrypto || globalThis.crypto
/**
* The SubtleCrypto API for low level crypto operations.
* @type SubtleCrypto
*/
const subtleCrypto = webCrypto.subtle
const textEncoder = new TextEncoder()
/**
*
* @param {*} length
* @returns
*/
function randomBytes(length) {
return webCrypto.getRandomValues(Buffer.alloc(length))
}
async function md5(string) {
try {
return nodeCrypto.createHash('md5').update(string, 'utf-8').digest('hex')
} catch (e) {
// `createHash()` failed so we are probably not in Node.js, use the WebCrypto API instead.
// Note that the MD5 algorithm on WebCrypto is not available in Node.js.
// This is why we cannot just use WebCrypto in all environments.
const data = typeof string === 'string' ? textEncoder.encode(string) : string
const hash = await subtleCrypto.digest('MD5', data)
return Array.from(new Uint8Array(hash))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
}
}
// See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html
async function postgresMd5PasswordHash(user, password, salt) {
const inner = await md5(password + user)
const outer = await md5(Buffer.concat([Buffer.from(inner), salt]))
return 'md5' + outer
}
/**
* Create a SHA-256 digest of the given data
* @param {Buffer} data
*/
async function sha256(text) {
return await subtleCrypto.digest('SHA-256', text)
}
async function hashByName(hashName, text) {
return await subtleCrypto.digest(hashName, text)
}
/**
* Sign the message with the given key
* @param {ArrayBuffer} keyBuffer
* @param {string} msg
*/
async function hmacSha256(keyBuffer, msg) {
const key = await subtleCrypto.importKey('raw', keyBuffer, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
return await subtleCrypto.sign('HMAC', key, textEncoder.encode(msg))
}
/**
* Derive a key from the password and salt
* @param {string} password
* @param {Uint8Array} salt
* @param {number} iterations
*/
async function deriveKey(password, salt, iterations) {
const key = await subtleCrypto.importKey('raw', textEncoder.encode(password), 'PBKDF2', false, ['deriveBits'])
const params = { name: 'PBKDF2', hash: 'SHA-256', salt: salt, iterations: iterations }
return await subtleCrypto.deriveBits(params, key, 32 * 8, ['deriveBits'])
}

View File

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

View File

@@ -0,0 +1,130 @@
'use strict';
const FilterBase = require('./FilterBase');
const withParser = require('../utils/withParser');
class Filter extends FilterBase {
static make(options) {
return new Filter(options);
}
static withParser(options) {
return withParser(Filter.make, options);
}
constructor(options) {
super(options);
this._once = false;
this._lastStack = [];
}
_flush(callback) {
this._syncStack();
callback(null);
}
_checkChunk(chunk) {
switch (chunk.name) {
case 'startObject':
if (this._filter(this._stack, chunk)) {
this._syncStack();
this.push(chunk);
this._lastStack.push(null);
}
break;
case 'startArray':
if (this._filter(this._stack, chunk)) {
this._syncStack();
this.push(chunk);
this._lastStack.push(-1);
}
break;
case 'nullValue':
case 'trueValue':
case 'falseValue':
case 'stringValue':
case 'numberValue':
if (this._filter(this._stack, chunk)) {
this._syncStack();
this.push(chunk);
}
break;
case 'startString':
if (this._filter(this._stack, chunk)) {
this._syncStack();
this.push(chunk);
this._transform = this._passString;
} else {
this._transform = this._skipString;
}
break;
case 'startNumber':
if (this._filter(this._stack, chunk)) {
this._syncStack();
this.push(chunk);
this._transform = this._passNumber;
} else {
this._transform = this._skipNumber;
}
break;
}
return false;
}
_syncStack() {
const stack = this._stack,
last = this._lastStack,
stackLength = stack.length,
lastLength = last.length;
// find the common part
let commonLength = 0;
for (const n = Math.min(stackLength, lastLength); commonLength < n && stack[commonLength] === last[commonLength]; ++commonLength);
// close old objects
for (let i = lastLength - 1; i > commonLength; --i) {
this.push({name: typeof last[i] == 'number' ? 'endArray' : 'endObject'});
}
if (commonLength < lastLength) {
if (commonLength < stackLength) {
if (typeof stack[commonLength] == 'string') {
const key = stack[commonLength];
if (this._streamKeys) {
this.push({name: 'startKey'});
this.push({name: 'stringChunk', value: key});
this.push({name: 'endKey'});
}
this.push({name: 'keyValue', value: key});
}
++commonLength;
} else {
this.push({name: typeof last[commonLength] == 'number' ? 'endArray' : 'endObject'});
}
}
// open new objects
for (let i = commonLength; i < stackLength; ++i) {
const key = stack[i];
if (typeof key == 'number') {
if (key >= 0) {
this.push({name: 'startArray'});
}
} else if (typeof key == 'string') {
this.push({name: 'startObject'});
if (this._streamKeys) {
this.push({name: 'startKey'});
this.push({name: 'stringChunk', value: key});
this.push({name: 'endKey'});
}
this.push({name: 'keyValue', value: key});
}
}
// update the last stack
this._lastStack = Array.prototype.concat.call(stack);
}
}
Filter.filter = Filter.make;
Filter.make.Constructor = Filter;
module.exports = Filter;

View File

@@ -0,0 +1,14 @@
type ModeWriter = (doc: Doc, modes: {
execution: "sync" | "async";
}) => void;
export declare class Doc {
args: string[];
content: string[];
indent: number;
constructor(args?: string[]);
indented(fn: (doc: Doc) => void): void;
write(fn: ModeWriter): void;
write(line: string): void;
compile(): any;
}
export {};

View File

@@ -0,0 +1,110 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
test("object intersection", () => {
const BaseTeacher = z.object({
subjects: z.array(z.string()),
});
const HasID = z.object({ id: z.string() });
const Teacher = z.intersection(BaseTeacher.passthrough(), HasID); // BaseTeacher.merge(HasID);
const data = {
subjects: ["math"],
id: "asdfasdf",
};
expect(Teacher.parse(data)).toEqual(data);
expect(() => Teacher.parse({ subject: data.subjects })).toThrow();
expect(Teacher.parse({ ...data, extra: 12 })).toEqual({ ...data, extra: 12 });
expect(() => z.intersection(BaseTeacher.strict(), HasID).parse({ ...data, extra: 12 })).toThrow();
});
test("deep intersection", () => {
const Animal = z.object({
properties: z.object({
is_animal: z.boolean(),
}),
});
const Cat = z
.object({
properties: z.object({
jumped: z.boolean(),
}),
})
.and(Animal);
type _Cat = z.infer<typeof Cat>;
// const cat:Cat = 'asdf' as any;
const cat = Cat.parse({ properties: { is_animal: true, jumped: true } });
expect(cat.properties).toEqual({ is_animal: true, jumped: true });
});
test("deep intersection of arrays", async () => {
const Author = z.object({
posts: z.array(
z.object({
post_id: z.number(),
})
),
});
const Registry = z
.object({
posts: z.array(
z.object({
title: z.string(),
})
),
})
.and(Author);
const posts = [
{ post_id: 1, title: "Novels" },
{ post_id: 2, title: "Fairy tales" },
];
const cat = Registry.parse({ posts });
expect(cat.posts).toEqual(posts);
const asyncCat = await Registry.parseAsync({ posts });
expect(asyncCat.posts).toEqual(posts);
});
test("invalid intersection types", async () => {
const numberIntersection = z.intersection(
z.number(),
z.number().transform((x) => x + 1)
);
const syncResult = numberIntersection.safeParse(1234);
expect(syncResult.success).toEqual(false);
if (!syncResult.success) {
expect(syncResult.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_intersection_types);
}
const asyncResult = await numberIntersection.spa(1234);
expect(asyncResult.success).toEqual(false);
if (!asyncResult.success) {
expect(asyncResult.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_intersection_types);
}
});
test("invalid array merge", async () => {
const stringArrInt = z.intersection(
z.string().array(),
z
.string()
.array()
.transform((val) => [...val, "asdf"])
);
const syncResult = stringArrInt.safeParse(["asdf", "qwer"]);
expect(syncResult.success).toEqual(false);
if (!syncResult.success) {
expect(syncResult.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_intersection_types);
}
const asyncResult = await stringArrInt.spa(["asdf", "qwer"]);
expect(asyncResult.success).toEqual(false);
if (!asyncResult.success) {
expect(asyncResult.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_intersection_types);
}
});

View File

@@ -0,0 +1,107 @@
{
"name": "ajv",
"version": "6.15.0",
"description": "Another JSON Schema Validator",
"main": "lib/ajv.js",
"typings": "lib/ajv.d.ts",
"files": [
"lib/",
"dist/",
"scripts/",
"LICENSE",
".tonic_example.js"
],
"scripts": {
"eslint": "eslint lib/{compile/,}*.js spec/{**/,}*.js scripts --ignore-pattern spec/JSON-Schema-Test-Suite",
"jshint": "jshint lib/{compile/,}*.js",
"lint": "npm run jshint && npm run eslint",
"test-spec": "mocha spec/{**/,}*.spec.js -R spec",
"test-fast": "AJV_FAST_TEST=true npm run test-spec",
"test-debug": "npm run test-spec -- --inspect-brk",
"test-cov": "nyc npm run test-spec",
"test-ts": "tsc --target ES5 --noImplicitAny --noEmit spec/typescript/index.ts",
"bundle": "del-cli dist && node ./scripts/bundle.js . Ajv pure_getters",
"bundle-beautify": "node ./scripts/bundle.js js-beautify",
"build": "del-cli lib/dotjs/*.js \"!lib/dotjs/index.js\" && node scripts/compile-dots.js",
"test-karma": "karma start",
"test-browser": "del-cli .browser && npm run bundle && scripts/prepare-tests && npm run test-karma",
"test-all": "npm run test-cov && if-node-version 10 npm run test-browser",
"test": "npm run lint && npm run build && npm run test-all",
"prepublish": "npm run build && npm run bundle",
"watch": "watch \"npm run build\" ./lib/dot"
},
"nyc": {
"exclude": [
"**/spec/**",
"node_modules"
],
"reporter": [
"lcov",
"text-summary"
]
},
"repository": {
"type": "git",
"url": "https://github.com/ajv-validator/ajv.git"
},
"keywords": [
"JSON",
"schema",
"validator",
"validation",
"jsonschema",
"json-schema",
"json-schema-validator",
"json-schema-validation"
],
"author": "Evgeny Poberezkin",
"license": "MIT",
"bugs": {
"url": "https://github.com/ajv-validator/ajv/issues"
},
"homepage": "https://github.com/ajv-validator/ajv",
"tonicExampleFilename": ".tonic_example.js",
"dependencies": {
"fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0",
"json-schema-traverse": "^0.4.1",
"uri-js": "^4.2.2"
},
"devDependencies": {
"ajv-async": "^1.0.0",
"bluebird": "^3.5.3",
"brfs": "^2.0.0",
"browserify": "^16.2.0",
"chai": "^4.0.1",
"coveralls": "^3.0.1",
"del-cli": "^3.0.0",
"dot": "^1.0.3",
"eslint": "^7.3.1",
"gh-pages-generator": "^0.2.3",
"glob": "^7.0.0",
"if-node-version": "^1.0.0",
"js-beautify": "^1.7.3",
"jshint": "^2.10.2",
"json-schema-test": "^2.0.0",
"karma": "^5.0.0",
"karma-chrome-launcher": "^3.0.0",
"karma-mocha": "^2.0.0",
"karma-sauce-launcher": "^4.1.3",
"mocha": "^8.0.1",
"nyc": "^15.0.0",
"pre-commit": "^1.1.1",
"re2": "^1.21.4",
"require-globify": "^1.3.0",
"typescript": "^3.9.5",
"uglify-js": "^3.6.9",
"watch": "^1.0.0"
},
"collective": {
"type": "opencollective",
"url": "https://opencollective.com/ajv"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/epoberezkin"
}
}

View File

@@ -0,0 +1,75 @@
import { Codec, Decoder, Encoder, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder, VariableSizeCodec, VariableSizeDecoder, VariableSizeEncoder } from './codec';
/**
* Combines an `Encoder` and a `Decoder` into a `Codec`.
*
* That is, given a `Encoder<TFrom>` and a `Decoder<TTo>`, this function returns a `Codec<TFrom, TTo>`.
*
* This allows for modular composition by keeping encoding and decoding logic separate
* while still offering a convenient way to bundle them into a single `Codec`.
* This is particularly useful for library maintainers who want to expose `Encoders`,
* `Decoders`, and `Codecs` separately, enabling tree-shaking of unused logic.
*
* The provided `Encoder` and `Decoder` must be compatible in terms of:
* - **Fixed Size:** If both are fixed-size, they must have the same `fixedSize` value.
* - **Variable Size:** If either has a `maxSize` attribute, it must match the other.
*
* If these conditions are not met, a {@link SolanaError} will be thrown.
*
* @typeParam TFrom - The type of the value to encode.
* @typeParam TTo - The type of the decoded value.
* @typeParam TSize - The fixed size of the encoded value in bytes (for fixed-size codecs).
*
* @param encoder - The `Encoder` to combine.
* @param decoder - The `Decoder` to combine.
* @returns A `Codec` that provides both `encode` and `decode` methods.
*
* @throws {SolanaError}
* - `SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH`
* Thrown if the encoder and decoder have mismatched size types (fixed vs. variable).
* - `SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH`
* Thrown if both are fixed-size but have different `fixedSize` values.
* - `SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH`
* Thrown if the `maxSize` attributes do not match.
*
* @example
* Creating a fixed-size `Codec` from an encoder and a decoder.
* ```ts
* const encoder = getU32Encoder();
* const decoder = getU32Decoder();
* const codec = combineCodec(encoder, decoder);
*
* const bytes = codec.encode(42); // 0x2a000000
* const value = codec.decode(bytes); // 42
* ```
*
* @example
* Creating a variable-size `Codec` from an encoder and a decoder.
* ```ts
* const encoder = addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());
* const decoder = addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder());
* const codec = combineCodec(encoder, decoder);
*
* const bytes = codec.encode("hello"); // 0x0500000068656c6c6f
* const value = codec.decode(bytes); // "hello"
* ```
*
* @remarks
* The recommended pattern for defining codecs in libraries is to expose separate functions for the encoder, decoder, and codec.
* This allows users to import only what they need, improving tree-shaking efficiency.
*
* ```ts
* type MyType = \/* ... *\/;
* const getMyTypeEncoder = (): Encoder<MyType> => { \/* ... *\/ };
* const getMyTypeDecoder = (): Decoder<MyType> => { \/* ... *\/ };
* const getMyTypeCodec = (): Codec<MyType> =>
* combineCodec(getMyTypeEncoder(), getMyTypeDecoder());
* ```
*
* @see {@link Codec}
* @see {@link Encoder}
* @see {@link Decoder}
*/
export declare function combineCodec<TFrom, TTo extends TFrom, TSize extends number>(encoder: FixedSizeEncoder<TFrom, TSize>, decoder: FixedSizeDecoder<TTo, TSize>): FixedSizeCodec<TFrom, TTo, TSize>;
export declare function combineCodec<TFrom, TTo extends TFrom>(encoder: VariableSizeEncoder<TFrom>, decoder: VariableSizeDecoder<TTo>): VariableSizeCodec<TFrom, TTo>;
export declare function combineCodec<TFrom, TTo extends TFrom>(encoder: Encoder<TFrom>, decoder: Decoder<TTo>): Codec<TFrom, TTo>;
//# sourceMappingURL=combine-codec.d.ts.map

View File

@@ -0,0 +1,8 @@
import type { TSESTree } from '@typescript-eslint/types';
import type { ScopeManager } from '../ScopeManager';
import type { Scope } from './Scope';
import { ScopeBase } from './ScopeBase';
import { ScopeType } from './ScopeType';
export declare class SwitchScope extends ScopeBase<ScopeType.switch, TSESTree.SwitchStatement, Scope> {
constructor(scopeManager: ScopeManager, upperScope: SwitchScope['upper'], block: SwitchScope['block']);
}

View File

@@ -0,0 +1,150 @@
'use strict';
module.exports = function generate_format(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
if (it.opts.format === false) {
if ($breakOnError) {
out += ' if (true) { ';
}
return out;
}
var $isData = it.opts.$data && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $unknownFormats = it.opts.unknownFormats,
$allowUnknown = Array.isArray($unknownFormats);
if ($isData) {
var $format = 'format' + $lvl,
$isObject = 'isObject' + $lvl,
$formatType = 'formatType' + $lvl;
out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { ';
if (it.async) {
out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
}
out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
}
out += ' (';
if ($unknownFormats != 'ignore') {
out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
if ($allowUnknown) {
out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
}
out += ') || ';
}
out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? ';
if (it.async) {
out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
} else {
out += ' ' + ($format) + '(' + ($data) + ') ';
}
out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
} else {
var $format = it.formats[$schema];
if (!$format) {
if ($unknownFormats == 'ignore') {
it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
if ($breakOnError) {
out += ' if (true) { ';
}
return out;
} else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
if ($breakOnError) {
out += ' if (true) { ';
}
return out;
} else {
throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
}
}
var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
var $formatType = $isObject && $format.type || 'string';
if ($isObject) {
var $async = $format.async === true;
$format = $format.validate;
}
if ($formatType != $ruleType) {
if ($breakOnError) {
out += ' if (true) { ';
}
return out;
}
if ($async) {
if (!it.async) throw new Error('async format in sync schema');
var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { ';
} else {
out += ' if (! ';
var $formatRef = 'formats' + it.util.getProperty($schema);
if ($isObject) $formatRef += '.validate';
if (typeof $format == 'function') {
out += ' ' + ($formatRef) + '(' + ($data) + ') ';
} else {
out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
}
out += ') { ';
}
}
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: ';
if ($isData) {
out += '' + ($schemaValue);
} else {
out += '' + (it.util.toQuotedString($schema));
}
out += ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should match format "';
if ($isData) {
out += '\' + ' + ($schemaValue) + ' + \'';
} else {
out += '' + (it.util.escapeQuotes($schema));
}
out += '"\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + (it.util.toQuotedString($schema));
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
if ($breakOnError) {
out += ' else { ';
}
return out;
}

View File

@@ -0,0 +1,40 @@
declare const _default: {
extends: string[];
rules: {
'@typescript-eslint/ban-ts-comment': ["error", {
minimumDescriptionLength: number;
}];
'no-array-constructor': "off";
'@typescript-eslint/no-array-constructor': "error";
'@typescript-eslint/no-duplicate-enum-values': "error";
'@typescript-eslint/no-dynamic-delete': "error";
'@typescript-eslint/no-empty-object-type': "error";
'@typescript-eslint/no-explicit-any': "error";
'@typescript-eslint/no-extra-non-null-assertion': "error";
'@typescript-eslint/no-extraneous-class': "error";
'@typescript-eslint/no-invalid-void-type': "error";
'@typescript-eslint/no-misused-new': "error";
'@typescript-eslint/no-namespace': "error";
'@typescript-eslint/no-non-null-asserted-nullish-coalescing': "error";
'@typescript-eslint/no-non-null-asserted-optional-chain': "error";
'@typescript-eslint/no-non-null-assertion': "error";
'@typescript-eslint/no-require-imports': "error";
'@typescript-eslint/no-this-alias': "error";
'@typescript-eslint/no-unnecessary-type-constraint': "error";
'@typescript-eslint/no-unsafe-declaration-merging': "error";
'@typescript-eslint/no-unsafe-function-type': "error";
'no-unused-expressions': "off";
'@typescript-eslint/no-unused-expressions': "error";
'no-unused-vars': "off";
'@typescript-eslint/no-unused-vars': "error";
'no-useless-constructor': "off";
'@typescript-eslint/no-useless-constructor': "error";
'@typescript-eslint/no-wrapper-object-types': "error";
'@typescript-eslint/prefer-as-const': "error";
'@typescript-eslint/prefer-literal-enum-member': "error";
'@typescript-eslint/prefer-namespace-keyword': "error";
'@typescript-eslint/triple-slash-reference': "error";
'@typescript-eslint/unified-signatures': "error";
};
};
export = _default;

View File

@@ -0,0 +1,264 @@
# @jridgewell/sourcemap-codec
Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit).
## Why?
Sourcemaps are difficult to generate and manipulate, because the `mappings` property the part that actually links the generated code back to the original source is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation you have to understand the whole sourcemap.
This package makes the process slightly easier.
## Installation
```bash
npm install @jridgewell/sourcemap-codec
```
## Usage
```js
import { encode, decode } from '@jridgewell/sourcemap-codec';
var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' );
assert.deepEqual( decoded, [
// the first line (of the generated code) has no mappings,
// as shown by the starting semi-colon (which separates lines)
[],
// the second line contains four (comma-separated) segments
[
// segments are encoded as you'd expect:
// [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ]
// i.e. the first segment begins at column 2, and maps back to the second column
// of the second line (both zero-based) of the 0th source, and uses the 0th
// name in the `map.names` array
[ 2, 0, 2, 2, 0 ],
// the remaining segments are 4-length rather than 5-length,
// because they don't map a name
[ 4, 0, 2, 4 ],
[ 6, 0, 2, 5 ],
[ 7, 0, 2, 7 ]
],
// the final line contains two segments
[
[ 2, 1, 10, 19 ],
[ 12, 1, 11, 20 ]
]
]);
var encoded = encode( decoded );
assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' );
```
## Benchmarks
```
node v20.10.0
amp.js.map - 45120 segments
Decode Memory Usage:
local code 5815135 bytes
@jridgewell/sourcemap-codec 1.4.15 5868160 bytes
sourcemap-codec 5492584 bytes
source-map-0.6.1 13569984 bytes
source-map-0.8.0 6390584 bytes
chrome dev tools 8011136 bytes
Smallest memory usage is sourcemap-codec
Decode speed:
decode: local code x 492 ops/sec ±1.22% (90 runs sampled)
decode: @jridgewell/sourcemap-codec 1.4.15 x 499 ops/sec ±1.16% (89 runs sampled)
decode: sourcemap-codec x 376 ops/sec ±1.66% (89 runs sampled)
decode: source-map-0.6.1 x 34.99 ops/sec ±0.94% (48 runs sampled)
decode: source-map-0.8.0 x 351 ops/sec ±0.07% (95 runs sampled)
chrome dev tools x 165 ops/sec ±0.91% (86 runs sampled)
Fastest is decode: @jridgewell/sourcemap-codec 1.4.15
Encode Memory Usage:
local code 444248 bytes
@jridgewell/sourcemap-codec 1.4.15 623024 bytes
sourcemap-codec 8696280 bytes
source-map-0.6.1 8745176 bytes
source-map-0.8.0 8736624 bytes
Smallest memory usage is local code
Encode speed:
encode: local code x 796 ops/sec ±0.11% (97 runs sampled)
encode: @jridgewell/sourcemap-codec 1.4.15 x 795 ops/sec ±0.25% (98 runs sampled)
encode: sourcemap-codec x 231 ops/sec ±0.83% (86 runs sampled)
encode: source-map-0.6.1 x 166 ops/sec ±0.57% (86 runs sampled)
encode: source-map-0.8.0 x 203 ops/sec ±0.45% (88 runs sampled)
Fastest is encode: local code,encode: @jridgewell/sourcemap-codec 1.4.15
***
babel.min.js.map - 347793 segments
Decode Memory Usage:
local code 35424960 bytes
@jridgewell/sourcemap-codec 1.4.15 35424696 bytes
sourcemap-codec 36033464 bytes
source-map-0.6.1 62253704 bytes
source-map-0.8.0 43843920 bytes
chrome dev tools 45111400 bytes
Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15
Decode speed:
decode: local code x 38.18 ops/sec ±5.44% (52 runs sampled)
decode: @jridgewell/sourcemap-codec 1.4.15 x 38.36 ops/sec ±5.02% (52 runs sampled)
decode: sourcemap-codec x 34.05 ops/sec ±4.45% (47 runs sampled)
decode: source-map-0.6.1 x 4.31 ops/sec ±2.76% (15 runs sampled)
decode: source-map-0.8.0 x 55.60 ops/sec ±0.13% (73 runs sampled)
chrome dev tools x 16.94 ops/sec ±3.78% (46 runs sampled)
Fastest is decode: source-map-0.8.0
Encode Memory Usage:
local code 2606016 bytes
@jridgewell/sourcemap-codec 1.4.15 2626440 bytes
sourcemap-codec 21152576 bytes
source-map-0.6.1 25023928 bytes
source-map-0.8.0 25256448 bytes
Smallest memory usage is local code
Encode speed:
encode: local code x 127 ops/sec ±0.18% (83 runs sampled)
encode: @jridgewell/sourcemap-codec 1.4.15 x 128 ops/sec ±0.26% (83 runs sampled)
encode: sourcemap-codec x 29.31 ops/sec ±2.55% (53 runs sampled)
encode: source-map-0.6.1 x 18.85 ops/sec ±3.19% (36 runs sampled)
encode: source-map-0.8.0 x 19.34 ops/sec ±1.97% (36 runs sampled)
Fastest is encode: @jridgewell/sourcemap-codec 1.4.15
***
preact.js.map - 1992 segments
Decode Memory Usage:
local code 261696 bytes
@jridgewell/sourcemap-codec 1.4.15 244296 bytes
sourcemap-codec 302816 bytes
source-map-0.6.1 939176 bytes
source-map-0.8.0 336 bytes
chrome dev tools 587368 bytes
Smallest memory usage is source-map-0.8.0
Decode speed:
decode: local code x 17,782 ops/sec ±0.32% (97 runs sampled)
decode: @jridgewell/sourcemap-codec 1.4.15 x 17,863 ops/sec ±0.40% (100 runs sampled)
decode: sourcemap-codec x 12,453 ops/sec ±0.27% (101 runs sampled)
decode: source-map-0.6.1 x 1,288 ops/sec ±1.05% (96 runs sampled)
decode: source-map-0.8.0 x 9,289 ops/sec ±0.27% (101 runs sampled)
chrome dev tools x 4,769 ops/sec ±0.18% (100 runs sampled)
Fastest is decode: @jridgewell/sourcemap-codec 1.4.15
Encode Memory Usage:
local code 262944 bytes
@jridgewell/sourcemap-codec 1.4.15 25544 bytes
sourcemap-codec 323048 bytes
source-map-0.6.1 507808 bytes
source-map-0.8.0 507480 bytes
Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15
Encode speed:
encode: local code x 24,207 ops/sec ±0.79% (95 runs sampled)
encode: @jridgewell/sourcemap-codec 1.4.15 x 24,288 ops/sec ±0.48% (96 runs sampled)
encode: sourcemap-codec x 6,761 ops/sec ±0.21% (100 runs sampled)
encode: source-map-0.6.1 x 5,374 ops/sec ±0.17% (99 runs sampled)
encode: source-map-0.8.0 x 5,633 ops/sec ±0.32% (99 runs sampled)
Fastest is encode: @jridgewell/sourcemap-codec 1.4.15,encode: local code
***
react.js.map - 5726 segments
Decode Memory Usage:
local code 678816 bytes
@jridgewell/sourcemap-codec 1.4.15 678816 bytes
sourcemap-codec 816400 bytes
source-map-0.6.1 2288864 bytes
source-map-0.8.0 721360 bytes
chrome dev tools 1012512 bytes
Smallest memory usage is local code
Decode speed:
decode: local code x 6,178 ops/sec ±0.19% (98 runs sampled)
decode: @jridgewell/sourcemap-codec 1.4.15 x 6,261 ops/sec ±0.22% (100 runs sampled)
decode: sourcemap-codec x 4,472 ops/sec ±0.90% (99 runs sampled)
decode: source-map-0.6.1 x 449 ops/sec ±0.31% (95 runs sampled)
decode: source-map-0.8.0 x 3,219 ops/sec ±0.13% (100 runs sampled)
chrome dev tools x 1,743 ops/sec ±0.20% (99 runs sampled)
Fastest is decode: @jridgewell/sourcemap-codec 1.4.15
Encode Memory Usage:
local code 140960 bytes
@jridgewell/sourcemap-codec 1.4.15 159808 bytes
sourcemap-codec 969304 bytes
source-map-0.6.1 930520 bytes
source-map-0.8.0 930248 bytes
Smallest memory usage is local code
Encode speed:
encode: local code x 8,013 ops/sec ±0.19% (100 runs sampled)
encode: @jridgewell/sourcemap-codec 1.4.15 x 7,989 ops/sec ±0.20% (101 runs sampled)
encode: sourcemap-codec x 2,472 ops/sec ±0.21% (99 runs sampled)
encode: source-map-0.6.1 x 2,200 ops/sec ±0.17% (99 runs sampled)
encode: source-map-0.8.0 x 2,220 ops/sec ±0.37% (99 runs sampled)
Fastest is encode: local code
***
vscode.map - 2141001 segments
Decode Memory Usage:
local code 198955264 bytes
@jridgewell/sourcemap-codec 1.4.15 199175352 bytes
sourcemap-codec 199102688 bytes
source-map-0.6.1 386323432 bytes
source-map-0.8.0 244116432 bytes
chrome dev tools 293734280 bytes
Smallest memory usage is local code
Decode speed:
decode: local code x 3.90 ops/sec ±22.21% (15 runs sampled)
decode: @jridgewell/sourcemap-codec 1.4.15 x 3.95 ops/sec ±23.53% (15 runs sampled)
decode: sourcemap-codec x 3.82 ops/sec ±17.94% (14 runs sampled)
decode: source-map-0.6.1 x 0.61 ops/sec ±7.81% (6 runs sampled)
decode: source-map-0.8.0 x 9.54 ops/sec ±0.28% (28 runs sampled)
chrome dev tools x 2.18 ops/sec ±10.58% (10 runs sampled)
Fastest is decode: source-map-0.8.0
Encode Memory Usage:
local code 13509880 bytes
@jridgewell/sourcemap-codec 1.4.15 13537648 bytes
sourcemap-codec 32540104 bytes
source-map-0.6.1 127531040 bytes
source-map-0.8.0 127535312 bytes
Smallest memory usage is local code
Encode speed:
encode: local code x 20.10 ops/sec ±0.19% (38 runs sampled)
encode: @jridgewell/sourcemap-codec 1.4.15 x 20.26 ops/sec ±0.32% (38 runs sampled)
encode: sourcemap-codec x 5.44 ops/sec ±1.64% (18 runs sampled)
encode: source-map-0.6.1 x 2.30 ops/sec ±4.79% (10 runs sampled)
encode: source-map-0.8.0 x 2.46 ops/sec ±6.53% (10 runs sampled)
Fastest is encode: @jridgewell/sourcemap-codec 1.4.15
```
# License
MIT