WIP: bootstrap and partial real Solana watcher implementation

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

View File

@@ -0,0 +1,59 @@
'use strict';
module.exports = function (data, opts) {
if (!opts) opts = {};
if (typeof opts === 'function') opts = { cmp: opts };
var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
var cmp = opts.cmp && (function (f) {
return function (node) {
return function (a, b) {
var aobj = { key: a, value: node[a] };
var bobj = { key: b, value: node[b] };
return f(aobj, bobj);
};
};
})(opts.cmp);
var seen = [];
return (function stringify (node) {
if (node && node.toJSON && typeof node.toJSON === 'function') {
node = node.toJSON();
}
if (node === undefined) return;
if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
if (typeof node !== 'object') return JSON.stringify(node);
var i, out;
if (Array.isArray(node)) {
out = '[';
for (i = 0; i < node.length; i++) {
if (i) out += ',';
out += stringify(node[i]) || 'null';
}
return out + ']';
}
if (node === null) return 'null';
if (seen.indexOf(node) !== -1) {
if (cycles) return JSON.stringify('__cycle__');
throw new TypeError('Converting circular structure to JSON');
}
var seenIndex = seen.push(node) - 1;
var keys = Object.keys(node).sort(cmp && cmp(node));
out = '';
for (i = 0; i < keys.length; i++) {
var key = keys[i];
var value = stringify(node[key]);
if (!value) continue;
if (out) out += ',';
out += JSON.stringify(key) + ':' + value;
}
seen.splice(seenIndex, 1);
return '{' + out + '}';
})(data);
};

View File

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

View File

@@ -0,0 +1,106 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
test("z.stringbool", () => {
const a = z.stringbool();
type a = z.infer<typeof a>;
expectTypeOf<a>().toEqualTypeOf<boolean>();
type a_in = z.input<typeof a>;
expectTypeOf<a_in>().toEqualTypeOf<string>();
expect(z.parse(a, "true")).toEqual(true);
expect(z.parse(a, "yes")).toEqual(true);
expect(z.parse(a, "1")).toEqual(true);
expect(z.parse(a, "on")).toEqual(true);
expect(z.parse(a, "y")).toEqual(true);
expect(z.parse(a, "enabled")).toEqual(true);
expect(z.parse(a, "TRUE")).toEqual(true);
expect(z.parse(a, "false")).toEqual(false);
expect(z.parse(a, "no")).toEqual(false);
expect(z.parse(a, "0")).toEqual(false);
expect(z.parse(a, "off")).toEqual(false);
expect(z.parse(a, "n")).toEqual(false);
expect(z.parse(a, "disabled")).toEqual(false);
expect(z.parse(a, "FALSE")).toEqual(false);
expect(z.safeParse(a, "other")).toMatchObject({ success: false });
expect(z.safeParse(a, "")).toMatchObject({ success: false });
expect(z.safeParse(a, undefined)).toMatchObject({ success: false });
expect(z.safeParse(a, {})).toMatchObject({ success: false });
expect(z.safeParse(a, true)).toMatchObject({ success: false });
expect(z.safeParse(a, false)).toMatchObject({ success: false });
});
test("custom values", () => {
const b = z.stringbool({
truthy: ["y"],
falsy: ["N"],
});
expect(z.parse(b, "y")).toEqual(true);
expect(z.parse(b, "Y")).toEqual(true);
expect(z.parse(b, "n")).toEqual(false);
expect(z.parse(b, "N")).toEqual(false);
expect(z.safeParse(b, "true")).toMatchObject({ success: false });
expect(z.safeParse(b, "false")).toMatchObject({ success: false });
});
test("custom values - case sensitive", () => {
const c = z.stringbool({
truthy: ["y"],
falsy: ["N"],
case: "sensitive",
});
expect(z.parse(c, "y")).toEqual(true);
expect(z.safeParse(c, "Y")).toMatchObject({ success: false });
expect(z.parse(c, "N")).toEqual(false);
expect(z.safeParse(c, "n")).toMatchObject({ success: false });
expect(z.safeParse(c, "TRUE")).toMatchObject({ success: false });
});
// test custom error messages
test("z.stringbool with custom error messages", () => {
const a = z.stringbool("wrong!");
expect(() => a.parse("")).toThrowError("wrong!");
});
test("z.stringbool codec encoding", () => {
const schema = z.stringbool();
// Test encoding with default values
expect(z.encode(schema, true)).toEqual("true");
expect(z.encode(schema, false)).toEqual("false");
});
test("z.stringbool codec encoding with custom values", () => {
const schema = z.stringbool({
truthy: ["yes", "on", "1"],
falsy: ["no", "off", "0"],
});
// Should return first element of custom arrays
expect(z.encode(schema, true)).toEqual("yes");
expect(z.encode(schema, false)).toEqual("no");
});
test("z.stringbool codec round trip", () => {
const schema = z.stringbool({
truthy: ["enabled", "active"],
falsy: ["disabled", "inactive"],
});
// Test round trip: string -> boolean -> string
const decoded = z.decode(schema, "enabled");
expect(decoded).toEqual(true);
const encoded = z.encode(schema, decoded);
expect(encoded).toEqual("enabled"); // First element of truthy array
// Test with falsy value
const decodedFalse = z.decode(schema, "inactive");
expect(decodedFalse).toEqual(false);
const encodedFalse = z.encode(schema, decodedFalse);
expect(encodedFalse).toEqual("disabled"); // First element of falsy array
});

View File

@@ -0,0 +1,67 @@
{
"name": "pino-pretty",
"version": "13.1.3",
"description": "Prettifier for Pino log lines",
"type": "commonjs",
"main": "index.js",
"types": "index.d.ts",
"bin": {
"pino-pretty": "./bin.js"
},
"scripts": {
"ci": "eslint && borp --check-coverage && npm run test-types",
"lint": "eslint",
"lint:fix": "eslint --fix",
"test": "borp",
"test-types": "tsc && tsd && attw --pack .",
"test:watch": "borp -w --reporter gh",
"test:report": "c8 --reporter html borp"
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/pinojs/pino-pretty.git"
},
"keywords": [
"pino"
],
"author": "James Sumners <james.sumners@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/pinojs/pino-pretty/issues"
},
"homepage": "https://github.com/pinojs/pino-pretty#readme",
"dependencies": {
"colorette": "^2.0.7",
"dateformat": "^4.6.3",
"fast-copy": "^4.0.0",
"fast-safe-stringify": "^2.1.1",
"help-me": "^5.0.0",
"joycon": "^3.1.1",
"minimist": "^1.2.6",
"on-exit-leak-free": "^2.1.0",
"pino-abstract-transport": "^3.0.0",
"pump": "^3.0.0",
"secure-json-parse": "^4.0.0",
"sonic-boom": "^4.0.1",
"strip-json-comments": "^5.0.2"
},
"devDependencies": {
"@arethetypeswrong/cli": "^0.18.1",
"@jsumners/assert-match": "^1.0.0",
"@jsumners/line-reporter": "^1.0.1",
"@types/node": "^24.0.8",
"borp": "^0.21.0",
"eslint": "^9.37.0",
"fastbench": "^1.0.1",
"neostandard": "^0.12.2",
"pino": "^10.1.0",
"rimraf": "^6.0.1",
"semver": "^7.6.0",
"tap": "^16.0.0",
"tsd": "^0.33.0",
"typescript": "~5.9.2"
},
"tsd": {
"directory": "./test/types"
}
}

View File

