WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = default_1;
|
||||
const util = __importStar(require("../core/util.cjs"));
|
||||
const error = () => {
|
||||
const Sizable = {
|
||||
string: { unit: "aksara", verb: "mempunyai" },
|
||||
file: { unit: "bait", verb: "mempunyai" },
|
||||
array: { unit: "elemen", verb: "mempunyai" },
|
||||
set: { unit: "elemen", verb: "mempunyai" },
|
||||
};
|
||||
function getSizing(origin) {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
const FormatDictionary = {
|
||||
regex: "input",
|
||||
email: "alamat e-mel",
|
||||
url: "URL",
|
||||
emoji: "emoji",
|
||||
uuid: "UUID",
|
||||
uuidv4: "UUIDv4",
|
||||
uuidv6: "UUIDv6",
|
||||
nanoid: "nanoid",
|
||||
guid: "GUID",
|
||||
cuid: "cuid",
|
||||
cuid2: "cuid2",
|
||||
ulid: "ULID",
|
||||
xid: "XID",
|
||||
ksuid: "KSUID",
|
||||
datetime: "tarikh masa ISO",
|
||||
date: "tarikh ISO",
|
||||
time: "masa ISO",
|
||||
duration: "tempoh ISO",
|
||||
ipv4: "alamat IPv4",
|
||||
ipv6: "alamat IPv6",
|
||||
cidrv4: "julat IPv4",
|
||||
cidrv6: "julat IPv6",
|
||||
base64: "string dikodkan base64",
|
||||
base64url: "string dikodkan base64url",
|
||||
json_string: "string JSON",
|
||||
e164: "nombor E.164",
|
||||
jwt: "JWT",
|
||||
template_literal: "input",
|
||||
};
|
||||
const TypeDictionary = {
|
||||
nan: "NaN",
|
||||
number: "nombor",
|
||||
};
|
||||
return (issue) => {
|
||||
switch (issue.code) {
|
||||
case "invalid_type": {
|
||||
const expected = TypeDictionary[issue.expected] ?? issue.expected;
|
||||
const receivedType = util.parsedType(issue.input);
|
||||
const received = TypeDictionary[receivedType] ?? receivedType;
|
||||
if (/^[A-Z]/.test(issue.expected)) {
|
||||
return `Input tidak sah: dijangka instanceof ${issue.expected}, diterima ${received}`;
|
||||
}
|
||||
return `Input tidak sah: dijangka ${expected}, diterima ${received}`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1)
|
||||
return `Input tidak sah: dijangka ${util.stringifyPrimitive(issue.values[0])}`;
|
||||
return `Pilihan tidak sah: dijangka salah satu daripada ${util.joinValues(issue.values, "|")}`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing)
|
||||
return `Terlalu besar: dijangka ${issue.origin ?? "nilai"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elemen"}`;
|
||||
return `Terlalu besar: dijangka ${issue.origin ?? "nilai"} adalah ${adj}${issue.maximum.toString()}`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
return `Terlalu kecil: dijangka ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;
|
||||
}
|
||||
return `Terlalu kecil: dijangka ${issue.origin} adalah ${adj}${issue.minimum.toString()}`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue;
|
||||
if (_issue.format === "starts_with")
|
||||
return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`;
|
||||
if (_issue.format === "ends_with")
|
||||
return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;
|
||||
if (_issue.format === "includes")
|
||||
return `String tidak sah: mesti mengandungi "${_issue.includes}"`;
|
||||
if (_issue.format === "regex")
|
||||
return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;
|
||||
return `${FormatDictionary[_issue.format] ?? issue.format} tidak sah`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `Nombor tidak sah: perlu gandaan ${issue.divisor}`;
|
||||
case "unrecognized_keys":
|
||||
return `Kunci tidak dikenali: ${util.joinValues(issue.keys, ", ")}`;
|
||||
case "invalid_key":
|
||||
return `Kunci tidak sah dalam ${issue.origin}`;
|
||||
case "invalid_union":
|
||||
return "Input tidak sah";
|
||||
case "invalid_element":
|
||||
return `Nilai tidak sah dalam ${issue.origin}`;
|
||||
default:
|
||||
return `Input tidak sah`;
|
||||
}
|
||||
};
|
||||
};
|
||||
function default_1() {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
module.exports = exports.default;
|
||||
@@ -0,0 +1,153 @@
|
||||
# sonic-boom
|
||||
|
||||
[](https://www.npmjs.com/package/sonic-boom)
|
||||
[](https://github.com/pinojs/sonic-boom/actions?query=workflow%3ACI)
|
||||
[](https://standardjs.com/)
|
||||
|
||||
Extremely fast utf8-only stream implementation to write to files and
|
||||
file descriptors.
|
||||
|
||||
This implementation is partial, but support backpressure and `.pipe()` in is here.
|
||||
However, it is 2-3x faster than Node Core `fs.createWriteStream()`:
|
||||
|
||||
```
|
||||
benchSonic*1000: 1916.904ms
|
||||
benchSonicSync*1000: 8605.265ms
|
||||
benchSonic4k*1000: 1965.231ms
|
||||
benchSonicSync4k*1000: 1588.224ms
|
||||
benchCore*1000: 5851.959ms
|
||||
benchConsole*1000: 7605.713ms
|
||||
```
|
||||
|
||||
Note that sync mode without buffering is _slower_ than a Node Core WritableStream, however
|
||||
this mode matches the expected behavior of `console.log()`.
|
||||
|
||||
Note that if this is used to log to a windows terminal (`cmd.exe` or
|
||||
powershell), it is needed to run `chcp 65001` in the terminal to
|
||||
correctly display utf-8 characters, see
|
||||
[chcp](https://ss64.com/nt/chcp.html) for more details.
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
npm i sonic-boom
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
```js
|
||||
'use strict'
|
||||
|
||||
const SonicBoom = require('sonic-boom')
|
||||
const sonic = new SonicBoom({ fd: process.stdout.fd }) // or { dest: '/path/to/destination' }
|
||||
|
||||
for (let i = 0; i < 10; i++) {
|
||||
sonic.write('hello sonic\n')
|
||||
}
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### SonicBoom(opts)
|
||||
|
||||
Creates a new instance of SonicBoom.
|
||||
|
||||
The options are:
|
||||
|
||||
* `fd`: a file descriptor, something that is returned by `fs.open` or
|
||||
`fs.openSync`.
|
||||
* `dest`: a string that is a path to a file to be written to (mode controlled by the `append` option).
|
||||
* `minLength`: the minimum length of the internal buffer that is
|
||||
required to be full before flushing.
|
||||
* `maxLength`: the maximum length of the internal buffer. If a write operation would cause the buffer
|
||||
to exceed `maxLength`, the data written is dropped and a `drop` event is emitted with the dropped data
|
||||
* `maxWrite`: the maximum number of bytes that can be written; default: 16384
|
||||
* `periodicFlush`: calls `flush` every x`ms`.
|
||||
* `sync`: perform writes synchronously (similar to `console.log`).
|
||||
* `fsync`: perform a [fsyncSync](https://nodejs.org/api/fs.html#fsfsyncsyncfd) every time a write is completed.
|
||||
* `append`: appends writes to dest file instead of truncating it (default `true`).
|
||||
* `mode`: specify the creating file `mode` (see [fs.open()](https://nodejs.org/api/fs.html#fsopenpath-flags-mode-callback) from Node.js core).
|
||||
* `contentMode`: which type of data you can send to the `write` function, supported values are `utf8` or `buffer`. (default `utf8`)
|
||||
* `mkdir`: ensure directory for dest file exists when `true` (default `false`).
|
||||
* `retryEAGAIN(err, writeBufferLen, remainingBufferLen)`: a function that will be called when sonic-boom
|
||||
write/writeSync/flushSync encounters a EAGAIN or EBUSY error. If the return value is
|
||||
true sonic-boom will retry the operation, otherwise it will bubble the
|
||||
error. `err` is the error that caused this function to be called,
|
||||
`writeBufferLen` is the length of the buffer sonic-boom tried to write, and
|
||||
`remainingBufferLen` is the length of the remaining buffer sonic-boom didn't try to write.
|
||||
|
||||
For `sync:false` a `SonicBoom` instance will emit the `'ready'` event when a file descriptor is available.
|
||||
For `sync:true` this is not relevant because the `'ready'` event will be fired when the `SonicBoom` instance is created, before it can be subscribed to.
|
||||
|
||||
|
||||
### SonicBoom#write(string)
|
||||
|
||||
Writes the string to the file.
|
||||
It will return false to signal the producer to slow down.
|
||||
|
||||
### SonicBoom#flush([cb])
|
||||
|
||||
Writes the current buffer to the file if a write was not in progress.
|
||||
Do nothing if `minLength` is zero or if it is already writing.
|
||||
|
||||
call the callback when the flush operation is completed. when failed the callback is called with an error.
|
||||
|
||||
### SonicBoom#reopen([file])
|
||||
|
||||
Reopen the file in place, useful for log rotation.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
const stream = new SonicBoom('./my.log')
|
||||
process.on('SIGUSR2', function () {
|
||||
stream.reopen()
|
||||
})
|
||||
```
|
||||
|
||||
### SonicBoom#flushSync()
|
||||
|
||||
Flushes the buffered data synchronously. This is a costly operation.
|
||||
|
||||
### SonicBoom#end()
|
||||
|
||||
Closes the stream, the data will be flushed down asynchronously
|
||||
|
||||
### SonicBoom#destroy()
|
||||
|
||||
Closes the stream immediately, the data is not flushed.
|
||||
|
||||
### Events
|
||||
|
||||
|
||||
#### SonicBoom#close
|
||||
|
||||
See [Stream#close](https://nodejs.org/api/stream.html#event-close). The `'close'` event when the instance has been closed.
|
||||
|
||||
#### SonicBoom#drain
|
||||
|
||||
See [Stream#drain](https://nodejs.org/api/stream.html#event-drain). The `'drain'` event is emitted when source can resume sending data.
|
||||
|
||||
#### SonicBoom#drop <any>
|
||||
|
||||
When destination file maximal length is reached, the `'drop'` event is emitted with data that could not be written.
|
||||
|
||||
#### SonicBoom#error <Error>
|
||||
|
||||
The `'error'` event is emitted when the destination file can not be opened, or written.
|
||||
|
||||
#### SonicBoom#finish
|
||||
|
||||
See [Stream#finish](https://nodejs.org/api/stream.html#event-finish). The `'finish'` event after calling `end()` method and when all data was written.
|
||||
|
||||
#### SonicBoom#ready
|
||||
|
||||
The `'ready'` event occurs when the created instance is ready to process input.
|
||||
|
||||
#### SonicBoom#write <number>
|
||||
|
||||
The `'write'` event occurs every time data is written to the underlying file. It emits the number of written bytes.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -0,0 +1,310 @@
|
||||
import type { CompletionItemKind } from "#enums/completionItemKind";
|
||||
import type { DiagnosticCategory } from "#enums/diagnosticCategory";
|
||||
import type { ElementFlags } from "#enums/elementFlags";
|
||||
import type { ObjectFlags } from "#enums/objectFlags";
|
||||
import type { TypeFlags } from "#enums/typeFlags";
|
||||
import type { TypePredicateKind } from "#enums/typePredicateKind";
|
||||
import type { NodeHandle, Symbol } from "./api.ts";
|
||||
/**
|
||||
* A TypeScript type.
|
||||
*
|
||||
* Use TypeFlags to determine the specific kind of type and access
|
||||
* kind-specific properties. For example:
|
||||
*
|
||||
* ```ts
|
||||
* if (type.flags & TypeFlags.StringLiteral) {
|
||||
* console.log((type as StringLiteralType).value); // string
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export interface Type {
|
||||
/** Type flags — use to determine the specific kind of type. */
|
||||
readonly flags: TypeFlags;
|
||||
/** Unique identifier for this type */
|
||||
readonly id: number;
|
||||
/** Get the symbol associated with this type, if any */
|
||||
getSymbol(): Symbol | undefined;
|
||||
/** Get the type arguments of the type alias this type was instantiated from, if any */
|
||||
getAliasTypeArguments(): readonly Type[];
|
||||
/** Get the symbol of the type alias this type was instantiated from, if any */
|
||||
getAliasSymbol(): Symbol | undefined;
|
||||
/**
|
||||
* Get the base types of this type, or `undefined` if it is not a class or
|
||||
* interface type.
|
||||
*/
|
||||
getBaseTypes(): readonly Type[] | undefined;
|
||||
/** Whether this type is a class or interface type */
|
||||
isClassOrInterface(): this is InterfaceType;
|
||||
/** Whether this type is a union type */
|
||||
isUnionType(): this is UnionType;
|
||||
/** Whether this type is an intersection type */
|
||||
isIntersectionType(): this is IntersectionType;
|
||||
/** Whether this type is an object type */
|
||||
isObjectType(): this is ObjectType;
|
||||
/** Whether this type is an intrinsic primitive type */
|
||||
isIntrinsicType(): this is IntrinsicType;
|
||||
/**
|
||||
* Whether this is the error type — the placeholder produced when a type
|
||||
* cannot be determined (e.g. an unresolved reference).
|
||||
*/
|
||||
isErrorType(): boolean;
|
||||
/** Whether this type is a literal type */
|
||||
isLiteralType(): this is LiteralType;
|
||||
/** Whether this type is a string literal type */
|
||||
isStringLiteralType(): this is StringLiteralType;
|
||||
/** Whether this type is a number literal type */
|
||||
isNumberLiteralType(): this is NumberLiteralType;
|
||||
/** Whether this type is a bigint literal type */
|
||||
isBigIntLiteralType(): this is BigIntLiteralType;
|
||||
/** Whether this type is a boolean literal type */
|
||||
isBooleanLiteralType(): this is BooleanLiteralType;
|
||||
/** Whether this type is a type reference */
|
||||
isTypeReference(): this is TypeReference;
|
||||
/** Whether this type is a tuple type */
|
||||
isTupleType(): this is TupleType;
|
||||
/** Whether this type is an index type (`keyof T`) */
|
||||
isIndexType(): this is IndexType;
|
||||
/** Whether this type is an indexed access type (`T[K]`) */
|
||||
isIndexedAccessType(): this is IndexedAccessType;
|
||||
/** Whether this type is a conditional type */
|
||||
isConditionalType(): this is ConditionalType;
|
||||
/** Whether this type is a substitution type */
|
||||
isSubstitutionType(): this is SubstitutionType;
|
||||
/** Whether this type is a template literal type */
|
||||
isTemplateLiteralType(): this is TemplateLiteralType;
|
||||
/** Whether this type is a string mapping type */
|
||||
isStringMappingType(): this is StringMappingType;
|
||||
/** Whether this type is a type parameter */
|
||||
isTypeParameter(): this is TypeParameter;
|
||||
}
|
||||
/**
|
||||
* Freshable types (TypeFlags.Freshable) - literal types (TypeFlags.Literal) and computed enum types (TypeFlags.Enum).
|
||||
*/
|
||||
export interface FreshableType extends Type {
|
||||
/** Get the fresh version of this type, if any */
|
||||
getFreshType(): FreshableType | undefined;
|
||||
/** Get the regular (non-fresh) version of this type, if any */
|
||||
getRegularType(): FreshableType | undefined;
|
||||
}
|
||||
/** Literal types: StringLiteral, NumberLiteral, BigIntLiteral, BooleanLiteral */
|
||||
export interface LiteralType extends FreshableType {
|
||||
/** The literal value. Use TypeFlags to narrow to a specific literal subtype with a concrete value type. */
|
||||
readonly value: string | number | boolean | bigint;
|
||||
}
|
||||
/** String literal types (TypeFlags.StringLiteral) */
|
||||
export interface StringLiteralType extends LiteralType {
|
||||
/** The string value of the literal */
|
||||
readonly value: string;
|
||||
}
|
||||
/** Numeric literal types (TypeFlags.NumberLiteral) */
|
||||
export interface NumberLiteralType extends LiteralType {
|
||||
/** The numeric value of the literal */
|
||||
readonly value: number;
|
||||
}
|
||||
/** BigInt literal types (TypeFlags.BigIntLiteral) */
|
||||
export interface BigIntLiteralType extends LiteralType {
|
||||
/** The bigint value of the literal */
|
||||
readonly value: bigint;
|
||||
}
|
||||
/** Boolean literal types (TypeFlags.BooleanLiteral) */
|
||||
export interface BooleanLiteralType extends LiteralType {
|
||||
/** The boolean value of the literal */
|
||||
readonly value: boolean;
|
||||
}
|
||||
/** Object types (TypeFlags.Object) */
|
||||
export interface ObjectType extends Type {
|
||||
/** Object flags — use to determine the specific kind of object type. */
|
||||
readonly objectFlags: ObjectFlags;
|
||||
}
|
||||
/** Type references (ObjectFlags.Reference) — e.g. Array<string>, Map<K, V> */
|
||||
export interface TypeReference extends ObjectType {
|
||||
/** Get the generic target type (e.g. Array for Array<string>) */
|
||||
getTarget(): Type;
|
||||
}
|
||||
/** Interface types — classes and interfaces (ObjectFlags.ClassOrInterface) */
|
||||
export interface InterfaceType extends TypeReference {
|
||||
/** Get all type parameters (outer + local, excluding thisType) */
|
||||
getTypeParameters(): readonly TypeParameter[];
|
||||
/** Get outer type parameters from enclosing declarations */
|
||||
getOuterTypeParameters(): readonly TypeParameter[];
|
||||
/** Get local type parameters declared on this interface/class */
|
||||
getLocalTypeParameters(): readonly TypeParameter[];
|
||||
}
|
||||
/** Tuple types (ObjectFlags.Tuple) */
|
||||
export interface TupleType extends InterfaceType {
|
||||
/** Per-element flags (Required, Optional, Rest, Variadic) */
|
||||
readonly elementFlags: readonly ElementFlags[];
|
||||
/** Number of initial required or optional elements */
|
||||
readonly fixedLength: number;
|
||||
/** Whether the tuple is readonly */
|
||||
readonly readonly: boolean;
|
||||
}
|
||||
/** Union or intersection types (TypeFlags.Union | TypeFlags.Intersection) */
|
||||
export interface UnionOrIntersectionType extends Type {
|
||||
/** Get the constituent types */
|
||||
getTypes(): readonly Type[];
|
||||
}
|
||||
/** Union types (TypeFlags.Union) */
|
||||
export interface UnionType extends UnionOrIntersectionType {
|
||||
}
|
||||
/** Intersection types (TypeFlags.Intersection) */
|
||||
export interface IntersectionType extends UnionOrIntersectionType {
|
||||
}
|
||||
/** Type parameters (TypeFlags.TypeParameter) */
|
||||
export interface TypeParameter extends Type {
|
||||
/** True if this is the synthetic `this` type of an interface, class, or tuple */
|
||||
readonly isThisType?: boolean | undefined;
|
||||
}
|
||||
/** Index types — keyof T (TypeFlags.Index) */
|
||||
export interface IndexType extends Type {
|
||||
/** Get the target type T in `keyof T` */
|
||||
getTarget(): Type;
|
||||
}
|
||||
/** Indexed access types — T[K] (TypeFlags.IndexedAccess) */
|
||||
export interface IndexedAccessType extends Type {
|
||||
/** Get the object type T in `T[K]` */
|
||||
getObjectType(): Type;
|
||||
/** Get the index type K in `T[K]` */
|
||||
getIndexType(): Type;
|
||||
}
|
||||
/** Conditional types — T extends U ? X : Y (TypeFlags.Conditional) */
|
||||
export interface ConditionalType extends Type {
|
||||
/** Get the check type T in `T extends U ? X : Y` */
|
||||
getCheckType(): Type;
|
||||
/** Get the extends type U in `T extends U ? X : Y` */
|
||||
getExtendsType(): Type;
|
||||
/** Get the true type X in `T extends U ? X : Y` */
|
||||
getTrueType(): Type;
|
||||
/** Get the false type Y in `T extends U ? X : Y` */
|
||||
getFalseType(): Type;
|
||||
}
|
||||
/** Substitution types (TypeFlags.Substitution) */
|
||||
export interface SubstitutionType extends Type {
|
||||
getBaseType(): Type;
|
||||
getConstraint(): Type;
|
||||
}
|
||||
/** Template literal types (TypeFlags.TemplateLiteral) */
|
||||
export interface TemplateLiteralType extends Type {
|
||||
/** Text segments (always one more than the number of type spans) */
|
||||
readonly texts: readonly string[];
|
||||
/** Get the types interspersed between text segments */
|
||||
getTypes(): readonly Type[];
|
||||
}
|
||||
/** String mapping types — Uppercase<T>, Lowercase<T>, etc. (TypeFlags.StringMapping) */
|
||||
export interface StringMappingType extends Type {
|
||||
/** Get the mapped type */
|
||||
getTarget(): Type;
|
||||
}
|
||||
/** Intrinsic types — any, unknown, string, number, bigint, symbol, void, undefined, null, never, object (TypeFlags.Intrinsic) */
|
||||
export interface IntrinsicType extends Type {
|
||||
/** The intrinsic type name (e.g. "any", "string", "never") */
|
||||
readonly intrinsicName: string;
|
||||
}
|
||||
/** Base for all type predicates */
|
||||
export interface TypePredicateBase {
|
||||
readonly kind: TypePredicateKind;
|
||||
readonly type: Type | undefined;
|
||||
}
|
||||
/** `this is T` */
|
||||
export interface ThisTypePredicate extends TypePredicateBase {
|
||||
readonly kind: TypePredicateKind.This;
|
||||
readonly parameterName: undefined;
|
||||
readonly parameterIndex: undefined;
|
||||
readonly type: Type;
|
||||
}
|
||||
/** `x is T` */
|
||||
export interface IdentifierTypePredicate extends TypePredicateBase {
|
||||
readonly kind: TypePredicateKind.Identifier;
|
||||
readonly parameterName: string;
|
||||
readonly parameterIndex: number;
|
||||
readonly type: Type;
|
||||
}
|
||||
/** `asserts this is T` */
|
||||
export interface AssertsThisTypePredicate extends TypePredicateBase {
|
||||
readonly kind: TypePredicateKind.AssertsThis;
|
||||
readonly parameterName: undefined;
|
||||
readonly parameterIndex: undefined;
|
||||
readonly type: Type | undefined;
|
||||
}
|
||||
/** `asserts x is T` */
|
||||
export interface AssertsIdentifierTypePredicate extends TypePredicateBase {
|
||||
readonly kind: TypePredicateKind.AssertsIdentifier;
|
||||
readonly parameterName: string;
|
||||
readonly parameterIndex: number;
|
||||
readonly type: Type | undefined;
|
||||
}
|
||||
/** A type predicate — e.g. `x is T` or `asserts x is T` */
|
||||
export type TypePredicate = ThisTypePredicate | IdentifierTypePredicate | AssertsThisTypePredicate | AssertsIdentifierTypePredicate;
|
||||
/** An index signature — e.g. `[key: string]: T` */
|
||||
export interface IndexInfo {
|
||||
/** The index key type (e.g. string or number) */
|
||||
readonly keyType: Type;
|
||||
/** The index value type */
|
||||
readonly valueType: Type;
|
||||
/** Whether the index signature is readonly */
|
||||
readonly isReadonly: boolean;
|
||||
/** The index signature declaration, if any */
|
||||
readonly declaration?: NodeHandle | undefined;
|
||||
}
|
||||
/**
|
||||
* A single JSDoc tag attached to a symbol — e.g. `@param`, `@returns`.
|
||||
*/
|
||||
export interface JSDocTagInfo {
|
||||
/** The tag name, without the leading `@` — e.g. `"param"`. */
|
||||
readonly name: string;
|
||||
/** The rendered tag text, if any — e.g. `"a the first number"` for `@param a the first number`. */
|
||||
readonly text?: string | undefined;
|
||||
}
|
||||
export interface CompletionEntryLabelDetails {
|
||||
detail?: string | undefined;
|
||||
description?: string | undefined;
|
||||
}
|
||||
/** Options for {@link Checker.getCompletionsAtPosition}. */
|
||||
export interface CompletionOptions {
|
||||
triggerCharacter?: string | undefined;
|
||||
/** Include a `symbol` property on each completion entry. Only populated for symbol-based completions (not keywords or literals). */
|
||||
includeSymbol?: boolean | undefined;
|
||||
}
|
||||
/** A single completion item returned by {@link Checker.getCompletionsAtPosition}. */
|
||||
export interface CompletionEntry {
|
||||
readonly name: string;
|
||||
readonly kind?: CompletionItemKind | undefined;
|
||||
readonly sortText?: string | undefined;
|
||||
readonly insertText?: string | undefined;
|
||||
readonly filterText?: string | undefined;
|
||||
readonly detail?: string | undefined;
|
||||
readonly labelDetails?: CompletionEntryLabelDetails | undefined;
|
||||
/** The symbol associated with this completion entry. Only set when `includeSymbol: true` is passed and a symbol is available. */
|
||||
readonly symbol?: Symbol | undefined;
|
||||
}
|
||||
/** The result of {@link Checker.getCompletionsAtPosition}. */
|
||||
export interface CompletionInfo {
|
||||
readonly isIncomplete: boolean;
|
||||
readonly entries: readonly CompletionEntry[];
|
||||
}
|
||||
/**
|
||||
* A diagnostic message from the TypeScript compiler.
|
||||
*/
|
||||
export interface Diagnostic {
|
||||
/** File name of the source file this diagnostic belongs to, if any */
|
||||
readonly fileName?: string | undefined;
|
||||
/** Start position of the diagnostic */
|
||||
readonly pos: number;
|
||||
/** End position of the diagnostic */
|
||||
readonly end: number;
|
||||
/** Diagnostic error code */
|
||||
readonly code: number;
|
||||
/** Diagnostic category (error, warning, suggestion, message) */
|
||||
readonly category: DiagnosticCategory;
|
||||
/** Localized diagnostic message text */
|
||||
readonly text: string;
|
||||
/** Whether this diagnostic highlights unnecessary code */
|
||||
readonly reportsUnnecessary?: boolean | undefined;
|
||||
/** Whether this diagnostic highlights deprecated code */
|
||||
readonly reportsDeprecated?: boolean | undefined;
|
||||
/** Chained diagnostic messages */
|
||||
readonly messageChain?: readonly Diagnostic[] | undefined;
|
||||
/** Related diagnostic information */
|
||||
readonly relatedInformation?: readonly Diagnostic[] | undefined;
|
||||
}
|
||||
//# sourceMappingURL=types.d.ts.map
|
||||
@@ -0,0 +1,344 @@
|
||||
import { VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER } from './constants.js';
|
||||
|
||||
// port from nanoid
|
||||
// https://github.com/ai/nanoid
|
||||
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
|
||||
function nanoid(size = 21) {
|
||||
let id = "";
|
||||
let i = size;
|
||||
while (i--) {
|
||||
id += urlAlphabet[Math.random() * 64 | 0];
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
const RealDate = Date;
|
||||
function random(seed) {
|
||||
const x = Math.sin(seed++) * 1e4;
|
||||
return x - Math.floor(x);
|
||||
}
|
||||
function shuffle(array, seed = RealDate.now()) {
|
||||
let length = array.length;
|
||||
while (length) {
|
||||
const index = Math.floor(random(seed) * length--);
|
||||
const previous = array[length];
|
||||
array[length] = array[index];
|
||||
array[index] = previous;
|
||||
++seed;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get original stacktrace without source map support the most performant way.
|
||||
* - Create only 1 stack frame.
|
||||
* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms).
|
||||
*/
|
||||
function createSimpleStackTrace(options) {
|
||||
const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {};
|
||||
const limit = Error.stackTraceLimit;
|
||||
const prepareStackTrace = Error.prepareStackTrace;
|
||||
Error.stackTraceLimit = stackTraceLimit;
|
||||
Error.prepareStackTrace = (e) => e.stack;
|
||||
const err = new Error(message);
|
||||
const stackTrace = err.stack || "";
|
||||
Error.prepareStackTrace = prepareStackTrace;
|
||||
Error.stackTraceLimit = limit;
|
||||
return stackTrace;
|
||||
}
|
||||
function notNullish(v) {
|
||||
return v != null;
|
||||
}
|
||||
function assertTypes(value, name, types) {
|
||||
const receivedType = typeof value;
|
||||
const pass = types.includes(receivedType);
|
||||
if (!pass) {
|
||||
throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`);
|
||||
}
|
||||
}
|
||||
function isPrimitive(value) {
|
||||
return value === null || typeof value !== "function" && typeof value !== "object";
|
||||
}
|
||||
function slash(path) {
|
||||
return path.replace(/\\/g, "/");
|
||||
}
|
||||
const postfixRE = /[?#].*$/;
|
||||
function cleanUrl(url) {
|
||||
return url.replace(postfixRE, "");
|
||||
}
|
||||
function splitFileAndPostfix(path) {
|
||||
const file = cleanUrl(path);
|
||||
return {
|
||||
file,
|
||||
postfix: path.slice(file.length)
|
||||
};
|
||||
}
|
||||
const externalRE = /^(?:[a-z]+:)?\/\//;
|
||||
const isExternalUrl = (url) => externalRE.test(url);
|
||||
/**
|
||||
* Prepend `/@id/` and replace null byte so the id is URL-safe.
|
||||
* This is prepended to resolved ids that are not valid browser
|
||||
* import specifiers by the importAnalysis plugin.
|
||||
*/
|
||||
function wrapId(id) {
|
||||
return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
|
||||
}
|
||||
/**
|
||||
* Undo {@link wrapId}'s `/@id/` and null byte replacements.
|
||||
*/
|
||||
function unwrapId(id) {
|
||||
return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
|
||||
}
|
||||
function withTrailingSlash(path) {
|
||||
if (path.at(-1) !== "/") {
|
||||
return `${path}/`;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
function filterOutComments(s) {
|
||||
const result = [];
|
||||
let commentState = "none";
|
||||
for (let i = 0; i < s.length; ++i) {
|
||||
if (commentState === "singleline") {
|
||||
if (s[i] === "\n") {
|
||||
commentState = "none";
|
||||
}
|
||||
} else if (commentState === "multiline") {
|
||||
if (s[i - 1] === "*" && s[i] === "/") {
|
||||
commentState = "none";
|
||||
}
|
||||
} else if (commentState === "none") {
|
||||
if (s[i] === "/" && s[i + 1] === "/") {
|
||||
commentState = "singleline";
|
||||
} else if (s[i] === "/" && s[i + 1] === "*") {
|
||||
commentState = "multiline";
|
||||
i += 2;
|
||||
} else {
|
||||
result.push(s[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result.join("");
|
||||
}
|
||||
const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
|
||||
function isBareImport(id) {
|
||||
return bareImportRE.test(id);
|
||||
}
|
||||
function toArray(array) {
|
||||
if (array === null || array === undefined) {
|
||||
array = [];
|
||||
}
|
||||
if (Array.isArray(array)) {
|
||||
return array;
|
||||
}
|
||||
return [array];
|
||||
}
|
||||
function isObject(item) {
|
||||
return item != null && typeof item === "object" && !Array.isArray(item);
|
||||
}
|
||||
function isFinalObj(obj) {
|
||||
return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype;
|
||||
}
|
||||
function getType(value) {
|
||||
return Object.prototype.toString.apply(value).slice(8, -1);
|
||||
}
|
||||
function collectOwnProperties(obj, collector) {
|
||||
const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
|
||||
Object.getOwnPropertyNames(obj).forEach(collect);
|
||||
Object.getOwnPropertySymbols(obj).forEach(collect);
|
||||
}
|
||||
function getOwnProperties(obj) {
|
||||
const ownProps = new Set();
|
||||
if (isFinalObj(obj)) {
|
||||
return [];
|
||||
}
|
||||
collectOwnProperties(obj, ownProps);
|
||||
return Array.from(ownProps);
|
||||
}
|
||||
const defaultCloneOptions = { forceWritable: false };
|
||||
function deepClone(val, options = defaultCloneOptions) {
|
||||
const seen = new WeakMap();
|
||||
return clone(val, seen, options);
|
||||
}
|
||||
function clone(val, seen, options = defaultCloneOptions) {
|
||||
let k, out;
|
||||
if (seen.has(val)) {
|
||||
return seen.get(val);
|
||||
}
|
||||
if (Array.isArray(val)) {
|
||||
out = Array.from({ length: k = val.length });
|
||||
seen.set(val, out);
|
||||
while (k--) {
|
||||
out[k] = clone(val[k], seen, options);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (Object.prototype.toString.call(val) === "[object Object]") {
|
||||
out = Object.create(Object.getPrototypeOf(val));
|
||||
seen.set(val, out);
|
||||
// we don't need properties from prototype
|
||||
const props = getOwnProperties(val);
|
||||
for (const k of props) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(val, k);
|
||||
if (!descriptor) {
|
||||
continue;
|
||||
}
|
||||
const cloned = clone(val[k], seen, options);
|
||||
if (options.forceWritable) {
|
||||
Object.defineProperty(out, k, {
|
||||
enumerable: descriptor.enumerable,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: cloned
|
||||
});
|
||||
} else if ("get" in descriptor) {
|
||||
Object.defineProperty(out, k, {
|
||||
...descriptor,
|
||||
get() {
|
||||
return cloned;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
Object.defineProperty(out, k, {
|
||||
...descriptor,
|
||||
value: cloned
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
function noop() {}
|
||||
function objectAttr(source, path, defaultValue = undefined) {
|
||||
// a[3].b -> a.3.b
|
||||
const paths = path.replace(/\[(\d+)\]/g, ".$1").split(".");
|
||||
let result = source;
|
||||
for (const p of paths) {
|
||||
result = new Object(result)[p];
|
||||
if (result === undefined) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function createDefer() {
|
||||
let resolve = null;
|
||||
let reject = null;
|
||||
const p = new Promise((_resolve, _reject) => {
|
||||
resolve = _resolve;
|
||||
reject = _reject;
|
||||
});
|
||||
p.resolve = resolve;
|
||||
p.reject = reject;
|
||||
return p;
|
||||
}
|
||||
/**
|
||||
* If code starts with a function call, will return its last index, respecting arguments.
|
||||
* This will return 25 - last ending character of toMatch ")"
|
||||
* Also works with callbacks
|
||||
* ```
|
||||
* toMatch({ test: '123' });
|
||||
* toBeAliased('123')
|
||||
* ```
|
||||
*/
|
||||
function getCallLastIndex(code) {
|
||||
let charIndex = -1;
|
||||
let inString = null;
|
||||
let startedBracers = 0;
|
||||
let endedBracers = 0;
|
||||
let beforeChar = null;
|
||||
while (charIndex <= code.length) {
|
||||
beforeChar = code[charIndex];
|
||||
charIndex++;
|
||||
const char = code[charIndex];
|
||||
const isCharString = char === "\"" || char === "'" || char === "`";
|
||||
if (isCharString && beforeChar !== "\\") {
|
||||
if (inString === char) {
|
||||
inString = null;
|
||||
} else if (!inString) {
|
||||
inString = char;
|
||||
}
|
||||
}
|
||||
if (!inString) {
|
||||
if (char === "(") {
|
||||
startedBracers++;
|
||||
}
|
||||
if (char === ")") {
|
||||
endedBracers++;
|
||||
}
|
||||
}
|
||||
if (startedBracers && endedBracers && startedBracers === endedBracers) {
|
||||
return charIndex;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function isNegativeNaN(val) {
|
||||
if (!Number.isNaN(val)) {
|
||||
return false;
|
||||
}
|
||||
const f64 = new Float64Array(1);
|
||||
f64[0] = val;
|
||||
const u32 = new Uint32Array(f64.buffer);
|
||||
const isNegative = u32[1] >>> 31 === 1;
|
||||
return isNegative;
|
||||
}
|
||||
function toString(v) {
|
||||
return Object.prototype.toString.call(v);
|
||||
}
|
||||
function isPlainObject(val) {
|
||||
return toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object");
|
||||
}
|
||||
function isMergeableObject(item) {
|
||||
return isPlainObject(item) && !Array.isArray(item);
|
||||
}
|
||||
function ordinal(i) {
|
||||
const j = i % 10;
|
||||
const k = i % 100;
|
||||
if (j === 1 && k !== 11) {
|
||||
return `${i}st`;
|
||||
}
|
||||
if (j === 2 && k !== 12) {
|
||||
return `${i}nd`;
|
||||
}
|
||||
if (j === 3 && k !== 13) {
|
||||
return `${i}rd`;
|
||||
}
|
||||
return `${i}th`;
|
||||
}
|
||||
/**
|
||||
* Deep merge :P
|
||||
*
|
||||
* Will merge objects only if they are plain
|
||||
*
|
||||
* Do not merge types - it is very expensive and usually it's better to case a type here
|
||||
*/
|
||||
function deepMerge(target, ...sources) {
|
||||
if (!sources.length) {
|
||||
return target;
|
||||
}
|
||||
const source = sources.shift();
|
||||
if (source === undefined) {
|
||||
return target;
|
||||
}
|
||||
if (isMergeableObject(target) && isMergeableObject(source)) {
|
||||
Object.keys(source).forEach((key) => {
|
||||
const _source = source;
|
||||
if (isMergeableObject(_source[key])) {
|
||||
if (!target[key]) {
|
||||
target[key] = {};
|
||||
}
|
||||
deepMerge(target[key], _source[key]);
|
||||
} else {
|
||||
target[key] = _source[key];
|
||||
}
|
||||
});
|
||||
}
|
||||
return deepMerge(target, ...sources);
|
||||
}
|
||||
function unique(array) {
|
||||
return Array.from(new Set(array));
|
||||
}
|
||||
|
||||
export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, filterOutComments, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, ordinal, shuffle, slash, splitFileAndPostfix, toArray, unique, unwrapId, withTrailingSlash, wrapId };
|
||||
@@ -0,0 +1,35 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const util_1 = require("../util");
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-extra-non-null-assertion',
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Disallow extra non-null assertions',
|
||||
recommended: 'recommended',
|
||||
},
|
||||
fixable: 'code',
|
||||
messages: {
|
||||
noExtraNonNullAssertion: 'Forbidden extra non-null assertion.',
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
defaultOptions: [],
|
||||
create(context) {
|
||||
function checkExtraNonNullAssertion(node) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'noExtraNonNullAssertion',
|
||||
fix(fixer) {
|
||||
return fixer.removeRange([node.range[1] - 1, node.range[1]]);
|
||||
},
|
||||
});
|
||||
}
|
||||
return {
|
||||
'CallExpression[optional = true] > TSNonNullExpression.callee': checkExtraNonNullAssertion,
|
||||
'MemberExpression[optional = true] > TSNonNullExpression.object': checkExtraNonNullAssertion,
|
||||
'TSNonNullExpression > TSNonNullExpression': checkExtraNonNullAssertion,
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"sha512.d.ts","sourceRoot":"","sources":["../src/sha512.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EACL,MAAM,IAAI,OAAO,EACjB,MAAM,IAAI,OAAO,EACjB,UAAU,IAAI,WAAW,EACzB,UAAU,IAAI,WAAW,EACzB,UAAU,IAAI,WAAW,EACzB,UAAU,IAAI,WAAW,EACzB,MAAM,IAAI,OAAO,EACjB,MAAM,IAAI,OAAO,EAClB,MAAM,WAAW,CAAC;AACnB,6DAA6D;AAC7D,eAAO,MAAM,MAAM,EAAE,OAAO,OAAiB,CAAC;AAC9C,6DAA6D;AAC7D,eAAO,MAAM,MAAM,EAAE,OAAO,OAAiB,CAAC;AAC9C,6DAA6D;AAC7D,eAAO,MAAM,MAAM,EAAE,OAAO,OAAiB,CAAC;AAC9C,6DAA6D;AAC7D,eAAO,MAAM,MAAM,EAAE,OAAO,OAAiB,CAAC;AAC9C,6DAA6D;AAC7D,eAAO,MAAM,UAAU,EAAE,OAAO,WAAyB,CAAC;AAC1D,6DAA6D;AAC7D,eAAO,MAAM,UAAU,EAAE,OAAO,WAAyB,CAAC;AAC1D,6DAA6D;AAC7D,eAAO,MAAM,UAAU,EAAE,OAAO,WAAyB,CAAC;AAC1D,6DAA6D;AAC7D,eAAO,MAAM,UAAU,EAAE,OAAO,WAAyB,CAAC"}
|
||||
@@ -0,0 +1,306 @@
|
||||
/**
|
||||
* hash-to-curve from RFC 9380.
|
||||
* Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
|
||||
* https://www.rfc-editor.org/rfc/rfc9380
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import type { CHash } from '../utils.ts';
|
||||
import {
|
||||
_validateObject,
|
||||
abytes,
|
||||
bytesToNumberBE,
|
||||
concatBytes,
|
||||
isBytes,
|
||||
isHash,
|
||||
utf8ToBytes,
|
||||
} from '../utils.ts';
|
||||
import type { AffinePoint, Group, GroupConstructor } from './curve.ts';
|
||||
import { FpInvertBatch, mod, type IField } from './modular.ts';
|
||||
|
||||
export type UnicodeOrBytes = string | Uint8Array;
|
||||
|
||||
/**
|
||||
* * `DST` is a domain separation tag, defined in section 2.2.5
|
||||
* * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m
|
||||
* * `m` is extension degree (1 for prime fields)
|
||||
* * `k` is the target security target in bits (e.g. 128), from section 5.1
|
||||
* * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)
|
||||
* * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props
|
||||
*/
|
||||
export type H2COpts = {
|
||||
DST: UnicodeOrBytes;
|
||||
expand: 'xmd' | 'xof';
|
||||
hash: CHash;
|
||||
p: bigint;
|
||||
m: number;
|
||||
k: number;
|
||||
};
|
||||
export type H2CHashOpts = {
|
||||
expand: 'xmd' | 'xof';
|
||||
hash: CHash;
|
||||
};
|
||||
// todo: remove
|
||||
export type Opts = H2COpts;
|
||||
|
||||
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
|
||||
const os2ip = bytesToNumberBE;
|
||||
|
||||
// Integer to Octet Stream (numberToBytesBE)
|
||||
function i2osp(value: number, length: number): Uint8Array {
|
||||
anum(value);
|
||||
anum(length);
|
||||
if (value < 0 || value >= 1 << (8 * length)) throw new Error('invalid I2OSP input: ' + value);
|
||||
const res = Array.from({ length }).fill(0) as number[];
|
||||
for (let i = length - 1; i >= 0; i--) {
|
||||
res[i] = value & 0xff;
|
||||
value >>>= 8;
|
||||
}
|
||||
return new Uint8Array(res);
|
||||
}
|
||||
|
||||
function strxor(a: Uint8Array, b: Uint8Array): Uint8Array {
|
||||
const arr = new Uint8Array(a.length);
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
arr[i] = a[i] ^ b[i];
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
function anum(item: unknown): void {
|
||||
if (!Number.isSafeInteger(item)) throw new Error('number expected');
|
||||
}
|
||||
|
||||
function normDST(DST: UnicodeOrBytes): Uint8Array {
|
||||
if (!isBytes(DST) && typeof DST !== 'string') throw new Error('DST must be Uint8Array or string');
|
||||
return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
|
||||
* [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
|
||||
*/
|
||||
export function expand_message_xmd(
|
||||
msg: Uint8Array,
|
||||
DST: UnicodeOrBytes,
|
||||
lenInBytes: number,
|
||||
H: CHash
|
||||
): Uint8Array {
|
||||
abytes(msg);
|
||||
anum(lenInBytes);
|
||||
DST = normDST(DST);
|
||||
// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
|
||||
if (DST.length > 255) DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
|
||||
const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
|
||||
const ell = Math.ceil(lenInBytes / b_in_bytes);
|
||||
if (lenInBytes > 65535 || ell > 255) throw new Error('expand_message_xmd: invalid lenInBytes');
|
||||
const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
|
||||
const Z_pad = i2osp(0, r_in_bytes);
|
||||
const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
|
||||
const b = new Array<Uint8Array>(ell);
|
||||
const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
|
||||
b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
|
||||
for (let i = 1; i <= ell; i++) {
|
||||
const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
|
||||
b[i] = H(concatBytes(...args));
|
||||
}
|
||||
const pseudo_random_bytes = concatBytes(...b);
|
||||
return pseudo_random_bytes.slice(0, lenInBytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces a uniformly random byte string using an extendable-output function (XOF) H.
|
||||
* 1. The collision resistance of H MUST be at least k bits.
|
||||
* 2. H MUST be an XOF that has been proved indifferentiable from
|
||||
* a random oracle under a reasonable cryptographic assumption.
|
||||
* [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
|
||||
*/
|
||||
export function expand_message_xof(
|
||||
msg: Uint8Array,
|
||||
DST: UnicodeOrBytes,
|
||||
lenInBytes: number,
|
||||
k: number,
|
||||
H: CHash
|
||||
): Uint8Array {
|
||||
abytes(msg);
|
||||
anum(lenInBytes);
|
||||
DST = normDST(DST);
|
||||
// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
|
||||
// DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
|
||||
if (DST.length > 255) {
|
||||
const dkLen = Math.ceil((2 * k) / 8);
|
||||
DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
|
||||
}
|
||||
if (lenInBytes > 65535 || DST.length > 255)
|
||||
throw new Error('expand_message_xof: invalid lenInBytes');
|
||||
return (
|
||||
H.create({ dkLen: lenInBytes })
|
||||
.update(msg)
|
||||
.update(i2osp(lenInBytes, 2))
|
||||
// 2. DST_prime = DST || I2OSP(len(DST), 1)
|
||||
.update(DST)
|
||||
.update(i2osp(DST.length, 1))
|
||||
.digest()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
|
||||
* [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
|
||||
* @param msg a byte string containing the message to hash
|
||||
* @param count the number of elements of F to output
|
||||
* @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
|
||||
* @returns [u_0, ..., u_(count - 1)], a list of field elements.
|
||||
*/
|
||||
export function hash_to_field(msg: Uint8Array, count: number, options: H2COpts): bigint[][] {
|
||||
_validateObject(options, {
|
||||
p: 'bigint',
|
||||
m: 'number',
|
||||
k: 'number',
|
||||
hash: 'function',
|
||||
});
|
||||
const { p, k, m, hash, expand, DST } = options;
|
||||
if (!isHash(options.hash)) throw new Error('expected valid hash');
|
||||
abytes(msg);
|
||||
anum(count);
|
||||
const log2p = p.toString(2).length;
|
||||
const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
|
||||
const len_in_bytes = count * m * L;
|
||||
let prb; // pseudo_random_bytes
|
||||
if (expand === 'xmd') {
|
||||
prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
|
||||
} else if (expand === 'xof') {
|
||||
prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
|
||||
} else if (expand === '_internal_pass') {
|
||||
// for internal tests only
|
||||
prb = msg;
|
||||
} else {
|
||||
throw new Error('expand must be "xmd" or "xof"');
|
||||
}
|
||||
const u = new Array(count);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const e = new Array(m);
|
||||
for (let j = 0; j < m; j++) {
|
||||
const elm_offset = L * (j + i * m);
|
||||
const tv = prb.subarray(elm_offset, elm_offset + L);
|
||||
e[j] = mod(os2ip(tv), p);
|
||||
}
|
||||
u[i] = e;
|
||||
}
|
||||
return u;
|
||||
}
|
||||
|
||||
export type XY<T> = (x: T, y: T) => { x: T; y: T };
|
||||
export type XYRatio<T> = [T[], T[], T[], T[]]; // xn/xd, yn/yd
|
||||
export function isogenyMap<T, F extends IField<T>>(field: F, map: XYRatio<T>): XY<T> {
|
||||
// Make same order as in spec
|
||||
const coeff = map.map((i) => Array.from(i).reverse());
|
||||
return (x: T, y: T) => {
|
||||
const [xn, xd, yn, yd] = coeff.map((val) =>
|
||||
val.reduce((acc, i) => field.add(field.mul(acc, x), i))
|
||||
);
|
||||
// 6.6.3
|
||||
// Exceptional cases of iso_map are inputs that cause the denominator of
|
||||
// either rational function to evaluate to zero; such cases MUST return
|
||||
// the identity point on E.
|
||||
const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
|
||||
x = field.mul(xn, xd_inv); // xNum / xDen
|
||||
y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
|
||||
return { x, y };
|
||||
};
|
||||
}
|
||||
|
||||
/** Point interface, which curves must implement to work correctly with the module. */
|
||||
export interface H2CPoint<T> extends Group<H2CPoint<T>> {
|
||||
add(rhs: H2CPoint<T>): H2CPoint<T>;
|
||||
toAffine(iz?: bigint): AffinePoint<T>;
|
||||
clearCofactor(): H2CPoint<T>;
|
||||
assertValidity(): void;
|
||||
}
|
||||
|
||||
export interface H2CPointConstructor<T> extends GroupConstructor<H2CPoint<T>> {
|
||||
fromAffine(ap: AffinePoint<T>): H2CPoint<T>;
|
||||
}
|
||||
|
||||
export type MapToCurve<T> = (scalar: bigint[]) => AffinePoint<T>;
|
||||
|
||||
// Separated from initialization opts, so users won't accidentally change per-curve parameters
|
||||
// (changing DST is ok!)
|
||||
export type htfBasicOpts = { DST: UnicodeOrBytes };
|
||||
export type H2CMethod<T> = (msg: Uint8Array, options?: htfBasicOpts) => H2CPoint<T>;
|
||||
// TODO: remove
|
||||
export type HTFMethod<T> = H2CMethod<T>;
|
||||
export type MapMethod<T> = (scalars: bigint[]) => H2CPoint<T>;
|
||||
export type H2CHasherBase<T> = {
|
||||
hashToCurve: H2CMethod<T>;
|
||||
hashToScalar: (msg: Uint8Array, options: htfBasicOpts) => bigint;
|
||||
};
|
||||
/**
|
||||
* RFC 9380 methods, with cofactor clearing. See https://www.rfc-editor.org/rfc/rfc9380#section-3.
|
||||
*
|
||||
* * hashToCurve: `map(hash(input))`, encodes RANDOM bytes to curve (WITH hashing)
|
||||
* * encodeToCurve: `map(hash(input))`, encodes NON-UNIFORM bytes to curve (WITH hashing)
|
||||
* * mapToCurve: `map(scalars)`, encodes NON-UNIFORM scalars to curve (NO hashing)
|
||||
*/
|
||||
export type H2CHasher<T> = H2CHasherBase<T> & {
|
||||
encodeToCurve: H2CMethod<T>;
|
||||
mapToCurve: MapMethod<T>;
|
||||
defaults: H2COpts & { encodeDST?: UnicodeOrBytes };
|
||||
};
|
||||
// TODO: remove
|
||||
export type Hasher<T> = H2CHasher<T>;
|
||||
|
||||
export const _DST_scalar: Uint8Array = utf8ToBytes('HashToScalar-');
|
||||
|
||||
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
|
||||
export function createHasher<T>(
|
||||
Point: H2CPointConstructor<T>,
|
||||
mapToCurve: MapToCurve<T>,
|
||||
defaults: H2COpts & { encodeDST?: UnicodeOrBytes }
|
||||
): H2CHasher<T> {
|
||||
if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');
|
||||
function map(num: bigint[]) {
|
||||
return Point.fromAffine(mapToCurve(num));
|
||||
}
|
||||
function clear(initial: H2CPoint<T>) {
|
||||
const P = initial.clearCofactor();
|
||||
if (P.equals(Point.ZERO)) return Point.ZERO; // zero will throw in assert
|
||||
P.assertValidity();
|
||||
return P;
|
||||
}
|
||||
|
||||
return {
|
||||
defaults,
|
||||
|
||||
hashToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint<T> {
|
||||
const opts = Object.assign({}, defaults, options);
|
||||
const u = hash_to_field(msg, 2, opts);
|
||||
const u0 = map(u[0]);
|
||||
const u1 = map(u[1]);
|
||||
return clear(u0.add(u1));
|
||||
},
|
||||
encodeToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint<T> {
|
||||
const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
|
||||
const opts = Object.assign({}, defaults, optsDst, options);
|
||||
const u = hash_to_field(msg, 1, opts);
|
||||
const u0 = map(u[0]);
|
||||
return clear(u0);
|
||||
},
|
||||
/** See {@link H2CHasher} */
|
||||
mapToCurve(scalars: bigint[]): H2CPoint<T> {
|
||||
if (!Array.isArray(scalars)) throw new Error('expected array of bigints');
|
||||
for (const i of scalars)
|
||||
if (typeof i !== 'bigint') throw new Error('expected array of bigints');
|
||||
return clear(map(scalars));
|
||||
},
|
||||
|
||||
// hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
|
||||
// RFC 9380, draft-irtf-cfrg-bbs-signatures-08
|
||||
hashToScalar(msg: Uint8Array, options?: htfBasicOpts): bigint {
|
||||
// @ts-ignore
|
||||
const N = Point.Fn.ORDER;
|
||||
const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
|
||||
return hash_to_field(msg, 1, opts)[0][0];
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/*! *****************************************************************************
|
||||
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 ProxyHandler<T extends object> {
|
||||
/**
|
||||
* A trap method for a function call.
|
||||
* @param target The original callable object which is being proxied.
|
||||
*/
|
||||
apply?(target: T, thisArg: any, argArray: any[]): any;
|
||||
|
||||
/**
|
||||
* A trap for the `new` operator.
|
||||
* @param target The original object which is being proxied.
|
||||
* @param newTarget The constructor that was originally called.
|
||||
*/
|
||||
construct?(target: T, argArray: any[], newTarget: Function): object;
|
||||
|
||||
/**
|
||||
* A trap for `Object.defineProperty()`.
|
||||
* @param target The original object which is being proxied.
|
||||
* @returns A `Boolean` indicating whether or not the property has been defined.
|
||||
*/
|
||||
defineProperty?(target: T, property: string | symbol, attributes: PropertyDescriptor): boolean;
|
||||
|
||||
/**
|
||||
* A trap for the `delete` operator.
|
||||
* @param target The original object which is being proxied.
|
||||
* @param p The name or `Symbol` of the property to delete.
|
||||
* @returns A `Boolean` indicating whether or not the property was deleted.
|
||||
*/
|
||||
deleteProperty?(target: T, p: string | symbol): boolean;
|
||||
|
||||
/**
|
||||
* A trap for getting a property value.
|
||||
* @param target The original object which is being proxied.
|
||||
* @param p The name or `Symbol` of the property to get.
|
||||
* @param receiver The proxy or an object that inherits from the proxy.
|
||||
*/
|
||||
get?(target: T, p: string | symbol, receiver: any): any;
|
||||
|
||||
/**
|
||||
* A trap for `Object.getOwnPropertyDescriptor()`.
|
||||
* @param target The original object which is being proxied.
|
||||
* @param p The name of the property whose description should be retrieved.
|
||||
*/
|
||||
getOwnPropertyDescriptor?(target: T, p: string | symbol): PropertyDescriptor | undefined;
|
||||
|
||||
/**
|
||||
* A trap for the `[[GetPrototypeOf]]` internal method.
|
||||
* @param target The original object which is being proxied.
|
||||
*/
|
||||
getPrototypeOf?(target: T): object | null;
|
||||
|
||||
/**
|
||||
* A trap for the `in` operator.
|
||||
* @param target The original object which is being proxied.
|
||||
* @param p The name or `Symbol` of the property to check for existence.
|
||||
*/
|
||||
has?(target: T, p: string | symbol): boolean;
|
||||
|
||||
/**
|
||||
* A trap for `Object.isExtensible()`.
|
||||
* @param target The original object which is being proxied.
|
||||
*/
|
||||
isExtensible?(target: T): boolean;
|
||||
|
||||
/**
|
||||
* A trap for `Reflect.ownKeys()`.
|
||||
* @param target The original object which is being proxied.
|
||||
*/
|
||||
ownKeys?(target: T): ArrayLike<string | symbol>;
|
||||
|
||||
/**
|
||||
* A trap for `Object.preventExtensions()`.
|
||||
* @param target The original object which is being proxied.
|
||||
*/
|
||||
preventExtensions?(target: T): boolean;
|
||||
|
||||
/**
|
||||
* A trap for setting a property value.
|
||||
* @param target The original object which is being proxied.
|
||||
* @param p The name or `Symbol` of the property to set.
|
||||
* @param receiver The object to which the assignment was originally directed.
|
||||
* @returns A `Boolean` indicating whether or not the property was set.
|
||||
*/
|
||||
set?(target: T, p: string | symbol, newValue: any, receiver: any): boolean;
|
||||
|
||||
/**
|
||||
* A trap for `Object.setPrototypeOf()`.
|
||||
* @param target The original object which is being proxied.
|
||||
* @param newPrototype The object's new prototype or `null`.
|
||||
*/
|
||||
setPrototypeOf?(target: T, v: object | null): boolean;
|
||||
}
|
||||
|
||||
interface ProxyConstructor {
|
||||
/**
|
||||
* Creates a revocable Proxy object.
|
||||
* @param target A target object to wrap with Proxy.
|
||||
* @param handler An object whose properties define the behavior of Proxy when an operation is attempted on it.
|
||||
*/
|
||||
revocable<T extends object>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
|
||||
|
||||
/**
|
||||
* Creates a Proxy object. The Proxy object allows you to create an object that can be used in place of the
|
||||
* original object, but which may redefine fundamental Object operations like getting, setting, and defining
|
||||
* properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs.
|
||||
* @param target A target object to wrap with Proxy.
|
||||
* @param handler An object whose properties define the behavior of Proxy when an operation is attempted on it.
|
||||
*/
|
||||
new <T extends object>(target: T, handler: ProxyHandler<T>): T;
|
||||
}
|
||||
declare var Proxy: ProxyConstructor;
|
||||
@@ -0,0 +1,18 @@
|
||||
import { type CurveFn as BLSCurveFn, type PostPrecomputeFn } from './abstract/bls.ts';
|
||||
import { type IField } from './abstract/modular.ts';
|
||||
import { type CurveFn } from './abstract/weierstrass.ts';
|
||||
export declare const bn254_Fr: IField<bigint>;
|
||||
export declare const _postPrecompute: PostPrecomputeFn;
|
||||
/**
|
||||
* bn254 (a.k.a. alt_bn128) pairing-friendly curve.
|
||||
* Contains G1 / G2 operations and pairings.
|
||||
*/
|
||||
export declare const bn254: BLSCurveFn;
|
||||
/**
|
||||
* bn254 weierstrass curve with ECDSA.
|
||||
* This is very rare and probably not used anywhere.
|
||||
* Instead, you should use G1 / G2, defined above.
|
||||
* @deprecated
|
||||
*/
|
||||
export declare const bn254_weierstrass: CurveFn;
|
||||
//# sourceMappingURL=bn254.d.ts.map
|
||||
@@ -0,0 +1,322 @@
|
||||
/**
|
||||
* Hex, bytes and number utilities.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';
|
||||
export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
|
||||
const _0n = /* @__PURE__ */ BigInt(0);
|
||||
const _1n = /* @__PURE__ */ BigInt(1);
|
||||
export function abool(title, value) {
|
||||
if (typeof value !== 'boolean')
|
||||
throw new Error(title + ' boolean expected, got ' + value);
|
||||
}
|
||||
// tmp name until v2
|
||||
export function _abool2(value, title = '') {
|
||||
if (typeof value !== 'boolean') {
|
||||
const prefix = title && `"${title}"`;
|
||||
throw new Error(prefix + 'expected boolean, got type=' + typeof value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
// tmp name until v2
|
||||
/** Asserts something is Uint8Array. */
|
||||
export function _abytes2(value, length, title = '') {
|
||||
const bytes = isBytes_(value);
|
||||
const len = value?.length;
|
||||
const needsLen = length !== undefined;
|
||||
if (!bytes || (needsLen && len !== length)) {
|
||||
const prefix = title && `"${title}" `;
|
||||
const ofLen = needsLen ? ` of length ${length}` : '';
|
||||
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
||||
throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
// Used in weierstrass, der
|
||||
export function numberToHexUnpadded(num) {
|
||||
const hex = num.toString(16);
|
||||
return hex.length & 1 ? '0' + hex : hex;
|
||||
}
|
||||
export function hexToNumber(hex) {
|
||||
if (typeof hex !== 'string')
|
||||
throw new Error('hex string expected, got ' + typeof hex);
|
||||
return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
|
||||
}
|
||||
// BE: Big Endian, LE: Little Endian
|
||||
export function bytesToNumberBE(bytes) {
|
||||
return hexToNumber(bytesToHex_(bytes));
|
||||
}
|
||||
export function bytesToNumberLE(bytes) {
|
||||
abytes_(bytes);
|
||||
return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
|
||||
}
|
||||
export function numberToBytesBE(n, len) {
|
||||
return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
|
||||
}
|
||||
export function numberToBytesLE(n, len) {
|
||||
return numberToBytesBE(n, len).reverse();
|
||||
}
|
||||
// Unpadded, rarely used
|
||||
export function numberToVarBytesBE(n) {
|
||||
return hexToBytes_(numberToHexUnpadded(n));
|
||||
}
|
||||
/**
|
||||
* Takes hex string or Uint8Array, converts to Uint8Array.
|
||||
* Validates output length.
|
||||
* Will throw error for other types.
|
||||
* @param title descriptive title for an error e.g. 'secret key'
|
||||
* @param hex hex string or Uint8Array
|
||||
* @param expectedLength optional, will compare to result array's length
|
||||
* @returns
|
||||
*/
|
||||
export function ensureBytes(title, hex, expectedLength) {
|
||||
let res;
|
||||
if (typeof hex === 'string') {
|
||||
try {
|
||||
res = hexToBytes_(hex);
|
||||
}
|
||||
catch (e) {
|
||||
throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
|
||||
}
|
||||
}
|
||||
else if (isBytes_(hex)) {
|
||||
// Uint8Array.from() instead of hash.slice() because node.js Buffer
|
||||
// is instance of Uint8Array, and its slice() creates **mutable** copy
|
||||
res = Uint8Array.from(hex);
|
||||
}
|
||||
else {
|
||||
throw new Error(title + ' must be hex string or Uint8Array');
|
||||
}
|
||||
const len = res.length;
|
||||
if (typeof expectedLength === 'number' && len !== expectedLength)
|
||||
throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
|
||||
return res;
|
||||
}
|
||||
// Compares 2 u8a-s in kinda constant time
|
||||
export function equalBytes(a, b) {
|
||||
if (a.length !== b.length)
|
||||
return false;
|
||||
let diff = 0;
|
||||
for (let i = 0; i < a.length; i++)
|
||||
diff |= a[i] ^ b[i];
|
||||
return diff === 0;
|
||||
}
|
||||
/**
|
||||
* Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
|
||||
* and Buffer#slice creates mutable copy. Never use Buffers!
|
||||
*/
|
||||
export function copyBytes(bytes) {
|
||||
return Uint8Array.from(bytes);
|
||||
}
|
||||
/**
|
||||
* Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
|
||||
* Should be safe to use for things expected to be ASCII.
|
||||
* Returns exact same result as utf8ToBytes for ASCII or throws.
|
||||
*/
|
||||
export function asciiToBytes(ascii) {
|
||||
return Uint8Array.from(ascii, (c, i) => {
|
||||
const charCode = c.charCodeAt(0);
|
||||
if (c.length !== 1 || charCode > 127) {
|
||||
throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
|
||||
}
|
||||
return charCode;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
|
||||
*/
|
||||
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
|
||||
/**
|
||||
* Converts bytes to string using UTF8 encoding.
|
||||
* @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
|
||||
*/
|
||||
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
|
||||
// Is positive bigint
|
||||
const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
|
||||
export function inRange(n, min, max) {
|
||||
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
||||
}
|
||||
/**
|
||||
* Asserts min <= n < max. NOTE: It's < max and not <= max.
|
||||
* @example
|
||||
* aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
|
||||
*/
|
||||
export function aInRange(title, n, min, max) {
|
||||
// Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
|
||||
// consider P=256n, min=0n, max=P
|
||||
// - a for min=0 would require -1: `inRange('x', x, -1n, P)`
|
||||
// - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
|
||||
// - our way is the cleanest: `inRange('x', x, 0n, P)
|
||||
if (!inRange(n, min, max))
|
||||
throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
|
||||
}
|
||||
// Bit operations
|
||||
/**
|
||||
* Calculates amount of bits in a bigint.
|
||||
* Same as `n.toString(2).length`
|
||||
* TODO: merge with nLength in modular
|
||||
*/
|
||||
export function bitLen(n) {
|
||||
let len;
|
||||
for (len = 0; n > _0n; n >>= _1n, len += 1)
|
||||
;
|
||||
return len;
|
||||
}
|
||||
/**
|
||||
* Gets single bit at position.
|
||||
* NOTE: first bit position is 0 (same as arrays)
|
||||
* Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
|
||||
*/
|
||||
export function bitGet(n, pos) {
|
||||
return (n >> BigInt(pos)) & _1n;
|
||||
}
|
||||
/**
|
||||
* Sets single bit at position.
|
||||
*/
|
||||
export function bitSet(n, pos, value) {
|
||||
return n | ((value ? _1n : _0n) << BigInt(pos));
|
||||
}
|
||||
/**
|
||||
* Calculate mask for N bits. Not using ** operator with bigints because of old engines.
|
||||
* Same as BigInt(`0b${Array(i).fill('1').join('')}`)
|
||||
*/
|
||||
export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
|
||||
/**
|
||||
* Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
||||
* @returns function that will call DRBG until 2nd arg returns something meaningful
|
||||
* @example
|
||||
* const drbg = createHmacDRBG<Key>(32, 32, hmac);
|
||||
* drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
|
||||
*/
|
||||
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
||||
if (typeof hashLen !== 'number' || hashLen < 2)
|
||||
throw new Error('hashLen must be a number');
|
||||
if (typeof qByteLen !== 'number' || qByteLen < 2)
|
||||
throw new Error('qByteLen must be a number');
|
||||
if (typeof hmacFn !== 'function')
|
||||
throw new Error('hmacFn must be a function');
|
||||
// Step B, Step C: set hashLen to 8*ceil(hlen/8)
|
||||
const u8n = (len) => new Uint8Array(len); // creates Uint8Array
|
||||
const u8of = (byte) => Uint8Array.of(byte); // another shortcut
|
||||
let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
||||
let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
|
||||
let i = 0; // Iterations counter, will throw when over 1000
|
||||
const reset = () => {
|
||||
v.fill(1);
|
||||
k.fill(0);
|
||||
i = 0;
|
||||
};
|
||||
const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
|
||||
const reseed = (seed = u8n(0)) => {
|
||||
// HMAC-DRBG reseed() function. Steps D-G
|
||||
k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
|
||||
v = h(); // v = hmac(k || v)
|
||||
if (seed.length === 0)
|
||||
return;
|
||||
k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
|
||||
v = h(); // v = hmac(k || v)
|
||||
};
|
||||
const gen = () => {
|
||||
// HMAC-DRBG generate() function
|
||||
if (i++ >= 1000)
|
||||
throw new Error('drbg: tried 1000 values');
|
||||
let len = 0;
|
||||
const out = [];
|
||||
while (len < qByteLen) {
|
||||
v = h();
|
||||
const sl = v.slice();
|
||||
out.push(sl);
|
||||
len += v.length;
|
||||
}
|
||||
return concatBytes_(...out);
|
||||
};
|
||||
const genUntil = (seed, pred) => {
|
||||
reset();
|
||||
reseed(seed); // Steps D-G
|
||||
let res = undefined; // Step H: grind until k is in [1..n-1]
|
||||
while (!(res = pred(gen())))
|
||||
reseed();
|
||||
reset();
|
||||
return res;
|
||||
};
|
||||
return genUntil;
|
||||
}
|
||||
// Validating curves and fields
|
||||
const validatorFns = {
|
||||
bigint: (val) => typeof val === 'bigint',
|
||||
function: (val) => typeof val === 'function',
|
||||
boolean: (val) => typeof val === 'boolean',
|
||||
string: (val) => typeof val === 'string',
|
||||
stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),
|
||||
isSafeInteger: (val) => Number.isSafeInteger(val),
|
||||
array: (val) => Array.isArray(val),
|
||||
field: (val, object) => object.Fp.isValid(val),
|
||||
hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
|
||||
};
|
||||
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
|
||||
export function validateObject(object, validators, optValidators = {}) {
|
||||
const checkField = (fieldName, type, isOptional) => {
|
||||
const checkVal = validatorFns[type];
|
||||
if (typeof checkVal !== 'function')
|
||||
throw new Error('invalid validator function');
|
||||
const val = object[fieldName];
|
||||
if (isOptional && val === undefined)
|
||||
return;
|
||||
if (!checkVal(val, object)) {
|
||||
throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
|
||||
}
|
||||
};
|
||||
for (const [fieldName, type] of Object.entries(validators))
|
||||
checkField(fieldName, type, false);
|
||||
for (const [fieldName, type] of Object.entries(optValidators))
|
||||
checkField(fieldName, type, true);
|
||||
return object;
|
||||
}
|
||||
// validate type tests
|
||||
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
|
||||
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
|
||||
// // Should fail type-check
|
||||
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
|
||||
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
|
||||
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
|
||||
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
|
||||
export function isHash(val) {
|
||||
return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
|
||||
}
|
||||
export function _validateObject(object, fields, optFields = {}) {
|
||||
if (!object || typeof object !== 'object')
|
||||
throw new Error('expected valid options object');
|
||||
function checkField(fieldName, expectedType, isOpt) {
|
||||
const val = object[fieldName];
|
||||
if (isOpt && val === undefined)
|
||||
return;
|
||||
const current = typeof val;
|
||||
if (current !== expectedType || val === null)
|
||||
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
||||
}
|
||||
Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
|
||||
Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
|
||||
}
|
||||
/**
|
||||
* throws not implemented error
|
||||
*/
|
||||
export const notImplemented = () => {
|
||||
throw new Error('not implemented');
|
||||
};
|
||||
/**
|
||||
* Memoizes (caches) computation result.
|
||||
* Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
|
||||
*/
|
||||
export function memoized(fn) {
|
||||
const map = new WeakMap();
|
||||
return (arg, ...args) => {
|
||||
const val = map.get(arg);
|
||||
if (val !== undefined)
|
||||
return val;
|
||||
const computed = fn(arg, ...args);
|
||||
map.set(arg, computed);
|
||||
return computed;
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=utils.js.map
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Internal assertion helpers.
|
||||
* @module
|
||||
* @deprecated
|
||||
*/
|
||||
import {
|
||||
abytes as ab,
|
||||
aexists as ae,
|
||||
anumber as an,
|
||||
aoutput as ao,
|
||||
type IHash as H,
|
||||
} from './utils.ts';
|
||||
/** @deprecated Use import from `noble/hashes/utils` module */
|
||||
export const abytes: typeof ab = ab;
|
||||
/** @deprecated Use import from `noble/hashes/utils` module */
|
||||
export const aexists: typeof ae = ae;
|
||||
/** @deprecated Use import from `noble/hashes/utils` module */
|
||||
export const anumber: typeof an = an;
|
||||
/** @deprecated Use import from `noble/hashes/utils` module */
|
||||
export const aoutput: typeof ao = ao;
|
||||
/** @deprecated Use import from `noble/hashes/utils` module */
|
||||
export type Hash = H;
|
||||
@@ -0,0 +1,57 @@
|
||||
import { S as Suite, c as File, e as Task, a1 as TestTagDefinition, a5 as VitestRunnerConfig, a as Test } from './tasks.d-DEYaIMIu.js';
|
||||
export { ag as ChainableFunction, ah as createChainable } from './tasks.d-DEYaIMIu.js';
|
||||
import { ParsedStack, Arrayable } from '@vitest/utils';
|
||||
import '@vitest/utils/diff';
|
||||
|
||||
/**
|
||||
* If any tasks been marked as `only`, mark all other tasks as `skip`.
|
||||
*/
|
||||
declare function interpretTaskModes(file: Suite, namePattern?: string | RegExp, testLocations?: number[] | undefined, testIds?: string[] | undefined, testTagsFilter?: ((testTags: string[]) => boolean) | undefined, onlyMode?: boolean, parentIsOnly?: boolean, allowOnly?: boolean): void;
|
||||
declare function someTasksAreOnly(suite: Suite): boolean;
|
||||
declare function generateHash(str: string): string;
|
||||
declare function calculateSuiteHash(parent: Suite): void;
|
||||
declare function createFileTask(filepath: string, root: string, projectName: string | undefined, pool?: string, viteEnvironment?: string): File;
|
||||
/**
|
||||
* Generate a unique ID for a file based on its path and project name
|
||||
* @param file File relative to the root of the project to keep ID the same between different machines
|
||||
* @param projectName The name of the test project
|
||||
*/
|
||||
declare function generateFileHash(file: string, projectName: string | undefined): string;
|
||||
declare function findTestFileStackTrace(testFilePath: string, error: string): ParsedStack | undefined;
|
||||
|
||||
interface ConcurrencyLimiter extends ConcurrencyLimiterFn {
|
||||
acquire: () => (() => void) | Promise<() => void>;
|
||||
}
|
||||
type ConcurrencyLimiterFn = <
|
||||
Args extends unknown[],
|
||||
T
|
||||
>(func: (...args: Args) => PromiseLike<T> | T, ...args: Args) => Promise<T>;
|
||||
/**
|
||||
* Return a function for running multiple async operations with limited concurrency.
|
||||
*/
|
||||
declare function limitConcurrency(concurrency?: number): ConcurrencyLimiter;
|
||||
|
||||
/**
|
||||
* Partition in tasks groups by consecutive concurrent
|
||||
*/
|
||||
declare function partitionSuiteChildren(suite: Suite): Task[][];
|
||||
|
||||
/**
|
||||
* @experimental
|
||||
*/
|
||||
declare function matchesTags(testTags: string[]): boolean;
|
||||
declare function validateTags(config: VitestRunnerConfig, tags: string[]): void;
|
||||
declare function createTagsFilter(tagsExpr: string[], availableTags: TestTagDefinition[]): (testTags: string[]) => boolean;
|
||||
|
||||
declare function isTestCase(s: Task): s is Test;
|
||||
declare function getTests(suite: Arrayable<Task>): Test[];
|
||||
declare function getTasks(tasks?: Arrayable<Task>): Task[];
|
||||
declare function getSuites(suite: Arrayable<Task>): Suite[];
|
||||
declare function hasTests(suite: Arrayable<Suite>): boolean;
|
||||
declare function hasFailed(suite: Arrayable<Task>): boolean;
|
||||
declare function getNames(task: Task): string[];
|
||||
declare function getFullName(task: Task, separator?: string): string;
|
||||
declare function getTestName(task: Task, separator?: string): string;
|
||||
declare function createTaskName(names: readonly (string | undefined)[], separator?: string): string;
|
||||
|
||||
export { calculateSuiteHash, createFileTask, createTagsFilter, createTaskName, findTestFileStackTrace, generateFileHash, generateHash, getFullName, getNames, getSuites, getTasks, getTestName, getTests, hasFailed, hasTests, interpretTaskModes, isTestCase, limitConcurrency, matchesTags, partitionSuiteChildren, someTasksAreOnly, validateTags };
|
||||
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"reg": {
|
||||
"name": "reg",
|
||||
"browser": "Chrome Mobile 55.0.2883 (Android 6.0.0)",
|
||||
"suite": "escape-short",
|
||||
"hz": 383550.51167372527,
|
||||
"success": true,
|
||||
"fastest": false,
|
||||
"rme": 0.07384001243033904,
|
||||
"rhz": 0.29787002825625064,
|
||||
"sampleSize": 146
|
||||
},
|
||||
"fn if": {
|
||||
"name": "fn if",
|
||||
"browser": "Chrome Mobile 55.0.2883 (Android 6.0.0)",
|
||||
"suite": "escape-short",
|
||||
"hz": 618580.987554145,
|
||||
"success": true,
|
||||
"fastest": false,
|
||||
"rme": 0.020759770661330924,
|
||||
"rhz": 0.4803975764169341,
|
||||
"sampleSize": 147
|
||||
},
|
||||
"fn if reverse": {
|
||||
"name": "fn if reverse",
|
||||
"browser": "Chrome Mobile 55.0.2883 (Android 6.0.0)",
|
||||
"suite": "escape-short",
|
||||
"hz": 566687.2120246552,
|
||||
"success": true,
|
||||
"fastest": false,
|
||||
"rme": 0.024273474903516126,
|
||||
"rhz": 0.4400962343177167,
|
||||
"sampleSize": 147
|
||||
},
|
||||
"escape31": {
|
||||
"name": "escape31",
|
||||
"browser": "Chrome Mobile 55.0.2883 (Android 6.0.0)",
|
||||
"suite": "escape-short",
|
||||
"hz": 924253.0121271972,
|
||||
"success": true,
|
||||
"fastest": false,
|
||||
"rme": 0.022119683746745625,
|
||||
"rhz": 0.7177862170927007,
|
||||
"sampleSize": 148
|
||||
},
|
||||
"native": {
|
||||
"name": "native",
|
||||
"browser": "Chrome Mobile 55.0.2883 (Android 6.0.0)",
|
||||
"suite": "escape-short",
|
||||
"hz": 1287643.8556744142,
|
||||
"success": true,
|
||||
"fastest": true,
|
||||
"rme": 0.029172189762178075,
|
||||
"rhz": 1,
|
||||
"sampleSize": 145
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "esutils",
|
||||
"description": "utility box for ECMAScript language tools",
|
||||
"homepage": "https://github.com/estools/esutils",
|
||||
"main": "lib/utils.js",
|
||||
"version": "2.0.3",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"directories": {
|
||||
"lib": "./lib"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE.BSD",
|
||||
"README.md",
|
||||
"lib"
|
||||
],
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "Yusuke Suzuki",
|
||||
"email": "utatane.tea@gmail.com",
|
||||
"web": "http://github.com/Constellation"
|
||||
}
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "http://github.com/estools/esutils.git"
|
||||
},
|
||||
"devDependencies": {
|
||||
"chai": "~1.7.2",
|
||||
"coffee-script": "~1.6.3",
|
||||
"jshint": "2.6.3",
|
||||
"mocha": "~2.2.1",
|
||||
"regenerate": "~1.3.1",
|
||||
"unicode-9.0.0": "~0.7.0"
|
||||
},
|
||||
"license": "BSD-2-Clause",
|
||||
"scripts": {
|
||||
"test": "npm run-script lint && npm run-script unit-test",
|
||||
"lint": "jshint lib/*.js",
|
||||
"unit-test": "mocha --compilers coffee:coffee-script -R spec",
|
||||
"generate-regex": "node tools/generate-identifier-regex.js"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
"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.esnext_bigint = void 0;
|
||||
const base_config_1 = require("./base-config");
|
||||
const es2020_intl_1 = require("./es2020.intl");
|
||||
exports.esnext_bigint = {
|
||||
libs: [es2020_intl_1.es2020_intl],
|
||||
variables: [
|
||||
['BigIntToLocaleStringOptions', base_config_1.TYPE],
|
||||
['BigInt', base_config_1.TYPE_VALUE],
|
||||
['BigIntConstructor', base_config_1.TYPE],
|
||||
['BigInt64Array', base_config_1.TYPE_VALUE],
|
||||
['BigInt64ArrayConstructor', base_config_1.TYPE],
|
||||
['BigUint64Array', base_config_1.TYPE_VALUE],
|
||||
['BigUint64ArrayConstructor', base_config_1.TYPE],
|
||||
['DataView', base_config_1.TYPE],
|
||||
['Intl', base_config_1.TYPE_VALUE],
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"reg": {
|
||||
"name": "reg",
|
||||
"browser": "Chrome 60.0.3112 (Windows 7 0.0.0)",
|
||||
"suite": "escape-long",
|
||||
"hz": 253343.14412049987,
|
||||
"success": true,
|
||||
"fastest": false,
|
||||
"rme": 0.014150323478317376,
|
||||
"rhz": 0.8571066586149397,
|
||||
"sampleSize": 173
|
||||
},
|
||||
"fn if": {
|
||||
"name": "fn if",
|
||||
"browser": "Chrome 60.0.3112 (Windows 7 0.0.0)",
|
||||
"suite": "escape-long",
|
||||
"hz": 152430.27131168763,
|
||||
"success": true,
|
||||
"fastest": false,
|
||||
"rme": 0.009869184897547099,
|
||||
"rhz": 0.5156997674805344,
|
||||
"sampleSize": 173
|
||||
},
|
||||
"fn if reverse": {
|
||||
"name": "fn if reverse",
|
||||
"browser": "Chrome 60.0.3112 (Windows 7 0.0.0)",
|
||||
"suite": "escape-long",
|
||||
"hz": 134572.13503988463,
|
||||
"success": true,
|
||||
"fastest": false,
|
||||
"rme": 0.00900151732022404,
|
||||
"rhz": 0.4552823934002038,
|
||||
"sampleSize": 171
|
||||
},
|
||||
"escape31": {
|
||||
"name": "escape31",
|
||||
"browser": "Chrome 60.0.3112 (Windows 7 0.0.0)",
|
||||
"suite": "escape-long",
|
||||
"hz": 164000.28145229374,
|
||||
"success": true,
|
||||
"fastest": false,
|
||||
"rme": 0.010577368405487704,
|
||||
"rhz": 0.5548432492044333,
|
||||
"sampleSize": 172
|
||||
},
|
||||
"native": {
|
||||
"name": "native",
|
||||
"browser": "Chrome 60.0.3112 (Windows 7 0.0.0)",
|
||||
"suite": "escape-long",
|
||||
"hz": 295579.48427316535,
|
||||
"success": true,
|
||||
"fastest": true,
|
||||
"rme": 0.01035041406915358,
|
||||
"rhz": 1,
|
||||
"sampleSize": 171
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type * as Rolldown from 'rolldown'
|
||||
|
||||
export * from 'rolldown'
|
||||
|
||||
/** @deprecated use RolldownBuild instead */
|
||||
export type RollupBuild = Rolldown.RolldownBuild
|
||||
|
||||
/** @deprecated use RolldownOptions instead */
|
||||
export type RollupOptions = Rolldown.RolldownOptions
|
||||
|
||||
/** @deprecated use RolldownOutput instead */
|
||||
export type RollupOutput = Rolldown.RolldownOutput
|
||||
|
||||
/** @deprecated use RolldownPlugin instead */
|
||||
export type RollupPlugin = Rolldown.RolldownPlugin
|
||||
|
||||
/** @deprecated use RolldownPluginOption instead */
|
||||
export type RollupPluginOption = Rolldown.RolldownPluginOption
|
||||
|
||||
/** @deprecated use RolldownWatcher instead */
|
||||
export type RollupWatcher = Rolldown.RolldownWatcher
|
||||
|
||||
/** @deprecated use RollupWatcherEvent instead */
|
||||
export type RollupWatcherEvent = Rolldown.RolldownWatcherEvent
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,197 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const util_1 = require("../util");
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-explicit-any',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description: 'Disallow the `any` type',
|
||||
recommended: 'recommended',
|
||||
},
|
||||
fixable: 'code',
|
||||
hasSuggestions: true,
|
||||
messages: {
|
||||
suggestNever: "Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of.",
|
||||
suggestPropertyKey: 'Use `PropertyKey` instead, this is more explicit than `keyof any`.',
|
||||
suggestUnknown: 'Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct.',
|
||||
unexpectedAny: 'Unexpected any. Specify a different type.',
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
fixToUnknown: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to enable auto-fixing in which the `any` type is converted to the `unknown` type.',
|
||||
},
|
||||
ignoreRestArgs: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to ignore rest parameter arrays.',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
defaultOptions: [
|
||||
{
|
||||
fixToUnknown: false,
|
||||
ignoreRestArgs: false,
|
||||
},
|
||||
],
|
||||
create(context, [{ fixToUnknown, ignoreRestArgs }]) {
|
||||
/**
|
||||
* Checks if the node is an arrow function, function/constructor declaration or function expression
|
||||
* @param node the node to be validated.
|
||||
* @returns true if the node is any kind of function declaration or expression
|
||||
* @private
|
||||
*/
|
||||
function isNodeValidFunction(node) {
|
||||
return [
|
||||
utils_1.AST_NODE_TYPES.ArrowFunctionExpression, // const x = (...args: any[]) => {};
|
||||
utils_1.AST_NODE_TYPES.FunctionDeclaration, // function f(...args: any[]) {}
|
||||
utils_1.AST_NODE_TYPES.FunctionExpression, // const x = function(...args: any[]) {};
|
||||
utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration, // type T = {(...args: any[]): unknown};
|
||||
utils_1.AST_NODE_TYPES.TSConstructorType, // type T = new (...args: any[]) => unknown
|
||||
utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration, // type T = {new (...args: any[]): unknown};
|
||||
utils_1.AST_NODE_TYPES.TSDeclareFunction, // declare function _8(...args: any[]): unknown;
|
||||
utils_1.AST_NODE_TYPES.TSEmptyBodyFunctionExpression, // declare class A { f(...args: any[]): unknown; }
|
||||
utils_1.AST_NODE_TYPES.TSFunctionType, // type T = (...args: any[]) => unknown;
|
||||
utils_1.AST_NODE_TYPES.TSMethodSignature, // type T = {f(...args: any[]): unknown};
|
||||
].includes(node.type);
|
||||
}
|
||||
/**
|
||||
* Checks if the node is a rest element child node of a function
|
||||
* @param node the node to be validated.
|
||||
* @returns true if the node is a rest element child node of a function
|
||||
* @private
|
||||
*/
|
||||
function isNodeRestElementInFunction(node) {
|
||||
return (node.type === utils_1.AST_NODE_TYPES.RestElement &&
|
||||
isNodeValidFunction(node.parent));
|
||||
}
|
||||
/**
|
||||
* Checks if the node is a TSTypeOperator node with a readonly operator
|
||||
* @param node the node to be validated.
|
||||
* @returns true if the node is a TSTypeOperator node with a readonly operator
|
||||
* @private
|
||||
*/
|
||||
function isNodeReadonlyTSTypeOperator(node) {
|
||||
return (node.type === utils_1.AST_NODE_TYPES.TSTypeOperator &&
|
||||
node.operator === 'readonly');
|
||||
}
|
||||
/**
|
||||
* Checks if the node is a TSTypeReference node with an Array identifier
|
||||
* @param node the node to be validated.
|
||||
* @returns true if the node is a TSTypeReference node with an Array identifier
|
||||
* @private
|
||||
*/
|
||||
function isNodeValidArrayTSTypeReference(node) {
|
||||
return (node.type === utils_1.AST_NODE_TYPES.TSTypeReference &&
|
||||
node.typeName.type === utils_1.AST_NODE_TYPES.Identifier &&
|
||||
['Array', 'ReadonlyArray'].includes(node.typeName.name));
|
||||
}
|
||||
/**
|
||||
* Checks if the node is a valid TSTypeOperator or TSTypeReference node
|
||||
* @param node the node to be validated.
|
||||
* @returns true if the node is a valid TSTypeOperator or TSTypeReference node
|
||||
* @private
|
||||
*/
|
||||
function isNodeValidTSType(node) {
|
||||
return (isNodeReadonlyTSTypeOperator(node) ||
|
||||
isNodeValidArrayTSTypeReference(node));
|
||||
}
|
||||
/**
|
||||
* Checks if the great grand-parent node is a RestElement node in a function
|
||||
* @param node the node to be validated.
|
||||
* @returns true if the great grand-parent node is a RestElement node in a function
|
||||
* @private
|
||||
*/
|
||||
function isGreatGrandparentRestElement(node) {
|
||||
return (node.parent?.parent?.parent != null &&
|
||||
isNodeRestElementInFunction(node.parent.parent.parent));
|
||||
}
|
||||
/**
|
||||
* Checks if the great great grand-parent node is a valid RestElement node in a function
|
||||
* @param node the node to be validated.
|
||||
* @returns true if the great great grand-parent node is a valid RestElement node in a function
|
||||
* @private
|
||||
*/
|
||||
function isGreatGreatGrandparentRestElement(node) {
|
||||
return (node.parent?.parent?.parent?.parent != null &&
|
||||
isNodeValidTSType(node.parent.parent) &&
|
||||
isNodeRestElementInFunction(node.parent.parent.parent.parent));
|
||||
}
|
||||
/**
|
||||
* Checks if the great grand-parent or the great great grand-parent node is a RestElement node
|
||||
* @param node the node to be validated.
|
||||
* @returns true if the great grand-parent or the great great grand-parent node is a RestElement node
|
||||
* @private
|
||||
*/
|
||||
function isNodeDescendantOfRestElementInFunction(node) {
|
||||
return (isGreatGrandparentRestElement(node) ||
|
||||
isGreatGreatGrandparentRestElement(node));
|
||||
}
|
||||
/**
|
||||
* Checks if the node is within a keyof any expression
|
||||
* @param node the node to be validated.
|
||||
* @returns true if the node is within a keyof any expression, false otherwise
|
||||
* @private
|
||||
*/
|
||||
function isNodeWithinKeyofAny(node) {
|
||||
return (node.parent.type === utils_1.AST_NODE_TYPES.TSTypeOperator &&
|
||||
node.parent.operator === 'keyof');
|
||||
}
|
||||
/**
|
||||
* Creates a fixer that replaces a keyof any with PropertyKey
|
||||
* @param node the node to be fixed.
|
||||
* @returns a function that will fix the node.
|
||||
* @private
|
||||
*/
|
||||
function createPropertyKeyFixer(node) {
|
||||
return (fixer) => {
|
||||
return fixer.replaceText(node.parent, 'PropertyKey');
|
||||
};
|
||||
}
|
||||
return {
|
||||
TSAnyKeyword(node) {
|
||||
const isKeyofAny = isNodeWithinKeyofAny(node);
|
||||
if (ignoreRestArgs && isNodeDescendantOfRestElementInFunction(node)) {
|
||||
return;
|
||||
}
|
||||
const fixOrSuggest = {
|
||||
fix: null,
|
||||
suggest: isKeyofAny
|
||||
? [
|
||||
{
|
||||
messageId: 'suggestPropertyKey',
|
||||
fix: createPropertyKeyFixer(node),
|
||||
},
|
||||
]
|
||||
: [
|
||||
{
|
||||
messageId: 'suggestUnknown',
|
||||
fix: fixer => fixer.replaceText(node, 'unknown'),
|
||||
},
|
||||
{
|
||||
messageId: 'suggestNever',
|
||||
fix: fixer => fixer.replaceText(node, 'never'),
|
||||
},
|
||||
],
|
||||
};
|
||||
if (fixToUnknown) {
|
||||
fixOrSuggest.fix = isKeyofAny
|
||||
? createPropertyKeyFixer(node)
|
||||
: fixer => fixer.replaceText(node, 'unknown');
|
||||
}
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'unexpectedAny',
|
||||
...fixOrSuggest,
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"main": "../../cjs/_define_enumerable_properties.cjs",
|
||||
"module": "../../esm/_define_enumerable_properties.js"
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { TSESLint } from '@typescript-eslint/utils';
|
||||
export type Options = [
|
||||
{
|
||||
fixMixedExportsWithInlineTypeSpecifier: boolean;
|
||||
}
|
||||
];
|
||||
export type MessageIds = 'multipleExportsAreTypes' | 'singleExportIsType' | 'typeOverValue';
|
||||
declare const _default: TSESLint.RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, TSESLint.RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,15 @@
|
||||
'use strict'
|
||||
|
||||
const test = require('node:test')
|
||||
const assert = require('node:assert')
|
||||
const proxyquire = require('proxyquire')
|
||||
|
||||
test('pino.transport resolves targets in REPL', async () => {
|
||||
// Arrange
|
||||
const transport = proxyquire('../../lib/transport', {
|
||||
'./caller': () => ['node:repl']
|
||||
})
|
||||
|
||||
// Act / Assert
|
||||
assert.doesNotThrow(() => transport({ target: 'pino-pretty' }))
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
export type MessageIds = 'omittingRestParameter' | 'omittingSingleParameter' | 'singleParameterDifference';
|
||||
export type Options = [
|
||||
{
|
||||
ignoreDifferentlyNamedParameters?: boolean;
|
||||
ignoreOverloadsWithDifferentJSDoc?: boolean;
|
||||
}
|
||||
];
|
||||
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"name": "dotenv",
|
||||
"version": "17.4.2",
|
||||
"description": "Loads environment variables from .env file",
|
||||
"main": "lib/main.js",
|
||||
"types": "lib/main.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/main.d.ts",
|
||||
"require": "./lib/main.js",
|
||||
"default": "./lib/main.js"
|
||||
},
|
||||
"./config": "./config.js",
|
||||
"./config.js": "./config.js",
|
||||
"./lib/env-options": "./lib/env-options.js",
|
||||
"./lib/env-options.js": "./lib/env-options.js",
|
||||
"./lib/cli-options": "./lib/cli-options.js",
|
||||
"./lib/cli-options.js": "./lib/cli-options.js",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"scripts": {
|
||||
"dts-check": "tsc --project tests/types/tsconfig.json",
|
||||
"lint": "standard",
|
||||
"pretest": "npm run lint && npm run dts-check",
|
||||
"test": "tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000",
|
||||
"test:coverage": "tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",
|
||||
"prerelease": "npm test",
|
||||
"release": "standard-version"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/motdotla/dotenv.git"
|
||||
},
|
||||
"homepage": "https://github.com/motdotla/dotenv#readme",
|
||||
"funding": "https://dotenvx.com",
|
||||
"keywords": [
|
||||
"dotenv",
|
||||
"env",
|
||||
".env",
|
||||
"environment",
|
||||
"variables",
|
||||
"config",
|
||||
"settings"
|
||||
],
|
||||
"readmeFilename": "README.md",
|
||||
"license": "BSD-2-Clause",
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.11.3",
|
||||
"decache": "^4.6.2",
|
||||
"sinon": "^14.0.1",
|
||||
"standard": "^17.0.0",
|
||||
"standard-version": "^9.5.0",
|
||||
"tap": "^19.2.0",
|
||||
"typescript": "^4.8.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"browser": {
|
||||
"fs": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
Copyright (c) 2013 Kael Zhang <i@kael.me>, contributors
|
||||
http://kael.me/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,224 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const util_1 = require("../util");
|
||||
/**
|
||||
* Check whatever node can be considered as simple
|
||||
* @param node the node to be evaluated.
|
||||
*/
|
||||
function isSimpleType(node) {
|
||||
switch (node.type) {
|
||||
case utils_1.AST_NODE_TYPES.Identifier:
|
||||
case utils_1.AST_NODE_TYPES.TSAnyKeyword:
|
||||
case utils_1.AST_NODE_TYPES.TSBooleanKeyword:
|
||||
case utils_1.AST_NODE_TYPES.TSNeverKeyword:
|
||||
case utils_1.AST_NODE_TYPES.TSNumberKeyword:
|
||||
case utils_1.AST_NODE_TYPES.TSBigIntKeyword:
|
||||
case utils_1.AST_NODE_TYPES.TSObjectKeyword:
|
||||
case utils_1.AST_NODE_TYPES.TSStringKeyword:
|
||||
case utils_1.AST_NODE_TYPES.TSSymbolKeyword:
|
||||
case utils_1.AST_NODE_TYPES.TSUnknownKeyword:
|
||||
case utils_1.AST_NODE_TYPES.TSVoidKeyword:
|
||||
case utils_1.AST_NODE_TYPES.TSNullKeyword:
|
||||
case utils_1.AST_NODE_TYPES.TSArrayType:
|
||||
case utils_1.AST_NODE_TYPES.TSUndefinedKeyword:
|
||||
case utils_1.AST_NODE_TYPES.TSThisType:
|
||||
case utils_1.AST_NODE_TYPES.TSQualifiedName:
|
||||
return true;
|
||||
case utils_1.AST_NODE_TYPES.TSTypeReference:
|
||||
if (node.typeName.type === utils_1.AST_NODE_TYPES.Identifier &&
|
||||
node.typeName.name === 'Array') {
|
||||
if (!node.typeArguments) {
|
||||
return true;
|
||||
}
|
||||
if (node.typeArguments.params.length === 1) {
|
||||
return isSimpleType(node.typeArguments.params[0]);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (node.typeArguments) {
|
||||
return false;
|
||||
}
|
||||
return isSimpleType(node.typeName);
|
||||
}
|
||||
return false;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Check if node needs parentheses
|
||||
* @param node the node to be evaluated.
|
||||
*/
|
||||
function typeNeedsParentheses(node) {
|
||||
switch (node.type) {
|
||||
case utils_1.AST_NODE_TYPES.TSTypeReference:
|
||||
return typeNeedsParentheses(node.typeName);
|
||||
case utils_1.AST_NODE_TYPES.TSUnionType:
|
||||
case utils_1.AST_NODE_TYPES.TSFunctionType:
|
||||
case utils_1.AST_NODE_TYPES.TSIntersectionType:
|
||||
case utils_1.AST_NODE_TYPES.TSTypeOperator:
|
||||
case utils_1.AST_NODE_TYPES.TSInferType:
|
||||
case utils_1.AST_NODE_TYPES.TSConstructorType:
|
||||
case utils_1.AST_NODE_TYPES.TSConditionalType:
|
||||
return true;
|
||||
case utils_1.AST_NODE_TYPES.Identifier:
|
||||
return node.name === 'ReadonlyArray';
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'array-type',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description: 'Require consistently using either `T[]` or `Array<T>` for arrays',
|
||||
recommended: 'stylistic',
|
||||
},
|
||||
fixable: 'code',
|
||||
messages: {
|
||||
errorStringArray: "Array type using '{{className}}<{{type}}>' is forbidden. Use '{{readonlyPrefix}}{{type}}[]' instead.",
|
||||
errorStringArrayReadonly: "Array type using '{{className}}<{{type}}>' is forbidden. Use '{{readonlyPrefix}}{{type}}' instead.",
|
||||
errorStringArraySimple: "Array type using '{{className}}<{{type}}>' is forbidden for simple types. Use '{{readonlyPrefix}}{{type}}[]' instead.",
|
||||
errorStringArraySimpleReadonly: "Array type using '{{className}}<{{type}}>' is forbidden for simple types. Use '{{readonlyPrefix}}{{type}}' instead.",
|
||||
errorStringGeneric: "Array type using '{{readonlyPrefix}}{{type}}[]' is forbidden. Use '{{className}}<{{type}}>' instead.",
|
||||
errorStringGenericSimple: "Array type using '{{readonlyPrefix}}{{type}}[]' is forbidden for non-simple types. Use '{{className}}<{{type}}>' instead.",
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: 'object',
|
||||
$defs: {
|
||||
arrayOption: {
|
||||
type: 'string',
|
||||
enum: ['array', 'generic', 'array-simple'],
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
default: {
|
||||
$ref: '#/items/0/$defs/arrayOption',
|
||||
description: 'The array type expected for mutable cases.',
|
||||
},
|
||||
readonly: {
|
||||
$ref: '#/items/0/$defs/arrayOption',
|
||||
description: 'The array type expected for readonly cases. If omitted, the value for `default` will be used.',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
defaultOptions: [
|
||||
{
|
||||
default: 'array',
|
||||
},
|
||||
],
|
||||
create(context, [options]) {
|
||||
const defaultOption = options.default;
|
||||
const readonlyOption = options.readonly ?? defaultOption;
|
||||
/**
|
||||
* @param node the node to be evaluated.
|
||||
*/
|
||||
function getMessageType(node) {
|
||||
if (isSimpleType(node)) {
|
||||
return context.sourceCode.getText(node);
|
||||
}
|
||||
return 'T';
|
||||
}
|
||||
return {
|
||||
TSArrayType(node) {
|
||||
const isReadonly = node.parent.type === utils_1.AST_NODE_TYPES.TSTypeOperator &&
|
||||
node.parent.operator === 'readonly';
|
||||
const currentOption = isReadonly ? readonlyOption : defaultOption;
|
||||
if (currentOption === 'array' ||
|
||||
(currentOption === 'array-simple' && isSimpleType(node.elementType))) {
|
||||
return;
|
||||
}
|
||||
const messageId = currentOption === 'generic'
|
||||
? 'errorStringGeneric'
|
||||
: 'errorStringGenericSimple';
|
||||
const errorNode = isReadonly ? node.parent : node;
|
||||
context.report({
|
||||
node: errorNode,
|
||||
messageId,
|
||||
data: {
|
||||
type: getMessageType(node.elementType),
|
||||
className: isReadonly ? 'ReadonlyArray' : 'Array',
|
||||
readonlyPrefix: isReadonly ? 'readonly ' : '',
|
||||
},
|
||||
fix(fixer) {
|
||||
const typeNode = node.elementType;
|
||||
const arrayType = isReadonly ? 'ReadonlyArray' : 'Array';
|
||||
return [
|
||||
fixer.replaceTextRange([errorNode.range[0], typeNode.range[0]], `${arrayType}<`),
|
||||
fixer.replaceTextRange([typeNode.range[1], errorNode.range[1]], '>'),
|
||||
];
|
||||
},
|
||||
});
|
||||
},
|
||||
TSTypeReference(node) {
|
||||
if (node.typeName.type !== utils_1.AST_NODE_TYPES.Identifier ||
|
||||
!(node.typeName.name === 'Array' ||
|
||||
node.typeName.name === 'ReadonlyArray' ||
|
||||
node.typeName.name === 'Readonly') ||
|
||||
(node.typeName.name === 'Readonly' &&
|
||||
node.typeArguments?.params[0].type !== utils_1.AST_NODE_TYPES.TSArrayType)) {
|
||||
return;
|
||||
}
|
||||
for (let scope = context.sourceCode.getScope(node); scope.upper; scope = scope.upper) {
|
||||
if (scope.set.has(node.typeName.name)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const isReadonlyWithGenericArrayType = node.typeName.name === 'Readonly' &&
|
||||
node.typeArguments?.params[0].type === utils_1.AST_NODE_TYPES.TSArrayType;
|
||||
const isReadonlyArrayType = node.typeName.name === 'ReadonlyArray' ||
|
||||
isReadonlyWithGenericArrayType;
|
||||
const currentOption = isReadonlyArrayType
|
||||
? readonlyOption
|
||||
: defaultOption;
|
||||
if (currentOption === 'generic') {
|
||||
return;
|
||||
}
|
||||
const readonlyPrefix = isReadonlyArrayType ? 'readonly ' : '';
|
||||
const typeParams = node.typeArguments?.params;
|
||||
const messageId = currentOption === 'array'
|
||||
? isReadonlyWithGenericArrayType
|
||||
? 'errorStringArrayReadonly'
|
||||
: 'errorStringArray'
|
||||
: isReadonlyArrayType && node.typeName.name !== 'ReadonlyArray'
|
||||
? 'errorStringArraySimpleReadonly'
|
||||
: 'errorStringArraySimple';
|
||||
if (!typeParams) {
|
||||
return;
|
||||
}
|
||||
if (typeParams.length !== 1 ||
|
||||
(currentOption === 'array-simple' && !isSimpleType(typeParams[0]))) {
|
||||
return;
|
||||
}
|
||||
const type = typeParams[0];
|
||||
const typeParens = typeNeedsParentheses(type);
|
||||
const parentParens = readonlyPrefix &&
|
||||
node.parent.type === utils_1.AST_NODE_TYPES.TSArrayType &&
|
||||
!(0, util_1.isParenthesized)(node.parent.elementType, context.sourceCode);
|
||||
const start = `${parentParens ? '(' : ''}${readonlyPrefix}${typeParens ? '(' : ''}`;
|
||||
const end = `${typeParens ? ')' : ''}${isReadonlyWithGenericArrayType ? '' : `[]`}${parentParens ? ')' : ''}`;
|
||||
context.report({
|
||||
node,
|
||||
messageId,
|
||||
data: {
|
||||
type: getMessageType(type),
|
||||
className: isReadonlyArrayType ? node.typeName.name : 'Array',
|
||||
readonlyPrefix,
|
||||
},
|
||||
fix(fixer) {
|
||||
return [
|
||||
fixer.replaceTextRange([node.range[0], type.range[0]], start),
|
||||
fixer.replaceTextRange([type.range[1], node.range[1]], end),
|
||||
];
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import { Autocomplete } from './utility'
|
||||
|
||||
/**
|
||||
* The header type declaration of `undici`.
|
||||
*/
|
||||
export type IncomingHttpHeaders = Record<string, string | string[] | undefined>
|
||||
|
||||
/**
|
||||
* The header type declaration of `undici` for outgoing requests.
|
||||
*/
|
||||
export type OutgoingHttpHeaders = Record<string, number | string | string[] | undefined>
|
||||
|
||||
type HeaderNames = Autocomplete<
|
||||
| 'Accept'
|
||||
| 'Accept-CH'
|
||||
| 'Accept-Charset'
|
||||
| 'Accept-Encoding'
|
||||
| 'Accept-Language'
|
||||
| 'Accept-Patch'
|
||||
| 'Accept-Post'
|
||||
| 'Accept-Ranges'
|
||||
| 'Access-Control-Allow-Credentials'
|
||||
| 'Access-Control-Allow-Headers'
|
||||
| 'Access-Control-Allow-Methods'
|
||||
| 'Access-Control-Allow-Origin'
|
||||
| 'Access-Control-Expose-Headers'
|
||||
| 'Access-Control-Max-Age'
|
||||
| 'Access-Control-Request-Headers'
|
||||
| 'Access-Control-Request-Method'
|
||||
| 'Age'
|
||||
| 'Allow'
|
||||
| 'Alt-Svc'
|
||||
| 'Alt-Used'
|
||||
| 'Authorization'
|
||||
| 'Cache-Control'
|
||||
| 'Clear-Site-Data'
|
||||
| 'Connection'
|
||||
| 'Content-Disposition'
|
||||
| 'Content-Encoding'
|
||||
| 'Content-Language'
|
||||
| 'Content-Length'
|
||||
| 'Content-Location'
|
||||
| 'Content-Range'
|
||||
| 'Content-Security-Policy'
|
||||
| 'Content-Security-Policy-Report-Only'
|
||||
| 'Content-Type'
|
||||
| 'Cookie'
|
||||
| 'Cross-Origin-Embedder-Policy'
|
||||
| 'Cross-Origin-Opener-Policy'
|
||||
| 'Cross-Origin-Resource-Policy'
|
||||
| 'Date'
|
||||
| 'Device-Memory'
|
||||
| 'ETag'
|
||||
| 'Expect'
|
||||
| 'Expect-CT'
|
||||
| 'Expires'
|
||||
| 'Forwarded'
|
||||
| 'From'
|
||||
| 'Host'
|
||||
| 'If-Match'
|
||||
| 'If-Modified-Since'
|
||||
| 'If-None-Match'
|
||||
| 'If-Range'
|
||||
| 'If-Unmodified-Since'
|
||||
| 'Keep-Alive'
|
||||
| 'Last-Modified'
|
||||
| 'Link'
|
||||
| 'Location'
|
||||
| 'Max-Forwards'
|
||||
| 'Origin'
|
||||
| 'Permissions-Policy'
|
||||
| 'Priority'
|
||||
| 'Proxy-Authenticate'
|
||||
| 'Proxy-Authorization'
|
||||
| 'Range'
|
||||
| 'Referer'
|
||||
| 'Referrer-Policy'
|
||||
| 'Retry-After'
|
||||
| 'Sec-Fetch-Dest'
|
||||
| 'Sec-Fetch-Mode'
|
||||
| 'Sec-Fetch-Site'
|
||||
| 'Sec-Fetch-User'
|
||||
| 'Sec-Purpose'
|
||||
| 'Sec-WebSocket-Accept'
|
||||
| 'Server'
|
||||
| 'Server-Timing'
|
||||
| 'Service-Worker-Navigation-Preload'
|
||||
| 'Set-Cookie'
|
||||
| 'SourceMap'
|
||||
| 'Strict-Transport-Security'
|
||||
| 'TE'
|
||||
| 'Timing-Allow-Origin'
|
||||
| 'Trailer'
|
||||
| 'Transfer-Encoding'
|
||||
| 'Upgrade'
|
||||
| 'Upgrade-Insecure-Requests'
|
||||
| 'User-Agent'
|
||||
| 'Vary'
|
||||
| 'Via'
|
||||
| 'WWW-Authenticate'
|
||||
| 'X-Content-Type-Options'
|
||||
| 'X-Frame-Options'
|
||||
>
|
||||
|
||||
type IANARegisteredMimeType = Autocomplete<
|
||||
| 'audio/aac'
|
||||
| 'video/x-msvideo'
|
||||
| 'image/avif'
|
||||
| 'video/av1'
|
||||
| 'application/octet-stream'
|
||||
| 'image/bmp'
|
||||
| 'text/css'
|
||||
| 'text/csv'
|
||||
| 'application/vnd.ms-fontobject'
|
||||
| 'application/epub+zip'
|
||||
| 'image/gif'
|
||||
| 'application/gzip'
|
||||
| 'text/html'
|
||||
| 'image/x-icon'
|
||||
| 'text/calendar'
|
||||
| 'image/jpeg'
|
||||
| 'text/javascript'
|
||||
| 'application/json'
|
||||
| 'application/ld+json'
|
||||
| 'audio/x-midi'
|
||||
| 'audio/mpeg'
|
||||
| 'video/mp4'
|
||||
| 'video/mpeg'
|
||||
| 'audio/ogg'
|
||||
| 'video/ogg'
|
||||
| 'application/ogg'
|
||||
| 'audio/opus'
|
||||
| 'font/otf'
|
||||
| 'application/pdf'
|
||||
| 'image/png'
|
||||
| 'application/rtf'
|
||||
| 'image/svg+xml'
|
||||
| 'image/tiff'
|
||||
| 'video/mp2t'
|
||||
| 'font/ttf'
|
||||
| 'text/plain'
|
||||
| 'application/wasm'
|
||||
| 'video/webm'
|
||||
| 'audio/webm'
|
||||
| 'image/webp'
|
||||
| 'font/woff'
|
||||
| 'font/woff2'
|
||||
| 'application/xhtml+xml'
|
||||
| 'application/xml'
|
||||
| 'application/zip'
|
||||
| 'video/3gpp'
|
||||
| 'video/3gpp2'
|
||||
| 'model/gltf+json'
|
||||
| 'model/gltf-binary'
|
||||
>
|
||||
|
||||
type KnownHeaderValues = {
|
||||
'content-type': IANARegisteredMimeType
|
||||
}
|
||||
|
||||
export type HeaderRecord = {
|
||||
[K in HeaderNames | Lowercase<HeaderNames>]?: Lowercase<K> extends keyof KnownHeaderValues
|
||||
? KnownHeaderValues[Lowercase<K>]
|
||||
: string
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
export declare enum CompletionItemKind {
|
||||
Text = 1,
|
||||
Method = 2,
|
||||
Function = 3,
|
||||
Constructor = 4,
|
||||
Field = 5,
|
||||
Variable = 6,
|
||||
Class = 7,
|
||||
Interface = 8,
|
||||
Module = 9,
|
||||
Property = 10,
|
||||
Unit = 11,
|
||||
Value = 12,
|
||||
Enum = 13,
|
||||
Keyword = 14,
|
||||
Snippet = 15,
|
||||
Color = 16,
|
||||
File = 17,
|
||||
Reference = 18,
|
||||
Folder = 19,
|
||||
EnumMember = 20,
|
||||
Constant = 21,
|
||||
Struct = 22,
|
||||
Event = 23,
|
||||
Operator = 24,
|
||||
TypeParameter = 25
|
||||
}
|
||||
//# sourceMappingURL=completionItemKind.enum.d.ts.map
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* @fileoverview Assertion utilities equivalent to the Node.js node:asserts module.
|
||||
* @author Josh Goldberg
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
/**
|
||||
* Throws an error if the input is not truthy.
|
||||
* @param {unknown} value The input that is checked for being truthy.
|
||||
* @param {string} message Message to throw if the input is not truthy.
|
||||
* @returns {void}
|
||||
* @throws {Error} When the condition is not truthy.
|
||||
*/
|
||||
function ok(value, message = "Assertion failed.") {
|
||||
if (!value) {
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ok;
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Deprecated module: moved from curves/abstract/utils.js to curves/utils.js
|
||||
* @module
|
||||
*/
|
||||
import * as u from '../utils.ts';
|
||||
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export type Hex = u.Hex;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export type PrivKey = u.PrivKey;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export type CHash = u.CHash;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export type FHash = u.FHash;
|
||||
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const abytes: typeof u.abytes = u.abytes;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const anumber: typeof u.anumber = u.anumber;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const bytesToHex: typeof u.bytesToHex = u.bytesToHex;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const bytesToUtf8: typeof u.bytesToUtf8 = u.bytesToUtf8;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const concatBytes: typeof u.concatBytes = u.concatBytes;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const hexToBytes: typeof u.hexToBytes = u.hexToBytes;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const isBytes: typeof u.isBytes = u.isBytes;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const randomBytes: typeof u.randomBytes = u.randomBytes;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const utf8ToBytes: typeof u.utf8ToBytes = u.utf8ToBytes;
|
||||
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const abool: typeof u.abool = u.abool;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const numberToHexUnpadded: typeof u.numberToHexUnpadded = u.numberToHexUnpadded;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const hexToNumber: typeof u.hexToNumber = u.hexToNumber;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const bytesToNumberBE: typeof u.bytesToNumberBE = u.bytesToNumberBE;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const bytesToNumberLE: typeof u.bytesToNumberLE = u.bytesToNumberLE;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const numberToBytesBE: typeof u.numberToBytesBE = u.numberToBytesBE;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const numberToBytesLE: typeof u.numberToBytesLE = u.numberToBytesLE;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const numberToVarBytesBE: typeof u.numberToVarBytesBE = u.numberToVarBytesBE;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const ensureBytes: typeof u.ensureBytes = u.ensureBytes;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const equalBytes: typeof u.equalBytes = u.equalBytes;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const copyBytes: typeof u.copyBytes = u.copyBytes;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const asciiToBytes: typeof u.asciiToBytes = u.asciiToBytes;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const inRange: typeof u.inRange = u.inRange;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const aInRange: typeof u.aInRange = u.aInRange;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const bitLen: typeof u.bitLen = u.bitLen;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const bitGet: typeof u.bitGet = u.bitGet;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const bitSet: typeof u.bitSet = u.bitSet;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const bitMask: typeof u.bitMask = u.bitMask;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const createHmacDrbg: typeof u.createHmacDrbg = u.createHmacDrbg;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const notImplemented: typeof u.notImplemented = u.notImplemented;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const memoized: typeof u.memoized = u.memoized;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const validateObject: typeof u.validateObject = u.validateObject;
|
||||
/** @deprecated moved to `@noble/curves/utils.js` */
|
||||
export const isHash: typeof u.isHash = u.isHash;
|
||||
Reference in New Issue
Block a user