@@ -0,0 +1,102 @@
{
"name": "@vitest/utils",
"type": "module",
"version": "4.1.10",
"description": "Shared Vitest utility functions",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/utils",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
"directory": "packages/utils"
},
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./diff": {
"types": "./dist/diff.d.ts",
"default": "./dist/diff.js"
},
"./resolver": {
"types": "./dist/resolver.d.ts",
"default": "./dist/resolver.js"
},
"./error": {
"types": "./dist/error.d.ts",
"default": "./dist/error.js"
},
"./helpers": {
"types": "./dist/helpers.d.ts",
"default": "./dist/helpers.js"
},
"./offset": {
"types": "./dist/offset.d.ts",
"default": "./dist/offset.js"
},
"./constants": {
"types": "./dist/constants.d.ts",
"default": "./dist/constants.js"
},
"./timers": {
"types": "./dist/timers.d.ts",
"default": "./dist/timers.js"
},
"./display": {
"types": "./dist/display.d.ts",
"default": "./dist/display.js"
},
"./source-map": {
"types": "./dist/source-map.d.ts",
"default": "./dist/source-map.js"
},
"./source-map/node": {
"types": "./dist/source-map/node.d.ts",
"default": "./dist/source-map/node.js"
},
"./serialize": {
"types": "./dist/serialize.d.ts",
"default": "./dist/serialize.js"
},
"./*": "./*"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"typesVersions": {
"*": {
"source-map": [
"dist/source-map.d.ts"
],
"source-map/node": [
"dist/source-map/node.d.ts"
]
}
},
"files": [
"*.d.ts",
"dist"
],
"dependencies": {
"convert-source-map": "^2.0.0",
"tinyrainbow": "^3.1.0",
"@vitest/pretty-format": "4.1.10"
},
"devDependencies": {
"@jridgewell/trace-mapping": "0.3.31",
"@types/convert-source-map": "^2.0.3",
"@types/estree": "^1.0.8",
"diff-sequences": "^29.6.3",
"loupe": "^3.2.1"
},
"scripts": {
"build": "premove dist && rollup -c",
"dev": "rollup -c --watch"
}
}

View File

@@ -0,0 +1,56 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getImportClausePhaseModifier = getImportClausePhaseModifier;
const ts = __importStar(require("typescript"));
const version_check_1 = require("./version-check");
const isAtLeast59 = version_check_1.typescriptVersionIsAtLeast['5.9'];
// TODO: Remove when we support TS >= 5.9
function getImportClausePhaseModifier(node) {
if (!node) {
return null;
}
if (isAtLeast59) {
// eslint-disable-next-line @typescript-eslint/no-deprecated -- guarded by TS version check.
return node.phaseModifier === ts.SyntaxKind.TypeKeyword
? 'type'
: // eslint-disable-next-line @typescript-eslint/no-deprecated -- guarded by TS version check
node.phaseModifier === ts.SyntaxKind.DeferKeyword
? 'defer'
: null;
}
// eslint-disable-next-line @typescript-eslint/no-deprecated -- guarded by TS version check
return node.isTypeOnly ? 'type' : null;
}

View File

@@ -0,0 +1,104 @@
"use strict";
//binary data writer tuned for encoding binary specific to the postgres binary protocol
Object.defineProperty(exports, "__esModule", { value: true });
exports.Writer = void 0;
class Writer {
constructor(size = 256) {
this.size = size;
this.offset = 5;
this.headerPosition = 0;
this.buffer = Buffer.allocUnsafe(size);
}
ensure(size) {
const remaining = this.buffer.length - this.offset;
if (remaining < size) {
const oldBuffer = this.buffer;
// exponential growth factor of around ~ 1.5
// https://stackoverflow.com/questions/2269063/buffer-growth-strategy
const newSize = oldBuffer.length + (oldBuffer.length >> 1) + size;
this.buffer = Buffer.allocUnsafe(newSize);
oldBuffer.copy(this.buffer);
}
}
addInt32(num) {
this.ensure(4);
this.buffer[this.offset++] = (num >>> 24) & 0xff;
this.buffer[this.offset++] = (num >>> 16) & 0xff;
this.buffer[this.offset++] = (num >>> 8) & 0xff;
this.buffer[this.offset++] = (num >>> 0) & 0xff;
return this;
}
addInt16(num) {
this.ensure(2);
this.buffer[this.offset++] = (num >>> 8) & 0xff;
this.buffer[this.offset++] = (num >>> 0) & 0xff;
return this;
}
addCString(string) {
if (!string) {
this.ensure(1);
}
else {
const len = Buffer.byteLength(string);
this.ensure(len + 1); // +1 for null terminator
this.buffer.write(string, this.offset, 'utf-8');
this.offset += len;
}
this.buffer[this.offset++] = 0; // null terminator
return this;
}
addString(string = '') {
const len = Buffer.byteLength(string);
this.ensure(len);
this.buffer.write(string, this.offset);
this.offset += len;
return this;
}
// Write an Int32 byte-length prefix immediately followed by the string's UTF-8
// bytes. Postgres' Bind wire format prefixes every parameter with its length,
// and doing it in one method computes Buffer.byteLength ONCE — the previous
// `addInt32(Buffer.byteLength(s)).addString(s)` pairing scanned the string
// three times (byteLength for the prefix, byteLength again inside addString,
// then the encode), which is costly for large text parameters.
addInt32PrefixedString(string) {
const len = Buffer.byteLength(string);
this.ensure(4 + len);
const buffer = this.buffer;
let offset = this.offset;
buffer[offset++] = (len >>> 24) & 0xff;
buffer[offset++] = (len >>> 16) & 0xff;
buffer[offset++] = (len >>> 8) & 0xff;
buffer[offset++] = (len >>> 0) & 0xff;
buffer.write(string, offset, 'utf-8');
this.offset = offset + len;
return this;
}
add(otherBuffer) {
this.ensure(otherBuffer.length);
otherBuffer.copy(this.buffer, this.offset);
this.offset += otherBuffer.length;
return this;
}
join(code) {
if (code) {
this.buffer[this.headerPosition] = code;
//length is everything in this packet minus the code
const length = this.offset - (this.headerPosition + 1);
this.buffer.writeInt32BE(length, this.headerPosition + 1);
}
return this.buffer.slice(code ? 0 : 5, this.offset);
}
flush(code) {
const result = this.join(code);
this.offset = 5;
this.headerPosition = 0;
this.buffer = Buffer.allocUnsafe(this.size);
return result;
}
clear() {
this.offset = 5;
this.headerPosition = 0;
}
}
exports.Writer = Writer;
//# sourceMappingURL=buffer-writer.js.map

View File

@@ -0,0 +1,38 @@
{
"name": "commander",
"version": "2.20.3",
"description": "the complete solution for node.js command-line programs",
"keywords": [
"commander",
"command",
"option",
"parser"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/tj/commander.js.git"
},
"scripts": {
"lint": "eslint index.js",
"test": "node test/run.js && npm run test-typings",
"test-typings": "tsc -p tsconfig.json"
},
"main": "index",
"files": [
"index.js",
"typings/index.d.ts"
],
"dependencies": {},
"devDependencies": {
"@types/node": "^12.7.8",
"eslint": "^6.4.0",
"should": "^13.2.3",
"sinon": "^7.5.0",
"standard": "^14.3.1",
"ts-node": "^8.4.1",
"typescript": "^3.6.3"
},
"typings": "typings/index.d.ts"
}

View File

@@ -0,0 +1,12 @@
import { _ as _class_apply_descriptor_set } from "./_class_apply_descriptor_set.js";
import { _ as _class_check_private_static_access } from "./_class_check_private_static_access.js";
import { _ as _class_check_private_static_field_descriptor } from "./_class_check_private_static_field_descriptor.js";
function _class_static_private_field_spec_set(receiver, classConstructor, descriptor, value) {
_class_check_private_static_access(receiver, classConstructor);
_class_check_private_static_field_descriptor(descriptor, "set");
_class_apply_descriptor_set(receiver, descriptor, value);
return value;
}
export { _class_static_private_field_spec_set as _ };

View File

@@ -0,0 +1 @@
export { _ as default } from "../esm/_class_private_field_get.js";

View File

@@ -0,0 +1,30 @@
/// <reference types="node" />
import type { Headers } from './fetch'
export interface Cookie {
name: string
value: string
expires?: Date | number
maxAge?: number
domain?: string
path?: string
secure?: boolean
httpOnly?: boolean
sameSite?: 'Strict' | 'Lax' | 'None'
unparsed?: string[]
}
export function deleteCookie (
headers: Headers,
name: string,
attributes?: { name?: string, domain?: string }
): void
export function getCookies (headers: Headers): Record<string, string>
export function getSetCookies (headers: Headers): Cookie[]
export function setCookie (headers: Headers, cookie: Cookie): void
export function parseCookie (cookie: string): Cookie | null

View File

@@ -0,0 +1,68 @@
<p align=center>
AssertionError and AssertionResult classes.
</p>
<p align=center>
<a href="https://github.com/chaijs/assertion-error/actions">
<img
alt="build:?"
src="https://github.com/chaijs/assertion-error/actions/workflows/nodejs.yml/badge.svg"
/>
</a><a href="https://www.npmjs.com/package/assertion-error">
<img
alt="downloads:?"
src="https://img.shields.io/npm/dm/assertion-error.svg"
/>
</a><a href="">
<img
alt="devDependencies:none"
src="https://img.shields.io/badge/dependencies-none-brightgreen"
/>
</a>
</p>
## What is AssertionError?
Assertion Error is a module that contains two classes: `AssertionError`, which
is an instance of an `Error`, and `AssertionResult` which is not an instance of
Error.
These can be useful for returning from a function - if the function "succeeds"
return an `AssertionResult` and if the function fails return (or throw) an
`AssertionError`.
Both `AssertionError` and `AssertionResult` implement the `Result` interface:
```typescript
interface Result {
name: "AssertionError" | "AssertionResult";
ok: boolean;
toJSON(...args: unknown[]): Record<string, unknown>;
}
```
So if a function returns `AssertionResult | AssertionError` it is easy to check
_which_ one is returned by checking either `.name` or `.ok`, or check
`instanceof Error`.
## Installation
### Node.js
`assertion-error` is available on [npm](http://npmjs.org).
```
$ npm install --save assertion-error
```
### Deno
`assertion_error` is available on
[Deno.land](https://deno.land/x/assertion_error)
```typescript
import {
AssertionError,
AssertionResult,
} from "https://deno.land/x/assertion_error@2.0.0/mod.ts";
```

View File

@@ -0,0 +1,29 @@
# ESLint Core
## Overview
This package is the future home of the rewritten, runtime-agnostic ESLint core.
Right now, it exports the core types necessary to implement language plugins.
## License
Apache 2.0
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/d472863/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/2d6c3b6/logo.png" alt="Liftoff" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://opensource.sap.com"><img src="https://avatars.githubusercontent.com/u/2531208" alt="SAP" height="32"></a> <a href="https://www.crawljobs.com/"><img src="https://images.opencollective.com/crawljobs-poland/fa43a17/logo.png" alt="CrawlJobs" height="32"></a> <a href="#"><img src="https://images.opencollective.com/aeriusventilations-org/avatar.png" alt="aeriusventilation's Org" height="32"></a> <a href="https://depot.dev"><img src="https://images.opencollective.com/depot/39125a1/logo.png" alt="Depot" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="TestMu AI Open Source Office (Formerly LambdaTest)" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->

View File

@@ -0,0 +1,79 @@
import {LoadedAddresses} from '../connection';
import {PublicKey} from '../publickey';
import {TransactionInstruction} from '../transaction';
import {MessageCompiledInstruction} from './index';
export type AccountKeysFromLookups = LoadedAddresses;
export class MessageAccountKeys {
staticAccountKeys: Array<PublicKey>;
accountKeysFromLookups?: AccountKeysFromLookups;
constructor(
staticAccountKeys: Array<PublicKey>,
accountKeysFromLookups?: AccountKeysFromLookups,
) {
this.staticAccountKeys = staticAccountKeys;
this.accountKeysFromLookups = accountKeysFromLookups;
}
keySegments(): Array<Array<PublicKey>> {
const keySegments = [this.staticAccountKeys];
if (this.accountKeysFromLookups) {
keySegments.push(this.accountKeysFromLookups.writable);
keySegments.push(this.accountKeysFromLookups.readonly);
}
return keySegments;
}
get(index: number): PublicKey | undefined {
for (const keySegment of this.keySegments()) {
if (index < keySegment.length) {
return keySegment[index];
} else {
index -= keySegment.length;
}
}
return;
}
get length(): number {
return this.keySegments().flat().length;
}
compileInstructions(
instructions: Array<TransactionInstruction>,
): Array<MessageCompiledInstruction> {
// Bail early if any account indexes would overflow a u8
const U8_MAX = 255;
if (this.length > U8_MAX + 1) {
throw new Error('Account index overflow encountered during compilation');
}
const keyIndexMap = new Map();
this.keySegments()
.flat()
.forEach((key, index) => {
keyIndexMap.set(key.toBase58(), index);
});
const findKeyIndex = (key: PublicKey) => {
const keyIndex = keyIndexMap.get(key.toBase58());
if (keyIndex === undefined)
throw new Error(
'Encountered an unknown instruction account key during compilation',
);
return keyIndex;
};
return instructions.map((instruction): MessageCompiledInstruction => {
return {
programIdIndex: findKeyIndex(instruction.programId),
accountKeyIndexes: instruction.keys.map(meta =>
findKeyIndex(meta.pubkey),
),
data: instruction.data,
};
});
}
}

View File

@@ -0,0 +1,148 @@
import { pctEncChar, pctDecChars, unescapeComponent } from "../uri";
import punycode from "punycode";
import { merge, subexp, toUpperCase, toArray } from "../util";
const O = {};
const isIRI = true;
//RFC 3986
const UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]";
const HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive
const PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded
//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =
//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]";
//const WSP$$ = "[\\x20\\x09]";
//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127)
//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext
//const VCHAR$$ = "[\\x21-\\x7E]";
//const WSP$$ = "[\\x20\\x09]";
//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext
//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+");
//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$);
//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"');
const ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
const QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
const VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]");
const DOT_ATOM_TEXT$ = subexp(ATEXT$$ + "+" + subexp("\\." + ATEXT$$ + "+") + "*");
const QUOTED_PAIR$ = subexp("\\\\" + VCHAR$$);
const QCONTENT$ = subexp(QTEXT$$ + "|" + QUOTED_PAIR$);
const QUOTED_STRING$ = subexp('\\"' + QCONTENT$ + "*" + '\\"');
//RFC 6068
const DTEXT_NO_OBS$$ = "[\\x21-\\x5A\\x5E-\\x7E]"; //%d33-90 / %d94-126
const SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
const QCHAR$ = subexp(UNRESERVED$$ + "|" + PCT_ENCODED$ + "|" + SOME_DELIMS$$);
const DOMAIN$ = subexp(DOT_ATOM_TEXT$ + "|" + "\\[" + DTEXT_NO_OBS$$ + "*" + "\\]");
const LOCAL_PART$ = subexp(DOT_ATOM_TEXT$ + "|" + QUOTED_STRING$);
const ADDR_SPEC$ = subexp(LOCAL_PART$ + "\\@" + DOMAIN$);
const TO$ = subexp(ADDR_SPEC$ + subexp("\\," + ADDR_SPEC$) + "*");
const HFNAME$ = subexp(QCHAR$ + "*");
const HFVALUE$ = HFNAME$;
const HFIELD$ = subexp(HFNAME$ + "\\=" + HFVALUE$);
const HFIELDS2$ = subexp(HFIELD$ + subexp("\\&" + HFIELD$) + "*");
const HFIELDS$ = subexp("\\?" + HFIELDS2$);
const MAILTO_URI = new RegExp("^mailto\\:" + TO$ + "?" + HFIELDS$ + "?$");
const UNRESERVED = new RegExp(UNRESERVED$$, "g");
const PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
const NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
const NOT_DOMAIN = new RegExp(merge("[^]", ATEXT$$, "[\\.]", "[\\[]", DTEXT_NO_OBS$$, "[\\]]"), "g");
const NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
const NOT_HFVALUE = NOT_HFNAME;
const TO = new RegExp("^" + TO$ + "$");
const HFIELDS = new RegExp("^" + HFIELDS2$ + "$");
function decodeUnreserved(str) {
const decStr = pctDecChars(str);
return (!decStr.match(UNRESERVED) ? str : decStr);
}
const handler = {
scheme: "mailto",
parse: function (components, options) {
const mailtoComponents = components;
const to = mailtoComponents.to = (mailtoComponents.path ? mailtoComponents.path.split(",") : []);
mailtoComponents.path = undefined;
if (mailtoComponents.query) {
let unknownHeaders = false;
const headers = {};
const hfields = mailtoComponents.query.split("&");
for (let x = 0, xl = hfields.length; x < xl; ++x) {
const hfield = hfields[x].split("=");
switch (hfield[0]) {
case "to":
const toAddrs = hfield[1].split(",");
for (let x = 0, xl = toAddrs.length; x < xl; ++x) {
to.push(toAddrs[x]);
}
break;
case "subject":
mailtoComponents.subject = unescapeComponent(hfield[1], options);
break;
case "body":
mailtoComponents.body = unescapeComponent(hfield[1], options);
break;
default:
unknownHeaders = true;
headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);
break;
}
}
if (unknownHeaders)
mailtoComponents.headers = headers;
}
mailtoComponents.query = undefined;
for (let x = 0, xl = to.length; x < xl; ++x) {
const addr = to[x].split("@");
addr[0] = unescapeComponent(addr[0]);
if (!options.unicodeSupport) {
//convert Unicode IDN -> ASCII IDN
try {
addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());
}
catch (e) {
mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e;
}
}
else {
addr[1] = unescapeComponent(addr[1], options).toLowerCase();
}
to[x] = addr.join("@");
}
return mailtoComponents;
},
serialize: function (mailtoComponents, options) {
const components = mailtoComponents;
const to = toArray(mailtoComponents.to);
if (to) {
for (let x = 0, xl = to.length; x < xl; ++x) {
const toAddr = String(to[x]);
const atIdx = toAddr.lastIndexOf("@");
const localPart = (toAddr.slice(0, atIdx)).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
let domain = toAddr.slice(atIdx + 1);
//convert IDN via punycode
try {
domain = (!options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain));
}
catch (e) {
components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
}
to[x] = localPart + "@" + domain;
}
components.path = to.join(",");
}
const headers = mailtoComponents.headers = mailtoComponents.headers || {};
if (mailtoComponents.subject)
headers["subject"] = mailtoComponents.subject;
if (mailtoComponents.body)
headers["body"] = mailtoComponents.body;
const fields = [];
for (const name in headers) {
if (headers[name] !== O[name]) {
fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) +
"=" +
headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
}
}
if (fields.length) {
components.query = fields.join("&");
}
return components;
}
};
export default handler;
//# sourceMappingURL=mailto.js.map

View File

@@ -0,0 +1,62 @@
{
"name": "@eslint/object-schema",
"version": "3.0.5",
"description": "An object schema merger/validator",
"type": "module",
"main": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
"exports": {
"require": {
"types": "./dist/cjs/index.d.cts",
"default": "./dist/cjs/index.cjs"
},
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
}
},
"files": [
"dist"
],
"publishConfig": {
"access": "public"
},
"directories": {
"test": "tests"
},
"scripts": {
"build:dedupe-types": "node ../../tools/dedupe-types.js dist/cjs/index.cjs dist/esm/index.js",
"build:cts": "node ../../tools/build-cts.js dist/esm/index.d.ts dist/cjs/index.d.cts",
"build": "rollup -c && npm run build:dedupe-types && tsc -p tsconfig.esm.json && npm run build:cts",
"lint:types": "attw --pack",
"pretest": "npm run build",
"test": "npm run test:types && npm run test:unit",
"test:coverage": "c8 npm run test:unit",
"test:jsr": "npx -y jsr@latest publish --dry-run",
"test:types": "tsc -p tests/types/tsconfig.json",
"test:unit": "mocha \"tests/**/*.test.js\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/eslint/rewrite.git",
"directory": "packages/object-schema"
},
"keywords": [
"object",
"validation",
"schema",
"merge"
],
"author": "Nicholas C. Zakas",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/eslint/rewrite/issues"
},
"homepage": "https://github.com/eslint/rewrite/tree/main/packages/object-schema#readme",
"devDependencies": {
"rollup-plugin-copy": "^3.5.0"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=24"
}
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"sha1.js","sourceRoot":"","sources":["src/sha1.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,2CAA2D;AAC3D,+DAA+D;AAClD,QAAA,IAAI,GAAiB,gBAAK,CAAC;AACxC,+DAA+D;AAClD,QAAA,IAAI,GAAiB,gBAAK,CAAC"}

View File

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

View File

@@ -0,0 +1,18 @@
# Contributing
Please feel free to file GitHub Issues or propose Pull Requests. We're always happy to discuss improvements to this library!
## Testing
```shell
npm test
```
## Releasing
Releases are supposed to be done from master, version bumping is automated through [`standard-version`](https://github.com/conventional-changelog/standard-version):
```shell
npm run release -- --dry-run # verify output manually
npm run release # follow the instructions from the output of this command
```

View File

@@ -0,0 +1 @@
{"version":3,"file":"typeFlags.enum.js","sourceRoot":"","sources":["../../src/enums/typeFlags.enum.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAE/F,MAAM,CAAN,IAA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/D,yFAAwD,CAAA;IACxD,uEAAwE,CAAA;IACxE,iEAAkD,CAAA;IAClD,wDAA0H,CAAA;IAC1H,6DAAqJ,CAAA;IACrJ,iEAAiI,CAAA;IACjI,4EAAmC,CAAA;IACnC,qFAA+B,CAAA;IAC/B,wEAAgC,CAAA;IAChC,8EAAiC,CAAA;IACjC,gFAAmC,CAAA;IACnC,uGAA2C,CAAA;IAC3C,oEAAyB,CAAA;IACzB,2EAA+F,CAAA;AACnG,CAAC,EA1EW,SAAS,KAAT,SAAS,QA0EpB"}

View File

@@ -0,0 +1,77 @@
{
"name": "word-wrap",
"description": "Wrap words to a specified length.",
"version": "1.2.5",
"homepage": "https://github.com/jonschlinkert/word-wrap",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"contributors": [
"Danilo Sampaio <danilo.sampaio@gmail.com> (localhost:8080)",
"Fede Ramirez <i@2fd.me> (https://2fd.github.io)",
"Joe Hildebrand <joe-github@cursive.net> (https://twitter.com/hildjj)",
"Jon Schlinkert <jon.schlinkert@sellside.com> (http://twitter.com/jonschlinkert)",
"Todd Kennedy (https://tck.io)",
"Waldemar Reusch (https://github.com/lordvlad)",
"Wolfgang Faust (http://www.linestarve.com)",
"Zach Hale <zachhale@gmail.com> (http://zachhale.com)"
],
"repository": "jonschlinkert/word-wrap",
"bugs": {
"url": "https://github.com/jonschlinkert/word-wrap/issues"
},
"license": "MIT",
"files": [
"index.js",
"index.d.ts"
],
"main": "index.js",
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
},
"devDependencies": {
"gulp-format-md": "^0.1.11",
"mocha": "^3.2.0"
},
"keywords": [
"break",
"carriage",
"line",
"new-line",
"newline",
"return",
"soft",
"text",
"word",
"word-wrap",
"words",
"wrap"
],
"typings": "index.d.ts",
"verb": {
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"lint": {
"reflinks": true
},
"related": {
"list": [
"common-words",
"shuffle-words",
"unique-words",
"wordcount"
]
},
"reflinks": [
"verb",
"verb-generate-readme"
]
}
}

View File

@@ -0,0 +1,69 @@
'use strict'
module.exports = buildSafeSonicBoom
const { isMainThread } = require('node:worker_threads')
const SonicBoom = require('sonic-boom')
const noop = require('./noop')
/**
* Creates a safe SonicBoom instance
*
* @param {object} opts Options for SonicBoom
*
* @returns {object} A new SonicBoom stream
*/
function buildSafeSonicBoom (opts) {
const stream = new SonicBoom(opts)
stream.on('error', filterBrokenPipe)
// if we are sync: false, we must flush on exit
if (!opts.sync && isMainThread) {
setupOnExit(stream)
}
return stream
function filterBrokenPipe (err) {
if (err.code === 'EPIPE') {
stream.write = noop
stream.end = noop
stream.flushSync = noop
stream.destroy = noop
return
}
stream.removeListener('error', filterBrokenPipe)
}
}
function setupOnExit (stream) {
/* istanbul ignore next */
if (global.WeakRef && global.WeakMap && global.FinalizationRegistry) {
// This is leak free, it does not leave event handlers
const onExit = require('on-exit-leak-free')
onExit.register(stream, autoEnd)
stream.on('close', function () {
onExit.unregister(stream)
})
}
}
/* istanbul ignore next */
function autoEnd (stream, eventName) {
// This check is needed only on some platforms
if (stream.destroyed) {
return
}
if (eventName === 'beforeExit') {
// We still have an event loop, let's use it
stream.flush()
stream.on('drain', function () {
stream.end()
})
} else {
// We do not have an event loop, so flush synchronously
stream.flushSync()
}
}

View File

@@ -0,0 +1,87 @@
import type { FlatConfig } from '../Config';
import type * as Shared from './ESLintShared';
declare class FlatESLintBase extends Shared.ESLintBase<FlatConfig.Config | FlatConfig.ConfigArray, FlatESLint.ESLintOptions> {
static readonly configType: 'flat';
/**
* Returns a configuration object for the given file based on the CLI options.
* This is the same logic used by the ESLint CLI executable to determine
* configuration for each file it processes.
* @param filePath The path of the file to retrieve a config object for.
* @returns A configuration object for the file or `undefined` if there is no configuration data for the object.
*/
calculateConfigForFile(filePath: string): Promise<FlatConfig.Config>;
/**
* Finds the config file being used by this instance based on the options
* passed to the constructor.
* @returns The path to the config file being used or `undefined` if no config file is being used.
*/
findConfigFile(): Promise<string | undefined>;
}
declare const FlatESLint_base: typeof FlatESLintBase;
/**
* The ESLint class is the primary class to use in Node.js applications.
* This class depends on the Node.js fs module and the file system, so you cannot use it in browsers.
*
* If you want to lint code on browsers, use the Linter class instead.
*/
export declare class FlatESLint extends FlatESLint_base {
}
export declare namespace FlatESLint {
interface ESLintOptions extends Shared.ESLintOptions<FlatConfig.ConfigArray> {
/**
* If false is present, the eslint.lintFiles() method doesn't respect `ignorePatterns` ignorePatterns in your configuration.
* @default true
*/
ignore?: boolean;
/**
* Ignore file patterns to use in addition to config ignores. These patterns are relative to cwd.
* @default null
*/
ignorePatterns?: string[] | null;
/**
* The path to a configuration file. Overrides all configurations used with this instance.
* The options.overrideConfig option is applied after this option is applied.
*
* - When falsy, searches for default config file.
* - When `true`, does not do any config file lookup.
* - When a string, considered to be a config file name.
*
* @default false
*/
overrideConfigFile?: boolean | string;
/**
* A predicate function that filters rules to be run.
* This function is called with an object containing `ruleId` and `severity`, and returns `true` if the rule should be run.
* @default () => true
*/
ruleFilter?: RuleFilter;
/**
* When set to true, additional statistics are added to the lint results.
* @see {@link https://eslint.org/docs/latest/extend/stats}
* @default false
*/
stats?: boolean;
/**
* Show warnings when the file list includes ignored files.
* @default true
*/
warnIgnored?: boolean;
}
type DeprecatedRuleInfo = Shared.DeprecatedRuleInfo;
type EditInfo = Shared.EditInfo;
type Formatter = Shared.Formatter;
type LintMessage = Shared.LintMessage;
type LintResult = Shared.LintResult;
type LintStats = Shared.LintStats;
type LintStatsFixTime = Shared.LintStatsFixTime;
type LintStatsParseTime = Shared.LintStatsParseTime;
type LintStatsRuleTime = Shared.LintStatsRuleTime;
type LintStatsTimePass = Shared.LintStatsTimePass;
type LintTextOptions = Shared.LintTextOptions;
type SuppressedLintMessage = Shared.SuppressedLintMessage;
type RuleFilter = (rule: {
ruleId: string;
severity: number;
}) => boolean;
}
export {};

View File

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

View File

@@ -0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AC,EAAE,EAAE,MAAM,CAAkB;IACtC,SAAS,CAAC,EAAE,EAAE,MAAM,CAAkB;IACtC,SAAS,CAAC,EAAE,EAAE,MAAM,CAAkB;IACtC,SAAS,CAAC,EAAE,EAAE,MAAM,CAAmB;IACvC,SAAS,CAAC,EAAE,EAAE,MAAM,CAAmB;IACvC,SAAS,CAAC,EAAE,EAAE,MAAM,CAAmB;IACvC,SAAS,CAAC,EAAE,EAAE,MAAM,CAAmB;IACvC,SAAS,CAAC,EAAE,EAAE,MAAM,CAAmB;IACvC,SAAS,CAAC,EAAE,EAAE,MAAM,CAAmB;;CAKxC;AAED;;;;;;GAMG;AACH,eAAO,MAAM,MAAM,EAAE,KAAwD,CAAC;AAC9E,2CAA2C;AAC3C,eAAO,MAAM,MAAM,EAAE,KAAwD,CAAC;AAE9E,4CAA4C;AAC5C,eAAO,MAAM,MAAM,EAAE,KAAwD,CAAC;AAC9E,4CAA4C;AAC5C,eAAO,MAAM,MAAM,EAAE,KAAwD,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,UAAU,EAAE,KAA4D,CAAC;AACtF;;;GAGG;AACH,eAAO,MAAM,UAAU,EAAE,KAA4D,CAAC"}

View File

@@ -0,0 +1,36 @@
# wrappy
Callback wrapping utility
## USAGE
```javascript
var wrappy = require("wrappy")
// var wrapper = wrappy(wrapperFunction)
// make sure a cb is called only once
// See also: http://npm.im/once for this specific use case
var once = wrappy(function (cb) {
var called = false
return function () {
if (called) return
called = true
return cb.apply(this, arguments)
}
})
function printBoo () {
console.log('boo')
}
// has some rando property
printBoo.iAmBooPrinter = true
var onlyPrintOnce = once(printBoo)
onlyPrintOnce() // prints 'boo'
onlyPrintOnce() // does nothing
// random property is retained!
assert.equal(onlyPrintOnce.iAmBooPrinter, true)
```

View File

@@ -0,0 +1,319 @@
/**
* A class that represents each benchmark task in Tinybench. It keeps track of the
* results, name, Bench instance, the task function and the number times the task
* function has been executed.
*/
declare class Task extends EventTarget {
bench: Bench;
/**
* task name
*/
name: string;
fn: Fn;
runs: number;
/**
* the result object
*/
result?: TaskResult;
/**
* Task options
*/
opts: FnOptions;
constructor(bench: Bench, name: string, fn: Fn, opts?: FnOptions);
private loop;
/**
* run the current task and write the results in `Task.result` object
*/
run(): Promise<this>;
/**
* warmup the current task
*/
warmup(): Promise<void>;
addEventListener<K extends TaskEvents, T = TaskEventsMap[K]>(type: K, listener: T, options?: AddEventListenerOptionsArgument): void;
removeEventListener<K extends TaskEvents, T = TaskEventsMap[K]>(type: K, listener: T, options?: RemoveEventListenerOptionsArgument): void;
/**
* change the result object values
*/
setResult(result: Partial<TaskResult>): void;
/**
* reset the task to make the `Task.runs` a zero-value and remove the `Task.result`
* object
*/
reset(): void;
}
/**
* the task function
*/
type Fn = () => any | Promise<any>;
interface FnOptions {
/**
* An optional function that is run before iterations of this task begin
*/
beforeAll?: (this: Task) => void | Promise<void>;
/**
* An optional function that is run before each iteration of this task
*/
beforeEach?: (this: Task) => void | Promise<void>;
/**
* An optional function that is run after each iteration of this task
*/
afterEach?: (this: Task) => void | Promise<void>;
/**
* An optional function that is run after all iterations of this task end
*/
afterAll?: (this: Task) => void | Promise<void>;
}
/**
* the benchmark task result object
*/
type TaskResult = {
error?: unknown;
/**
* The amount of time in milliseconds to run the benchmark task (cycle).
*/
totalTime: number;
/**
* the minimum value in the samples
*/
min: number;
/**
* the maximum value in the samples
*/
max: number;
/**
* the number of operations per second
*/
hz: number;
/**
* how long each operation takes (ms)
*/
period: number;
/**
* task samples of each task iteration time (ms)
*/
samples: number[];
/**
* samples mean/average (estimate of the population mean)
*/
mean: number;
/**
* samples variance (estimate of the population variance)
*/
variance: number;
/**
* samples standard deviation (estimate of the population standard deviation)
*/
sd: number;
/**
* standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean)
*/
sem: number;
/**
* degrees of freedom
*/
df: number;
/**
* critical value of the samples
*/
critical: number;
/**
* margin of error
*/
moe: number;
/**
* relative margin of error
*/
rme: number;
/**
* p75 percentile
*/
p75: number;
/**
* p99 percentile
*/
p99: number;
/**
* p995 percentile
*/
p995: number;
/**
* p999 percentile
*/
p999: number;
};
/**
* Both the `Task` and `Bench` objects extend the `EventTarget` object,
* so you can attach a listeners to different types of events
* to each class instance using the universal `addEventListener` and
* `removeEventListener`
*/
/**
* Bench events
*/
type BenchEvents = 'abort' | 'complete' | 'error' | 'reset' | 'start' | 'warmup' | 'cycle' | 'add' | 'remove' | 'todo';
type Hook = (task: Task, mode: 'warmup' | 'run') => void | Promise<void>;
type NoopEventListener = () => any | Promise<any>;
type TaskEventListener = (e: Event & {
task: Task;
}) => any | Promise<any>;
interface BenchEventsMap {
abort: NoopEventListener;
start: NoopEventListener;
complete: NoopEventListener;
warmup: NoopEventListener;
reset: NoopEventListener;
add: TaskEventListener;
remove: TaskEventListener;
cycle: TaskEventListener;
error: TaskEventListener;
todo: TaskEventListener;
}
/**
* task events
*/
type TaskEvents = 'abort' | 'complete' | 'error' | 'reset' | 'start' | 'warmup' | 'cycle';
type TaskEventsMap = {
abort: NoopEventListener;
start: TaskEventListener;
error: TaskEventListener;
cycle: TaskEventListener;
complete: TaskEventListener;
warmup: TaskEventListener;
reset: TaskEventListener;
};
type Options = {
/**
* time needed for running a benchmark task (milliseconds) @default 500
*/
time?: number;
/**
* number of times that a task should run if even the time option is finished @default 10
*/
iterations?: number;
/**
* function to get the current timestamp in milliseconds
*/
now?: () => number;
/**
* An AbortSignal for aborting the benchmark
*/
signal?: AbortSignal;
/**
* Throw if a task fails (events will not work if true)
*/
throws?: boolean;
/**
* warmup time (milliseconds) @default 100ms
*/
warmupTime?: number;
/**
* warmup iterations @default 5
*/
warmupIterations?: number;
/**
* setup function to run before each benchmark task (cycle)
*/
setup?: Hook;
/**
* teardown function to run after each benchmark task (cycle)
*/
teardown?: Hook;
};
type BenchEvent = Event & {
task: Task | null;
};
type RemoveEventListenerOptionsArgument = Parameters<typeof EventTarget.prototype.removeEventListener>[2];
type AddEventListenerOptionsArgument = Parameters<typeof EventTarget.prototype.addEventListener>[2];
/**
* The Benchmark instance for keeping track of the benchmark tasks and controlling
* them.
*/
declare class Bench extends EventTarget {
_tasks: Map<string, Task>;
_todos: Map<string, Task>;
/**
* Executes tasks concurrently based on the specified concurrency mode.
*
* - When `mode` is set to `null` (default), concurrency is disabled.
* - When `mode` is set to 'task', each task's iterations (calls of a task function) run concurrently.
* - When `mode` is set to 'bench', different tasks within the bench run concurrently.
*/
concurrency: 'task' | 'bench' | null;
/**
* The maximum number of concurrent tasks to run. Defaults to Infinity.
*/
threshold: number;
signal?: AbortSignal;
throws: boolean;
warmupTime: number;
warmupIterations: number;
time: number;
iterations: number;
now: () => number;
setup: Hook;
teardown: Hook;
constructor(options?: Options);
private runTask;
/**
* run the added tasks that were registered using the
* {@link add} method.
* Note: This method does not do any warmup. Call {@link warmup} for that.
*/
run(): Promise<Task[]>;
/**
* See Bench.{@link concurrency}
*/
runConcurrently(threshold?: number, mode?: NonNullable<Bench['concurrency']>): Promise<Task[]>;
/**
* warmup the benchmark tasks.
* This is not run by default by the {@link run} method.
*/
warmup(): Promise<void>;
/**
* warmup the benchmark tasks concurrently.
* This is not run by default by the {@link runConcurrently} method.
*/
warmupConcurrently(threshold?: number, mode?: NonNullable<Bench['concurrency']>): Promise<void>;
/**
* reset each task and remove its result
*/
reset(): void;
/**
* add a benchmark task to the task map
*/
add(name: string, fn: Fn, opts?: FnOptions): this;
/**
* add a benchmark todo to the todo map
*/
todo(name: string, fn?: Fn, opts?: FnOptions): this;
/**
* remove a benchmark task from the task map
*/
remove(name: string): this;
addEventListener<K extends BenchEvents, T = BenchEventsMap[K]>(type: K, listener: T, options?: AddEventListenerOptionsArgument): void;
removeEventListener<K extends BenchEvents, T = BenchEventsMap[K]>(type: K, listener: T, options?: RemoveEventListenerOptionsArgument): void;
/**
* table of the tasks results
*/
table(convert?: (task: Task) => Record<string, string | number> | undefined): (Record<string, string | number> | null)[];
/**
* (getter) tasks results as an array
*/
get results(): (TaskResult | undefined)[];
/**
* (getter) tasks as an array
*/
get tasks(): Task[];
get todos(): Task[];
/**
* get a task based on the task name
*/
getTask(name: string): Task | undefined;
}
declare const hrtimeNow: () => number;
declare const now: () => number;
export { Bench, type BenchEvent, type BenchEvents, type Fn, type Hook, type Options, Task, type TaskEvents, type TaskResult, hrtimeNow, now };

View File

@@ -0,0 +1,68 @@
import { type IField } from './modular.ts';
export type PoseidonBasicOpts = {
Fp: IField<bigint>;
t: number;
roundsFull: number;
roundsPartial: number;
isSboxInverse?: boolean;
};
export type PoseidonGrainOpts = PoseidonBasicOpts & {
sboxPower?: number;
};
type PoseidonConstants = {
mds: bigint[][];
roundConstants: bigint[][];
};
export declare function grainGenConstants(opts: PoseidonGrainOpts, skipMDS?: number): PoseidonConstants;
export type PoseidonOpts = PoseidonBasicOpts & PoseidonConstants & {
sboxPower?: number;
reversePartialPowIdx?: boolean;
};
export declare function validateOpts(opts: PoseidonOpts): Readonly<{
rounds: number;
sboxFn: (n: bigint) => bigint;
roundConstants: bigint[][];
mds: bigint[][];
Fp: IField<bigint>;
t: number;
roundsFull: number;
roundsPartial: number;
sboxPower?: number;
reversePartialPowIdx?: boolean;
}>;
export declare function splitConstants(rc: bigint[], t: number): bigint[][];
export type PoseidonFn = {
(values: bigint[]): bigint[];
roundConstants: bigint[][];
};
/** Poseidon NTT-friendly hash. */
export declare function poseidon(opts: PoseidonOpts): PoseidonFn;
export declare class PoseidonSponge {
private Fp;
readonly rate: number;
readonly capacity: number;
readonly hash: PoseidonFn;
private state;
private pos;
private isAbsorbing;
constructor(Fp: IField<bigint>, rate: number, capacity: number, hash: PoseidonFn);
private process;
absorb(input: bigint[]): void;
squeeze(count: number): bigint[];
clean(): void;
clone(): PoseidonSponge;
}
export type PoseidonSpongeOpts = Omit<PoseidonOpts, 't'> & {
rate: number;
capacity: number;
};
/**
* The method is not defined in spec, but nevertheless used often.
* Check carefully for compatibility: there are many edge cases, like absorbing an empty array.
* We cross-test against:
* - https://github.com/ProvableHQ/snarkVM/tree/staging/algorithms
* - https://github.com/arkworks-rs/crypto-primitives/tree/main
*/
export declare function poseidonSponge(opts: PoseidonSpongeOpts): () => PoseidonSponge;
export {};
//# sourceMappingURL=poseidon.d.ts.map

View File

@@ -0,0 +1,249 @@
/**
* @fileoverview Require or disallow newlines around directives.
* @author Kai Cataldo
* @deprecated in ESLint v4.0.0
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "layout",
docs: {
description: "Require or disallow newlines around directives",
recommended: false,
url: "https://eslint.org/docs/latest/rules/lines-around-directive",
},
schema: [
{
oneOf: [
{
enum: ["always", "never"],
},
{
type: "object",
properties: {
before: {
enum: ["always", "never"],
},
after: {
enum: ["always", "never"],
},
},
additionalProperties: false,
minProperties: 2,
},
],
},
],
fixable: "whitespace",
messages: {
expected: 'Expected newline {{location}} "{{value}}" directive.',
unexpected:
'Unexpected newline {{location}} "{{value}}" directive.',
},
deprecated: {
message: "The rule was replaced with a more general rule.",
url: "https://eslint.org/blog/2017/06/eslint-v4.0.0-released/",
deprecatedSince: "4.0.0",
availableUntil: "11.0.0",
replacedBy: [
{
message: "The new rule moved to a plugin.",
url: "https://eslint.org/docs/latest/rules/padding-line-between-statements#examples",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "padding-line-between-statements",
url: "https://eslint.style/rules/padding-line-between-statements",
},
},
],
},
},
create(context) {
const sourceCode = context.sourceCode;
const config = context.options[0] || "always";
const expectLineBefore =
typeof config === "string" ? config : config.before;
const expectLineAfter =
typeof config === "string" ? config : config.after;
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
/**
* Check if node is preceded by a blank newline.
* @param {ASTNode} node Node to check.
* @returns {boolean} Whether or not the passed in node is preceded by a blank newline.
*/
function hasNewlineBefore(node) {
const tokenBefore = sourceCode.getTokenBefore(node, {
includeComments: true,
});
const tokenLineBefore = tokenBefore ? tokenBefore.loc.end.line : 0;
return node.loc.start.line - tokenLineBefore >= 2;
}
/**
* Gets the last token of a node that is on the same line as the rest of the node.
* This will usually be the last token of the node, but it will be the second-to-last token if the node has a trailing
* semicolon on a different line.
* @param {ASTNode} node A directive node
* @returns {Token} The last token of the node on the line
*/
function getLastTokenOnLine(node) {
const lastToken = sourceCode.getLastToken(node);
const secondToLastToken = sourceCode.getTokenBefore(lastToken);
return astUtils.isSemicolonToken(lastToken) &&
lastToken.loc.start.line > secondToLastToken.loc.end.line
? secondToLastToken
: lastToken;
}
/**
* Check if node is followed by a blank newline.
* @param {ASTNode} node Node to check.
* @returns {boolean} Whether or not the passed in node is followed by a blank newline.
*/
function hasNewlineAfter(node) {
const lastToken = getLastTokenOnLine(node);
const tokenAfter = sourceCode.getTokenAfter(lastToken, {
includeComments: true,
});
return tokenAfter.loc.start.line - lastToken.loc.end.line >= 2;
}
/**
* Report errors for newlines around directives.
* @param {ASTNode} node Node to check.
* @param {string} location Whether the error was found before or after the directive.
* @param {boolean} expected Whether or not a newline was expected or unexpected.
* @returns {void}
*/
function reportError(node, location, expected) {
context.report({
node,
messageId: expected ? "expected" : "unexpected",
data: {
value: node.expression.value,
location,
},
fix(fixer) {
const lastToken = getLastTokenOnLine(node);
if (expected) {
return location === "before"
? fixer.insertTextBefore(node, "\n")
: fixer.insertTextAfter(lastToken, "\n");
}
return fixer.removeRange(
location === "before"
? [node.range[0] - 1, node.range[0]]
: [lastToken.range[1], lastToken.range[1] + 1],
);
},
});
}
/**
* Check lines around directives in node
* @param {ASTNode} node node to check
* @returns {void}
*/
function checkDirectives(node) {
const directives = astUtils.getDirectivePrologue(node);
if (!directives.length) {
return;
}
const firstDirective = directives[0];
const leadingComments =
sourceCode.getCommentsBefore(firstDirective);
/*
* Only check before the first directive if it is preceded by a comment or if it is at the top of
* the file and expectLineBefore is set to "never". This is to not force a newline at the top of
* the file if there are no comments as well as for compatibility with padded-blocks.
*/
if (leadingComments.length) {
if (
expectLineBefore === "always" &&
!hasNewlineBefore(firstDirective)
) {
reportError(firstDirective, "before", true);
}
if (
expectLineBefore === "never" &&
hasNewlineBefore(firstDirective)
) {
reportError(firstDirective, "before", false);
}
} else if (
node.type === "Program" &&
expectLineBefore === "never" &&
!leadingComments.length &&
hasNewlineBefore(firstDirective)
) {
reportError(firstDirective, "before", false);
}
const lastDirective = directives.at(-1);
const statements =
node.type === "Program" ? node.body : node.body.body;
/*
* Do not check after the last directive if the body only
* contains a directive prologue and isn't followed by a comment to ensure
* this rule behaves well with padded-blocks.
*/
if (
lastDirective === statements.at(-1) &&
!lastDirective.trailingComments
) {
return;
}
if (
expectLineAfter === "always" &&
!hasNewlineAfter(lastDirective)
) {
reportError(lastDirective, "after", true);
}
if (expectLineAfter === "never" && hasNewlineAfter(lastDirective)) {
reportError(lastDirective, "after", false);
}
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
Program: checkDirectives,
FunctionDeclaration: checkDirectives,
FunctionExpression: checkDirectives,
ArrowFunctionExpression: checkDirectives,
};
},
};

View File

@@ -0,0 +1,58 @@
/**
* @fileoverview Utilities to operate on strings.
* @author Stephen Wade
*/
"use strict";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// eslint-disable-next-line no-control-regex -- intentionally including control characters
const ASCII_REGEX = /^[\u0000-\u007f]*$/u;
/** @type {Intl.Segmenter | undefined} */
let segmenter;
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Converts the first letter of a string to uppercase.
* @param {string} string The string to operate on
* @returns {string} The converted string
*/
function upperCaseFirst(string) {
if (string.length <= 1) {
return string.toUpperCase();
}
return string[0].toUpperCase() + string.slice(1);
}
/**
* Counts graphemes in a given string.
* @param {string} value A string to count graphemes.
* @returns {number} The number of graphemes in `value`.
*/
function getGraphemeCount(value) {
if (ASCII_REGEX.test(value)) {
return value.length;
}
segmenter ??= new Intl.Segmenter("en-US"); // en-US locale should be supported everywhere
let graphemeCount = 0;
// eslint-disable-next-line no-unused-vars -- for-of needs a variable
for (const unused of segmenter.segment(value)) {
graphemeCount++;
}
return graphemeCount;
}
module.exports = {
upperCaseFirst,
getGraphemeCount,
};

View File

@@ -0,0 +1,291 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const tsutils = __importStar(require("ts-api-utils"));
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
const DEFAULT_COMMENT_PATTERN = /^no default$/iu;
exports.default = (0, util_1.createRule)({
name: 'switch-exhaustiveness-check',
meta: {
type: 'suggestion',
docs: {
description: 'Require switch-case statements to be exhaustive',
requiresTypeChecking: true,
},
hasSuggestions: true,
messages: {
addMissingCases: 'Add branches for missing cases.',
dangerousDefaultCase: 'The switch statement is exhaustive, so the default case is unnecessary.',
switchIsNotExhaustive: 'Switch is not exhaustive. Cases not matched: {{missingBranches}}',
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allowDefaultCaseForExhaustiveSwitch: {
type: 'boolean',
description: `If 'true', allow 'default' cases on switch statements with exhaustive cases.`,
},
considerDefaultExhaustiveForUnions: {
type: 'boolean',
description: `If 'true', the 'default' clause is used to determine whether the switch statement is exhaustive for union type`,
},
defaultCaseCommentPattern: {
type: 'string',
description: `Regular expression for a comment that can indicate an intentionally omitted default case.`,
},
requireDefaultForNonUnion: {
type: 'boolean',
description: `If 'true', require a 'default' clause for switches on non-union types.`,
},
},
},
],
},
defaultOptions: [
{
allowDefaultCaseForExhaustiveSwitch: true,
considerDefaultExhaustiveForUnions: false,
requireDefaultForNonUnion: false,
},
],
create(context, [{ allowDefaultCaseForExhaustiveSwitch, considerDefaultExhaustiveForUnions, defaultCaseCommentPattern, requireDefaultForNonUnion, },]) {
const services = (0, util_1.getParserServices)(context);
const checker = services.program.getTypeChecker();
const compilerOptions = services.program.getCompilerOptions();
const commentRegExp = defaultCaseCommentPattern != null
? new RegExp(defaultCaseCommentPattern, 'u')
: DEFAULT_COMMENT_PATTERN;
function getCommentDefaultCase(node) {
const lastCase = node.cases.at(-1);
const commentsAfterLastCase = lastCase
? context.sourceCode.getCommentsAfter(lastCase)
: [];
const defaultCaseComment = commentsAfterLastCase.at(-1);
if (commentRegExp.test(defaultCaseComment?.value.trim() || '')) {
return defaultCaseComment;
}
return;
}
function typeToString(type) {
return checker.typeToString(type, undefined, ts.TypeFormatFlags.AllowUniqueESSymbolType |
ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope |
ts.TypeFormatFlags.UseFullyQualifiedType);
}
function getSwitchMetadata(node) {
const defaultCase = node.cases.find(switchCase => switchCase.test == null);
const discriminantType = (0, util_1.getConstrainedTypeAtLocation)(services, node.discriminant);
const symbolName = discriminantType.getSymbol()?.escapedName;
const containsNonLiteralType = doesTypeContainNonLiteralType(discriminantType);
const caseTypes = new Set();
for (const switchCase of node.cases) {
// If the `test` property of the switch case is `null`, then we are on a
// `default` case.
if (switchCase.test == null) {
continue;
}
const caseType = (0, util_1.getConstrainedTypeAtLocation)(services, switchCase.test);
caseTypes.add(caseType);
}
const missingLiteralBranchTypes = [];
for (const unionPart of tsutils.unionConstituents(discriminantType)) {
for (const intersectionPart of tsutils.intersectionConstituents(unionPart)) {
if (caseTypes.has(intersectionPart) ||
!isTypeLiteralLikeType(intersectionPart)) {
continue;
}
// "missing", "optional" and "undefined" types are different runtime objects,
// but all of them have TypeFlags.Undefined type flag
if ([...caseTypes].some(tsutils.isIntrinsicUndefinedType) &&
tsutils.isIntrinsicUndefinedType(intersectionPart)) {
continue;
}
missingLiteralBranchTypes.push(intersectionPart);
}
}
return {
containsNonLiteralType,
defaultCase: defaultCase ?? getCommentDefaultCase(node),
missingLiteralBranchTypes,
symbolName,
};
}
function checkSwitchExhaustive(node, switchMetadata) {
const { defaultCase, missingLiteralBranchTypes, symbolName } = switchMetadata;
// If considerDefaultExhaustiveForUnions is enabled, the presence of a default case
// always makes the switch exhaustive.
if (considerDefaultExhaustiveForUnions && defaultCase != null) {
return;
}
if (missingLiteralBranchTypes.length > 0) {
context.report({
node: node.discriminant,
messageId: 'switchIsNotExhaustive',
data: {
missingBranches: missingLiteralBranchTypes
.map(missingType => tsutils.isTypeFlagSet(missingType, ts.TypeFlags.ESSymbolLike)
? `typeof ${missingType.getSymbol()?.escapedName}`
: typeToString(missingType))
.join(' | '),
},
suggest: [
{
messageId: 'addMissingCases',
fix(fixer) {
return fixSwitch(fixer, node, missingLiteralBranchTypes, defaultCase, symbolName?.toString());
},
},
],
});
}
}
function fixSwitch(fixer, node, missingBranchTypes, // null means default branch
defaultCase, symbolName) {
const lastCase = node.cases.length > 0 ? node.cases[node.cases.length - 1] : null;
const caseIndent = lastCase
? ' '.repeat(lastCase.loc.start.column)
: // If there are no cases, use indentation of the switch statement and
// leave it to the user to format it correctly.
' '.repeat(node.loc.start.column);
const missingCases = [];
for (const missingBranchType of missingBranchTypes) {
if (missingBranchType == null) {
missingCases.push(`default: { throw new Error('default case') }`);
continue;
}
const missingBranchName = missingBranchType.getSymbol()?.escapedName;
let caseTest = tsutils.isTypeFlagSet(missingBranchType, ts.TypeFlags.ESSymbolLike)
? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
missingBranchName
: typeToString(missingBranchType);
if (symbolName &&
(missingBranchName || missingBranchName === '') &&
(0, util_1.requiresQuoting)(missingBranchName.toString(), compilerOptions.target)) {
const escapedBranchName = missingBranchName
.replaceAll("'", "\\'")
.replaceAll('\n', '\\n')
.replaceAll('\r', '\\r');
caseTest = `${symbolName}['${escapedBranchName}']`;
}
missingCases.push(`case ${caseTest}: { throw new Error('Not implemented yet: ${caseTest
.replaceAll('\\', '\\\\')
.replaceAll("'", "\\'")} case') }`);
}
const fixString = missingCases
.map(code => `${caseIndent}${code}`)
.join('\n');
if (lastCase) {
if (defaultCase) {
const beforeFixString = missingCases
.map(code => `${code}\n${caseIndent}`)
.join('');
return fixer.insertTextBefore(defaultCase, beforeFixString);
}
return fixer.insertTextAfter(lastCase, `\n${fixString}`);
}
// There were no existing cases.
const openingBrace = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.discriminant, util_1.isOpeningBraceToken), util_1.NullThrowsReasons.MissingToken('{', 'discriminant'));
const closingBrace = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.discriminant, util_1.isClosingBraceToken), util_1.NullThrowsReasons.MissingToken('}', 'discriminant'));
return fixer.replaceTextRange([openingBrace.range[0], closingBrace.range[1]], ['{', fixString, `${caseIndent}}`].join('\n'));
}
function checkSwitchUnnecessaryDefaultCase(switchMetadata) {
if (allowDefaultCaseForExhaustiveSwitch) {
return;
}
const { containsNonLiteralType, defaultCase, missingLiteralBranchTypes } = switchMetadata;
if (missingLiteralBranchTypes.length === 0 &&
defaultCase != null &&
!containsNonLiteralType) {
context.report({
node: defaultCase,
messageId: 'dangerousDefaultCase',
});
}
}
function checkSwitchNoUnionDefaultCase(node, switchMetadata) {
if (!requireDefaultForNonUnion) {
return;
}
const { containsNonLiteralType, defaultCase } = switchMetadata;
if (containsNonLiteralType && defaultCase == null) {
context.report({
node: node.discriminant,
messageId: 'switchIsNotExhaustive',
data: { missingBranches: 'default' },
suggest: [
{
messageId: 'addMissingCases',
fix(fixer) {
return fixSwitch(fixer, node, [null], defaultCase);
},
},
],
});
}
}
return {
SwitchStatement(node) {
const switchMetadata = getSwitchMetadata(node);
checkSwitchExhaustive(node, switchMetadata);
checkSwitchUnnecessaryDefaultCase(switchMetadata);
checkSwitchNoUnionDefaultCase(node, switchMetadata);
},
};
},
});
function isTypeLiteralLikeType(type) {
return tsutils.isTypeFlagSet(type, ts.TypeFlags.Literal |
ts.TypeFlags.Undefined |
ts.TypeFlags.Null |
ts.TypeFlags.UniqueESSymbol);
}
/**
* For example:
*
* - `"foo" | "bar"` is a type with all literal types.
* - `"foo" | number` is a type that contains non-literal types.
* - `"foo" & { bar: 1 }` is a type that contains non-literal types.
*
* Default cases are never superfluous in switches with non-literal types.
*/
function doesTypeContainNonLiteralType(type) {
return tsutils
.unionConstituents(type)
.some(type => tsutils
.intersectionConstituents(type)
.every(subType => !isTypeLiteralLikeType(subType)));
}