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,70 @@
/**
* @fileoverview Rule to disallow use of the new operator with global non-constructor functions
* @author Sosuke Suzuki
*/
"use strict";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const nonConstructorGlobalFunctionNames = ["Symbol", "BigInt"];
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
docs: {
description:
"Disallow `new` operators with global non-constructor functions",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-new-native-nonconstructor",
},
schema: [],
messages: {
noNewNonconstructor:
"`{{name}}` cannot be called as a constructor.",
},
},
create(context) {
const sourceCode = context.sourceCode;
return {
"Program:exit"(node) {
const globalScope = sourceCode.getScope(node);
for (const nonConstructorName of nonConstructorGlobalFunctionNames) {
const variable = globalScope.set.get(nonConstructorName);
if (variable && variable.defs.length === 0) {
variable.references.forEach(ref => {
const idNode = ref.identifier;
const parent = idNode.parent;
if (
parent &&
parent.type === "NewExpression" &&
parent.callee === idNode
) {
context.report({
node: idNode,
messageId: "noNewNonconstructor",
data: { name: nonConstructorName },
});
}
});
}
}
},
};
},
};

View File

@@ -0,0 +1,58 @@
{
"name": "deep-is",
"version": "0.1.4",
"description": "node's assert.deepEqual algorithm except for NaN being equal to NaN",
"main": "index.js",
"directories": {
"lib": ".",
"example": "example",
"test": "test"
},
"scripts": {
"test": "tape test/*.js"
},
"devDependencies": {
"tape": "~1.0.2"
},
"repository": {
"type": "git",
"url": "http://github.com/thlorenz/deep-is.git"
},
"keywords": [
"equality",
"equal",
"compare"
],
"author": {
"name": "Thorsten Lorenz",
"email": "thlorenz@gmx.de",
"url": "http://thlorenz.com"
},
"license": "MIT",
"testling": {
"files": "test/*.js",
"browsers": {
"ie": [
6,
7,
8,
9
],
"ff": [
3.5,
10,
15
],
"chrome": [
10,
22
],
"safari": [
5.1
],
"opera": [
12
]
}
}
}

View File

@@ -0,0 +1,8 @@
"use strict";
function _object_destructuring_empty(o) {
if (o === null || o === void 0) throw new TypeError("Cannot destructure " + o);
return o;
}
exports._ = _object_destructuring_empty;

View File

@@ -0,0 +1,2 @@
export declare const assertValidPattern: (pattern: unknown) => void;
//# sourceMappingURL=assert-valid-pattern.d.ts.map

View File

@@ -0,0 +1,5 @@
function _assertClassBrand(e, t, n) {
if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
throw new TypeError("Private element is not present on this object");
}
module.exports = _assertClassBrand, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,325 @@
// TODO: Make it this when TS suports that.
// import {ModifierName, ForegroundColor, BackgroundColor, ColorName} from '#ansi-styles';
// import {ColorInfo, ColorSupportLevel} from '#supports-color';
import {
ModifierName,
ForegroundColorName,
BackgroundColorName,
ColorName,
} from './vendor/ansi-styles/index.js';
import {ColorInfo, ColorSupportLevel} from './vendor/supports-color/index.js';
export interface Options {
/**
Specify the color support for Chalk.
By default, color support is automatically detected based on the environment.
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
readonly level?: ColorSupportLevel;
}
/**
Return a new Chalk instance.
*/
export const Chalk: new (options?: Options) => ChalkInstance; // eslint-disable-line @typescript-eslint/naming-convention
export interface ChalkInstance {
(...text: unknown[]): string;
/**
The color support for Chalk.
By default, color support is automatically detected based on the environment.
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
level: ColorSupportLevel;
/**
Use RGB values to set text color.
@example
```
import chalk from 'chalk';
chalk.rgb(222, 173, 237);
```
*/
rgb: (red: number, green: number, blue: number) => this;
/**
Use HEX value to set text color.
@param color - Hexadecimal value representing the desired color.
@example
```
import chalk from 'chalk';
chalk.hex('#DEADED');
```
*/
hex: (color: string) => this;
/**
Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
@example
```
import chalk from 'chalk';
chalk.ansi256(201);
```
*/
ansi256: (index: number) => this;
/**
Use RGB values to set background color.
@example
```
import chalk from 'chalk';
chalk.bgRgb(222, 173, 237);
```
*/
bgRgb: (red: number, green: number, blue: number) => this;
/**
Use HEX value to set background color.
@param color - Hexadecimal value representing the desired color.
@example
```
import chalk from 'chalk';
chalk.bgHex('#DEADED');
```
*/
bgHex: (color: string) => this;
/**
Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color.
@example
```
import chalk from 'chalk';
chalk.bgAnsi256(201);
```
*/
bgAnsi256: (index: number) => this;
/**
Modifier: Reset the current style.
*/
readonly reset: this;
/**
Modifier: Make the text bold.
*/
readonly bold: this;
/**
Modifier: Make the text have lower opacity.
*/
readonly dim: this;
/**
Modifier: Make the text italic. *(Not widely supported)*
*/
readonly italic: this;
/**
Modifier: Put a horizontal line below the text. *(Not widely supported)*
*/
readonly underline: this;
/**
Modifier: Put a horizontal line above the text. *(Not widely supported)*
*/
readonly overline: this;
/**
Modifier: Invert background and foreground colors.
*/
readonly inverse: this;
/**
Modifier: Print the text but make it invisible.
*/
readonly hidden: this;
/**
Modifier: Puts a horizontal line through the center of the text. *(Not widely supported)*
*/
readonly strikethrough: this;
/**
Modifier: Print the text only when Chalk has a color level above zero.
Can be useful for things that are purely cosmetic.
*/
readonly visible: this;
readonly black: this;
readonly red: this;
readonly green: this;
readonly yellow: this;
readonly blue: this;
readonly magenta: this;
readonly cyan: this;
readonly white: this;
/*
Alias for `blackBright`.
*/
readonly gray: this;
/*
Alias for `blackBright`.
*/
readonly grey: this;
readonly blackBright: this;
readonly redBright: this;
readonly greenBright: this;
readonly yellowBright: this;
readonly blueBright: this;
readonly magentaBright: this;
readonly cyanBright: this;
readonly whiteBright: this;
readonly bgBlack: this;
readonly bgRed: this;
readonly bgGreen: this;
readonly bgYellow: this;
readonly bgBlue: this;
readonly bgMagenta: this;
readonly bgCyan: this;
readonly bgWhite: this;
/*
Alias for `bgBlackBright`.
*/
readonly bgGray: this;
/*
Alias for `bgBlackBright`.
*/
readonly bgGrey: this;
readonly bgBlackBright: this;
readonly bgRedBright: this;
readonly bgGreenBright: this;
readonly bgYellowBright: this;
readonly bgBlueBright: this;
readonly bgMagentaBright: this;
readonly bgCyanBright: this;
readonly bgWhiteBright: this;
}
/**
Main Chalk object that allows to chain styles together.
Call the last one as a method with a string argument.
Order doesn't matter, and later styles take precedent in case of a conflict.
This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
*/
declare const chalk: ChalkInstance;
export const supportsColor: ColorInfo;
export const chalkStderr: typeof chalk;
export const supportsColorStderr: typeof supportsColor;
export {
ModifierName, ForegroundColorName, BackgroundColorName, ColorName,
modifierNames, foregroundColorNames, backgroundColorNames, colorNames,
// } from '#ansi-styles';
} from './vendor/ansi-styles/index.js';
export {
ColorInfo,
ColorSupport,
ColorSupportLevel,
// } from '#supports-color';
} from './vendor/supports-color/index.js';
// TODO: Remove these aliases in the next major version
/**
@deprecated Use `ModifierName` instead.
Basic modifier names.
*/
export type Modifiers = ModifierName;
/**
@deprecated Use `ForegroundColorName` instead.
Basic foreground color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type ForegroundColor = ForegroundColorName;
/**
@deprecated Use `BackgroundColorName` instead.
Basic background color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type BackgroundColor = BackgroundColorName;
/**
@deprecated Use `ColorName` instead.
Basic color names. The combination of foreground and background color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type Color = ColorName;
/**
@deprecated Use `modifierNames` instead.
Basic modifier names.
*/
export const modifiers: readonly Modifiers[];
/**
@deprecated Use `foregroundColorNames` instead.
Basic foreground color names.
*/
export const foregroundColors: readonly ForegroundColor[];
/**
@deprecated Use `backgroundColorNames` instead.
Basic background color names.
*/
export const backgroundColors: readonly BackgroundColor[];
/**
@deprecated Use `colorNames` instead.
Basic color names. The combination of foreground and background color names.
*/
export const colors: readonly Color[];
export default chalk;

View File

@@ -0,0 +1,27 @@
ESQuery is a library for querying the AST output by Esprima for patterns of syntax using a CSS style selector system. Check out the demo:
[demo](https://estools.github.io/esquery/)
The following selectors are supported:
* AST node type: `ForStatement`
* [wildcard](http://dev.w3.org/csswg/selectors4/#universal-selector): `*`
* [attribute existence](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr]`
* [attribute value](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr="foo"]` or `[attr=123]`
* attribute regex: `[attr=/foo.*/]` or (with flags) `[attr=/foo.*/is]`
* attribute conditions: `[attr!="foo"]`, `[attr>2]`, `[attr<3]`, `[attr>=2]`, or `[attr<=3]`
* nested attribute: `[attr.level2="foo"]`
* field: `FunctionDeclaration > Identifier.id`
* [First](http://dev.w3.org/csswg/selectors4/#the-first-child-pseudo) or [last](http://dev.w3.org/csswg/selectors4/#the-last-child-pseudo) child: `:first-child` or `:last-child`
* [nth-child](http://dev.w3.org/csswg/selectors4/#the-nth-child-pseudo) (no ax+b support): `:nth-child(2)`
* [nth-last-child](http://dev.w3.org/csswg/selectors4/#the-nth-last-child-pseudo) (no ax+b support): `:nth-last-child(1)`
* [descendant](http://dev.w3.org/csswg/selectors4/#descendant-combinators): `ancestor descendant`
* [child](http://dev.w3.org/csswg/selectors4/#child-combinators): `parent > child`
* [following sibling](http://dev.w3.org/csswg/selectors4/#general-sibling-combinators): `node ~ sibling`
* [adjacent sibling](http://dev.w3.org/csswg/selectors4/#adjacent-sibling-combinators): `node + adjacent`
* [negation](http://dev.w3.org/csswg/selectors4/#negation-pseudo): `:not(ForStatement)`
* [has](https://drafts.csswg.org/selectors-4/#has-pseudo): `:has(ForStatement)`, `:has(> ForStatement)`
* [matches-any](http://dev.w3.org/csswg/selectors4/#matches): `:is([attr] > :first-child, :last-child)`
* [subject indicator](http://dev.w3.org/csswg/selectors4/#subject): `!IfStatement > [name="foo"]`
* class of AST node: `:statement`, `:expression`, `:declaration`, `:function`, or `:pattern`
[![Build Status](https://travis-ci.org/estools/esquery.png?branch=master)](https://travis-ci.org/estools/esquery)

View File

@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.simpleTraverse = simpleTraverse;
const visitor_keys_1 = require("@typescript-eslint/visitor-keys");
function isValidNode(x) {
return (typeof x === 'object' &&
x != null &&
'type' in x &&
typeof x.type === 'string');
}
function getVisitorKeysForNode(allVisitorKeys, node) {
const keys = allVisitorKeys[node.type];
return (keys ?? []);
}
class SimpleTraverser {
allVisitorKeys = visitor_keys_1.visitorKeys;
selectors;
setParentPointers;
constructor(selectors, setParentPointers = false) {
this.selectors = selectors;
this.setParentPointers = setParentPointers;
if (selectors.visitorKeys) {
this.allVisitorKeys = selectors.visitorKeys;
}
}
traverse(node, parent) {
if (!isValidNode(node)) {
return;
}
if (this.setParentPointers) {
node.parent = parent;
}
if ('enter' in this.selectors) {
this.selectors.enter(node, parent);
}
else if (node.type in this.selectors.visitors) {
this.selectors.visitors[node.type](node, parent);
}
const keys = getVisitorKeysForNode(this.allVisitorKeys, node);
if (keys.length < 1) {
return;
}
for (const key of keys) {
const childOrChildren = node[key];
if (Array.isArray(childOrChildren)) {
for (const child of childOrChildren) {
this.traverse(child, node);
}
}
else {
this.traverse(childOrChildren, node);
}
}
}
}
function simpleTraverse(startingNode, options, setParentPointers = false) {
new SimpleTraverser(options, setParentPointers).traverse(startingNode, undefined);
}

View File

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

View File

@@ -0,0 +1,5 @@
module.exports = {
input: require('./input-data-types')
/*,
expected: require("./expected.json")*/
};

View File

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

View File

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

View File

@@ -0,0 +1,351 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
test("preprocess", () => {
const schema = z.preprocess((data) => [data], z.string().array());
const value = schema.parse("asdf");
expect(value).toEqual(["asdf"]);
expectTypeOf<(typeof schema)["_input"]>().toEqualTypeOf<unknown>();
});
test("async preprocess", async () => {
const schema = z.preprocess(async (data) => {
return [data];
}, z.string().array());
const value = await schema.safeParseAsync("asdf");
expect(value.data).toEqual(["asdf"]);
expect(value).toMatchInlineSnapshot(`
{
"data": [
"asdf",
],
"success": true,
}
`);
});
test("ctx.addIssue accepts string", () => {
const schema = z.preprocess((_, ctx) => {
ctx.addIssue("bad stuff");
}, z.string());
const result = schema.safeParse("asdf");
expect(result.error!.issues).toHaveLength(1);
expect(result).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"message": "bad stuff",
"code": "custom",
"path": []
}
]],
"success": false,
}
`);
});
test("preprocess ctx.addIssue with parse", () => {
const a = z.preprocess((data, ctx) => {
ctx.addIssue({
input: data,
code: "custom",
message: `${data} is not one of our allowed strings`,
});
return data;
}, z.string());
const result = a.safeParse("asdf");
// expect(result.error!.toJSON()).toContain("not one of our allowed strings");
expect(result.error!.issues).toHaveLength(1);
expect(result).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"code": "custom",
"message": "asdf is not one of our allowed strings",
"path": []
}
]],
"success": false,
}
`);
});
test("preprocess ctx.addIssue fatal by default", () => {
const schema = z.preprocess((data, ctx) => {
ctx.addIssue({
code: "custom",
message: `custom error`,
});
return data;
}, z.string());
const result = schema.safeParse(1234);
expect(result.error!.issues).toHaveLength(1);
expect(result).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"code": "custom",
"message": "custom error",
"path": []
}
]],
"success": false,
}
`);
});
test("preprocess ctx.addIssue fatal true", () => {
const schema = z.preprocess((data, ctx) => {
ctx.addIssue({
input: data,
code: "custom",
origin: "custom",
message: `custom error`,
fatal: true,
});
return data;
}, z.string());
const result = schema.safeParse(1234);
expect(result.error!.issues).toHaveLength(1);
expect(result).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"code": "custom",
"origin": "custom",
"message": "custom error",
"fatal": true,
"path": []
}
]],
"success": false,
}
`);
});
test("async preprocess ctx.addIssue with parseAsync", async () => {
const schema = z.preprocess(async (data, ctx) => {
ctx.addIssue({
input: data,
code: "custom",
message: `${data} is not one of our allowed strings`,
});
return data;
}, z.string());
const result = await schema.safeParseAsync("asdf");
expect(result.error!.issues).toHaveLength(1);
expect(result).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"code": "custom",
"message": "asdf is not one of our allowed strings",
"path": []
}
]],
"success": false,
}
`);
});
test("z.NEVER in preprocess", () => {
const foo = z.preprocess((val, ctx) => {
if (!val) {
ctx.addIssue({ input: val, code: "custom", message: "bad" });
return z.NEVER;
}
return val;
}, z.number());
type foo = z.infer<typeof foo>;
expectTypeOf<foo>().toEqualTypeOf<number>();
const result = foo.safeParse(undefined);
expect(result.error!.issues).toHaveLength(1);
expect(result).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"code": "custom",
"message": "bad",
"path": []
}
]],
"success": false,
}
`);
});
test("preprocess as the second property of object", () => {
const schema = z.object({
nonEmptyStr: z.string().min(1),
positiveNum: z.preprocess((v) => Number(v), z.number().positive()),
});
const result = schema.safeParse({
nonEmptyStr: "",
positiveNum: "",
});
expect(result.error!.issues).toHaveLength(2);
expect(result).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"origin": "string",
"code": "too_small",
"minimum": 1,
"inclusive": true,
"path": [
"nonEmptyStr"
],
"message": "Too small: expected string to have >=1 characters"
},
{
"origin": "number",
"code": "too_small",
"minimum": 0,
"inclusive": false,
"path": [
"positiveNum"
],
"message": "Too small: expected number to be >0"
}
]],
"success": false,
}
`);
});
test("preprocess validates with sibling errors", () => {
const schema = z.object({
missing: z.string().refine(() => false),
preprocess: z.preprocess((data: any) => data?.trim(), z.string().regex(/ asdf/)),
});
const result = schema.safeParse({ preprocess: " asdf" });
expect(result.error!.issues).toHaveLength(2);
expect(result).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"expected": "string",
"code": "invalid_type",
"path": [
"missing"
],
"message": "Invalid input: expected string, received undefined"
},
{
"origin": "string",
"code": "invalid_format",
"format": "regex",
"pattern": "/ asdf/",
"path": [
"preprocess"
],
"message": "Invalid string: must match pattern / asdf/"
}
]],
"success": false,
}
`);
});
test("perform transform with non-fatal issues", () => {
const A = z
.string()
.refine((_) => false)
.min(4)
.transform((val) => val.length)
.pipe(z.number())
.refine((_) => false);
expect(A.safeParse("asdfasdf").error!.issues).toHaveLength(1);
expect(A.safeParse("asdfasdf").error).toMatchInlineSnapshot(`
[ZodError: [
{
"code": "custom",
"path": [],
"message": "Invalid input"
}
]]
`);
});
test("preprocess accepts absent object keys (4.3 parity)", () => {
const schema = z.object({ a: z.preprocess((v) => v ?? "X", z.string()) });
expect(schema.parse({})).toEqual({ a: "X" });
expect(schema.parse({ a: "hi" })).toEqual({ a: "hi" });
expect(schema.parse({ a: undefined })).toEqual({ a: "X" });
// Outer optional clobbers preprocess output on undefined input
expect(
z
.preprocess((v) => v ?? "X", z.string())
.optional()
.parse(undefined)
).toBeUndefined();
expect(
z
.preprocess((v) => v ?? "X", z.string())
.optional()
.parse("hi")
).toBe("hi");
expect(z.object({ a: z.preprocess((v) => v ?? "X", z.string()).optional() }).parse({})).toEqual({});
// Top-level direct call unchanged
expect(z.preprocess((v) => v ?? "X", z.string()).parse(undefined)).toBe("X");
});
// https://github.com/colinhacks/zod/issues/5917
test("optional propagates through preprocess inside object", () => {
const outer = z.object({ x: z.preprocess((v) => v, z.number()).optional() });
const inner = z.object({ x: z.preprocess((v) => v, z.number().optional()) });
expect(outer.safeParse({}).success).toBe(true);
expect(inner.safeParse({}).success).toBe(true);
expect(outer.safeParse({ x: 1 })).toEqual({ success: true, data: { x: 1 } });
expect(inner.safeParse({ x: 1 })).toEqual({ success: true, data: { x: 1 } });
expect(inner._zod.def.shape.x._zod.optin).toBe("optional");
expect(inner._zod.def.shape.x._zod.optout).toBe("optional");
});
test("preprocess is a structural subtype of ZodPipe", () => {
const schema = z.preprocess((v) => v, z.string());
expect(schema).toBeInstanceOf(z.ZodPipe);
expect(schema).toBeInstanceOf(z.ZodPreprocess);
expect(schema._zod.def.type).toBe("pipe");
});
test("preprocess does not propagate values/propValues from inner schema", () => {
const inner = z.preprocess((v) => v, z.literal("test"));
expect(inner._zod.values).toBeUndefined();
expect(inner._zod.propValues).toBeUndefined();
});
test("preprocess as discriminator throws at construction (no propValues to inherit)", () => {
const schema = z.discriminatedUnion("kind", [
z.object({ kind: z.preprocess((v: any) => String(v).toUpperCase(), z.literal("A")), a: z.string() }),
z.object({ kind: z.preprocess((v: any) => String(v).toUpperCase(), z.literal("B")), b: z.number() }),
]);
expect(() => schema.parse({ kind: "a", a: "x" })).toThrow(/Invalid discriminated union option/);
});
test("preprocess as record key does not restrict accepted keys", () => {
const schema = z.record(
z.preprocess((v: any) => String(v).toLowerCase(), z.enum(["a", "b"])),
z.string()
);
expect(schema.safeParse({ A: "x", B: "y" })).toEqual({ success: true, data: { a: "x", b: "y" } });
});

View File

@@ -0,0 +1,13 @@
export * as core from "../core/index.js";
export * from "./parse.js";
export * from "./schemas.js";
export * from "./checks.js";
export type { infer, output, input } from "../core/index.js";
export type { JSONType } from "../core/util.js";
export { globalRegistry, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, } from "../core/index.js";
export { toJSONSchema } from "../core/json-schema-processors.js";
export * as locales from "../locales/index.js";
/** A special constant with type `never` */
export * as iso from "./iso.js";
export { ZodMiniISODateTime, ZodMiniISODate, ZodMiniISOTime, ZodMiniISODuration, } from "./iso.js";
export * as coerce from "./coerce.js";

View File

@@ -0,0 +1,239 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 = exports.keccak_256 = exports.keccak_224 = exports.sha3_512 = exports.sha3_384 = exports.sha3_256 = exports.sha3_224 = exports.Keccak = void 0;
exports.keccakP = keccakP;
/**
* SHA3 (keccak) hash function, based on a new "Sponge function" design.
* Different from older hashes, the internal state is bigger than output size.
*
* Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
* [Website](https://keccak.team/keccak.html),
* [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).
*
* Check out `sha3-addons` module for cSHAKE, k12, and others.
* @module
*/
const _u64_ts_1 = require("./_u64.js");
// prettier-ignore
const utils_ts_1 = require("./utils.js");
// No __PURE__ annotations in sha3 header:
// EVERYTHING is in fact used on every export.
// Various per round constants calculations
const _0n = BigInt(0);
const _1n = BigInt(1);
const _2n = BigInt(2);
const _7n = BigInt(7);
const _256n = BigInt(256);
const _0x71n = BigInt(0x71);
const SHA3_PI = [];
const SHA3_ROTL = [];
const _SHA3_IOTA = [];
for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
// Pi
[x, y] = [y, (2 * x + 3 * y) % 5];
SHA3_PI.push(2 * (5 * y + x));
// Rotational
SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
// Iota
let t = _0n;
for (let j = 0; j < 7; j++) {
R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
if (R & _2n)
t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);
}
_SHA3_IOTA.push(t);
}
const IOTAS = (0, _u64_ts_1.split)(_SHA3_IOTA, true);
const SHA3_IOTA_H = IOTAS[0];
const SHA3_IOTA_L = IOTAS[1];
// Left rotation (without 0, 32, 64)
const rotlH = (h, l, s) => (s > 32 ? (0, _u64_ts_1.rotlBH)(h, l, s) : (0, _u64_ts_1.rotlSH)(h, l, s));
const rotlL = (h, l, s) => (s > 32 ? (0, _u64_ts_1.rotlBL)(h, l, s) : (0, _u64_ts_1.rotlSL)(h, l, s));
/** `keccakf1600` internal function, additionally allows to adjust round count. */
function keccakP(s, rounds = 24) {
const B = new Uint32Array(5 * 2);
// NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
for (let round = 24 - rounds; round < 24; round++) {
// Theta θ
for (let x = 0; x < 10; x++)
B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
for (let x = 0; x < 10; x += 2) {
const idx1 = (x + 8) % 10;
const idx0 = (x + 2) % 10;
const B0 = B[idx0];
const B1 = B[idx0 + 1];
const Th = rotlH(B0, B1, 1) ^ B[idx1];
const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
for (let y = 0; y < 50; y += 10) {
s[x + y] ^= Th;
s[x + y + 1] ^= Tl;
}
}
// Rho (ρ) and Pi (π)
let curH = s[2];
let curL = s[3];
for (let t = 0; t < 24; t++) {
const shift = SHA3_ROTL[t];
const Th = rotlH(curH, curL, shift);
const Tl = rotlL(curH, curL, shift);
const PI = SHA3_PI[t];
curH = s[PI];
curL = s[PI + 1];
s[PI] = Th;
s[PI + 1] = Tl;
}
// Chi (χ)
for (let y = 0; y < 50; y += 10) {
for (let x = 0; x < 10; x++)
B[x] = s[y + x];
for (let x = 0; x < 10; x++)
s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
}
// Iota (ι)
s[0] ^= SHA3_IOTA_H[round];
s[1] ^= SHA3_IOTA_L[round];
}
(0, utils_ts_1.clean)(B);
}
/** Keccak sponge function. */
class Keccak extends utils_ts_1.Hash {
// NOTE: we accept arguments in bytes instead of bits here.
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
super();
this.pos = 0;
this.posOut = 0;
this.finished = false;
this.destroyed = false;
this.enableXOF = false;
this.blockLen = blockLen;
this.suffix = suffix;
this.outputLen = outputLen;
this.enableXOF = enableXOF;
this.rounds = rounds;
// Can be passed from user as dkLen
(0, utils_ts_1.anumber)(outputLen);
// 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
// 0 < blockLen < 200
if (!(0 < blockLen && blockLen < 200))
throw new Error('only keccak-f1600 function is supported');
this.state = new Uint8Array(200);
this.state32 = (0, utils_ts_1.u32)(this.state);
}
clone() {
return this._cloneInto();
}
keccak() {
(0, utils_ts_1.swap32IfBE)(this.state32);
keccakP(this.state32, this.rounds);
(0, utils_ts_1.swap32IfBE)(this.state32);
this.posOut = 0;
this.pos = 0;
}
update(data) {
(0, utils_ts_1.aexists)(this);
data = (0, utils_ts_1.toBytes)(data);
(0, utils_ts_1.abytes)(data);
const { blockLen, state } = this;
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
for (let i = 0; i < take; i++)
state[this.pos++] ^= data[pos++];
if (this.pos === blockLen)
this.keccak();
}
return this;
}
finish() {
if (this.finished)
return;
this.finished = true;
const { state, suffix, pos, blockLen } = this;
// Do the padding
state[pos] ^= suffix;
if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
this.keccak();
state[blockLen - 1] ^= 0x80;
this.keccak();
}
writeInto(out) {
(0, utils_ts_1.aexists)(this, false);
(0, utils_ts_1.abytes)(out);
this.finish();
const bufferOut = this.state;
const { blockLen } = this;
for (let pos = 0, len = out.length; pos < len;) {
if (this.posOut >= blockLen)
this.keccak();
const take = Math.min(blockLen - this.posOut, len - pos);
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
this.posOut += take;
pos += take;
}
return out;
}
xofInto(out) {
// Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
if (!this.enableXOF)
throw new Error('XOF is not possible for this instance');
return this.writeInto(out);
}
xof(bytes) {
(0, utils_ts_1.anumber)(bytes);
return this.xofInto(new Uint8Array(bytes));
}
digestInto(out) {
(0, utils_ts_1.aoutput)(out, this);
if (this.finished)
throw new Error('digest() was already called');
this.writeInto(out);
this.destroy();
return out;
}
digest() {
return this.digestInto(new Uint8Array(this.outputLen));
}
destroy() {
this.destroyed = true;
(0, utils_ts_1.clean)(this.state);
}
_cloneInto(to) {
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
to.state32.set(this.state32);
to.pos = this.pos;
to.posOut = this.posOut;
to.finished = this.finished;
to.rounds = rounds;
// Suffix can change in cSHAKE
to.suffix = suffix;
to.outputLen = outputLen;
to.enableXOF = enableXOF;
to.destroyed = this.destroyed;
return to;
}
}
exports.Keccak = Keccak;
const gen = (suffix, blockLen, outputLen) => (0, utils_ts_1.createHasher)(() => new Keccak(blockLen, suffix, outputLen));
/** SHA3-224 hash function. */
exports.sha3_224 = (() => gen(0x06, 144, 224 / 8))();
/** SHA3-256 hash function. Different from keccak-256. */
exports.sha3_256 = (() => gen(0x06, 136, 256 / 8))();
/** SHA3-384 hash function. */
exports.sha3_384 = (() => gen(0x06, 104, 384 / 8))();
/** SHA3-512 hash function. */
exports.sha3_512 = (() => gen(0x06, 72, 512 / 8))();
/** keccak-224 hash function. */
exports.keccak_224 = (() => gen(0x01, 144, 224 / 8))();
/** keccak-256 hash function. Different from SHA3-256. */
exports.keccak_256 = (() => gen(0x01, 136, 256 / 8))();
/** keccak-384 hash function. */
exports.keccak_384 = (() => gen(0x01, 104, 384 / 8))();
/** keccak-512 hash function. */
exports.keccak_512 = (() => gen(0x01, 72, 512 / 8))();
const genShake = (suffix, blockLen, outputLen) => (0, utils_ts_1.createXOFer)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));
/** SHAKE128 XOF with 128-bit security. */
exports.shake128 = (() => genShake(0x1f, 168, 128 / 8))();
/** SHAKE256 XOF with 256-bit security. */
exports.shake256 = (() => genShake(0x1f, 136, 256 / 8))();
//# sourceMappingURL=sha3.js.map

View File

@@ -0,0 +1,73 @@
'use strict'
const Client = require('./client')
const defaults = require('./defaults')
const Connection = require('./connection')
const Result = require('./result')
const utils = require('./utils')
const Pool = require('pg-pool')
const TypeOverrides = require('./type-overrides')
const { DatabaseError } = require('pg-protocol')
const { escapeIdentifier, escapeLiteral } = require('./utils')
const poolFactory = (Client) => {
return class BoundPool extends Pool {
constructor(options) {
super(options, Client)
}
}
}
const PG = function (clientConstructor) {
this.defaults = defaults
this.Client = clientConstructor
this.Query = this.Client.Query
this.Pool = poolFactory(this.Client)
this._pools = []
this.Connection = Connection
this.types = require('pg-types')
this.DatabaseError = DatabaseError
this.TypeOverrides = TypeOverrides
this.escapeIdentifier = escapeIdentifier
this.escapeLiteral = escapeLiteral
this.Result = Result
this.utils = utils
}
let clientConstructor = Client
let forceNative = false
try {
forceNative = !!process.env.NODE_PG_FORCE_NATIVE
} catch {
// ignore, e.g., Deno without --allow-env
}
if (forceNative) {
clientConstructor = require('./native')
}
module.exports = new PG(clientConstructor)
// lazy require native module...the native module may not have installed
Object.defineProperty(module.exports, 'native', {
configurable: true,
enumerable: false,
get() {
let native = null
try {
native = new PG(require('./native'))
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') {
throw err
}
}
// overwrite module.exports.native so that getter is never called again
Object.defineProperty(module.exports, 'native', {
value: native,
})
return native
},
})

View File

@@ -0,0 +1,25 @@
declare module 'cloudflare:sockets' {
export class Socket {
public readonly readable: any
public readonly writable: any
public readonly closed: Promise<void>
public close(): Promise<void>
public startTls(options: TlsOptions): Socket
}
export type TlsOptions = {
expectedServerHostname?: string
}
export type SocketAddress = {
hostname: string
port: number
}
export type SocketOptions = {
secureTransport?: 'off' | 'on' | 'starttls'
allowHalfOpen?: boolean
}
export function connect(address: string | SocketAddress, options?: SocketOptions): Socket
}

View File

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

View File

@@ -0,0 +1,194 @@
/**
* @fileoverview Disallow construction of dense arrays using the Array constructor
* @author Matt DuVall <http://www.mattduvall.com/>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const {
getVariableByName,
isClosingParenToken,
isOpeningParenToken,
isStartOfExpressionStatement,
needsPrecedingSemicolon,
} = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Disallow `Array` constructors",
dialects: ["JavaScript", "TypeScript"],
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-array-constructor",
},
fixable: "code",
hasSuggestions: true,
schema: [],
messages: {
preferLiteral: "The array literal notation [] is preferable.",
useLiteral: "Replace with an array literal.",
useLiteralAfterSemicolon:
"Replace with an array literal, add preceding semicolon.",
},
},
create(context) {
const sourceCode = context.sourceCode;
/**
* Checks if there are comments in Array constructor expressions.
* @param {ASTNode} node A CallExpression or NewExpression node.
* @returns {boolean} True if there are comments, false otherwise.
*/
function hasCommentsInArrayConstructor(node) {
const firstToken = sourceCode.getFirstToken(node);
const lastToken = sourceCode.getLastToken(node);
let lastRelevantToken = sourceCode.getLastToken(node.callee);
while (
lastRelevantToken !== lastToken &&
!isOpeningParenToken(lastRelevantToken)
) {
lastRelevantToken = sourceCode.getTokenAfter(lastRelevantToken);
}
return sourceCode.commentsExistBetween(
firstToken,
lastRelevantToken,
);
}
/**
* Gets the text between the calling parentheses of a CallExpression or NewExpression.
* @param {ASTNode} node A CallExpression or NewExpression node.
* @returns {string} The text between the calling parentheses, or an empty string if there are none.
*/
function getArgumentsText(node) {
const lastToken = sourceCode.getLastToken(node);
if (!isClosingParenToken(lastToken)) {
return "";
}
let firstToken = node.callee;
do {
firstToken = sourceCode.getTokenAfter(firstToken);
if (!firstToken || firstToken === lastToken) {
return "";
}
} while (!isOpeningParenToken(firstToken));
return sourceCode.text.slice(
firstToken.range[1],
lastToken.range[0],
);
}
/**
* Disallow construction of dense arrays using the Array constructor
* @param {ASTNode} node node to evaluate
* @returns {void}
* @private
*/
function check(node) {
if (
node.callee.type !== "Identifier" ||
node.callee.name !== "Array" ||
node.typeArguments ||
(node.arguments.length === 1 &&
node.arguments[0].type !== "SpreadElement")
) {
return;
}
const variable = getVariableByName(
sourceCode.getScope(node),
"Array",
);
/*
* Check if `Array` is a predefined global variable: predefined globals have no declarations,
* meaning that the `identifiers` list of the variable object is empty.
*/
if (variable && variable.identifiers.length === 0) {
const argsText = getArgumentsText(node);
let fixText;
let messageId;
const nonSpreadCount = node.arguments.reduce(
(count, arg) =>
arg.type !== "SpreadElement" ? count + 1 : count,
0,
);
const shouldSuggest =
node.optional ||
(node.arguments.length > 0 && nonSpreadCount < 2) ||
hasCommentsInArrayConstructor(node);
/*
* Check if the suggested change should include a preceding semicolon or not.
* Due to JavaScript's ASI rules, a missing semicolon may be inserted automatically
* before an expression like `Array()` or `new Array()`, but not when the expression
* is changed into an array literal like `[]`.
*/
if (
isStartOfExpressionStatement(node) &&
needsPrecedingSemicolon(sourceCode, node)
) {
fixText = `;[${argsText}]`;
messageId = "useLiteralAfterSemicolon";
} else {
fixText = `[${argsText}]`;
messageId = "useLiteral";
}
context.report({
node,
messageId: "preferLiteral",
fix(fixer) {
if (shouldSuggest) {
return null;
}
return fixer.replaceText(node, fixText);
},
suggest: [
{
messageId,
fix(fixer) {
if (shouldSuggest) {
return fixer.replaceText(node, fixText);
}
return null;
},
},
],
});
}
}
return {
CallExpression: check,
NewExpression: check,
};
},
};

View File

@@ -0,0 +1,423 @@
// src/vlq.ts
var comma = ",".charCodeAt(0);
var semicolon = ";".charCodeAt(0);
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var intToChar = new Uint8Array(64);
var charToInt = new Uint8Array(128);
for (let i = 0; i < chars.length; i++) {
const c = chars.charCodeAt(i);
intToChar[i] = c;
charToInt[c] = i;
}
function decodeInteger(reader, relative) {
let value = 0;
let shift = 0;
let integer = 0;
do {
const c = reader.next();
integer = charToInt[c];
value |= (integer & 31) << shift;
shift += 5;
} while (integer & 32);
const shouldNegate = value & 1;
value >>>= 1;
if (shouldNegate) {
value = -2147483648 | -value;
}
return relative + value;
}
function encodeInteger(builder, num, relative) {
let delta = num - relative;
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
do {
let clamped = delta & 31;
delta >>>= 5;
if (delta > 0) clamped |= 32;
builder.write(intToChar[clamped]);
} while (delta > 0);
return num;
}
function hasMoreVlq(reader, max) {
if (reader.pos >= max) return false;
return reader.peek() !== comma;
}
// src/strings.ts
var bufLength = 1024 * 16;
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
decode(buf) {
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
return out.toString();
}
} : {
decode(buf) {
let out = "";
for (let i = 0; i < buf.length; i++) {
out += String.fromCharCode(buf[i]);
}
return out;
}
};
var StringWriter = class {
constructor() {
this.pos = 0;
this.out = "";
this.buffer = new Uint8Array(bufLength);
}
write(v) {
const { buffer } = this;
buffer[this.pos++] = v;
if (this.pos === bufLength) {
this.out += td.decode(buffer);
this.pos = 0;
}
}
flush() {
const { buffer, out, pos } = this;
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
}
};
var StringReader = class {
constructor(buffer) {
this.pos = 0;
this.buffer = buffer;
}
next() {
return this.buffer.charCodeAt(this.pos++);
}
peek() {
return this.buffer.charCodeAt(this.pos);
}
indexOf(char) {
const { buffer, pos } = this;
const idx = buffer.indexOf(char, pos);
return idx === -1 ? buffer.length : idx;
}
};
// src/scopes.ts
var EMPTY = [];
function decodeOriginalScopes(input) {
const { length } = input;
const reader = new StringReader(input);
const scopes = [];
const stack = [];
let line = 0;
for (; reader.pos < length; reader.pos++) {
line = decodeInteger(reader, line);
const column = decodeInteger(reader, 0);
if (!hasMoreVlq(reader, length)) {
const last = stack.pop();
last[2] = line;
last[3] = column;
continue;
}
const kind = decodeInteger(reader, 0);
const fields = decodeInteger(reader, 0);
const hasName = fields & 1;
const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind];
let vars = EMPTY;
if (hasMoreVlq(reader, length)) {
vars = [];
do {
const varsIndex = decodeInteger(reader, 0);
vars.push(varsIndex);
} while (hasMoreVlq(reader, length));
}
scope.vars = vars;
scopes.push(scope);
stack.push(scope);
}
return scopes;
}
function encodeOriginalScopes(scopes) {
const writer = new StringWriter();
for (let i = 0; i < scopes.length; ) {
i = _encodeOriginalScopes(scopes, i, writer, [0]);
}
return writer.flush();
}
function _encodeOriginalScopes(scopes, index, writer, state) {
const scope = scopes[index];
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
if (index > 0) writer.write(comma);
state[0] = encodeInteger(writer, startLine, state[0]);
encodeInteger(writer, startColumn, 0);
encodeInteger(writer, kind, 0);
const fields = scope.length === 6 ? 1 : 0;
encodeInteger(writer, fields, 0);
if (scope.length === 6) encodeInteger(writer, scope[5], 0);
for (const v of vars) {
encodeInteger(writer, v, 0);
}
for (index++; index < scopes.length; ) {
const next = scopes[index];
const { 0: l, 1: c } = next;
if (l > endLine || l === endLine && c >= endColumn) {
break;
}
index = _encodeOriginalScopes(scopes, index, writer, state);
}
writer.write(comma);
state[0] = encodeInteger(writer, endLine, state[0]);
encodeInteger(writer, endColumn, 0);
return index;
}
function decodeGeneratedRanges(input) {
const { length } = input;
const reader = new StringReader(input);
const ranges = [];
const stack = [];
let genLine = 0;
let definitionSourcesIndex = 0;
let definitionScopeIndex = 0;
let callsiteSourcesIndex = 0;
let callsiteLine = 0;
let callsiteColumn = 0;
let bindingLine = 0;
let bindingColumn = 0;
do {
const semi = reader.indexOf(";");
let genColumn = 0;
for (; reader.pos < semi; reader.pos++) {
genColumn = decodeInteger(reader, genColumn);
if (!hasMoreVlq(reader, semi)) {
const last = stack.pop();
last[2] = genLine;
last[3] = genColumn;
continue;
}
const fields = decodeInteger(reader, 0);
const hasDefinition = fields & 1;
const hasCallsite = fields & 2;
const hasScope = fields & 4;
let callsite = null;
let bindings = EMPTY;
let range;
if (hasDefinition) {
const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
definitionScopeIndex = decodeInteger(
reader,
definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0
);
definitionSourcesIndex = defSourcesIndex;
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex];
} else {
range = [genLine, genColumn, 0, 0];
}
range.isScope = !!hasScope;
if (hasCallsite) {
const prevCsi = callsiteSourcesIndex;
const prevLine = callsiteLine;
callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
const sameSource = prevCsi === callsiteSourcesIndex;
callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
callsiteColumn = decodeInteger(
reader,
sameSource && prevLine === callsiteLine ? callsiteColumn : 0
);
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
}
range.callsite = callsite;
if (hasMoreVlq(reader, semi)) {
bindings = [];
do {
bindingLine = genLine;
bindingColumn = genColumn;
const expressionsCount = decodeInteger(reader, 0);
let expressionRanges;
if (expressionsCount < -1) {
expressionRanges = [[decodeInteger(reader, 0)]];
for (let i = -1; i > expressionsCount; i--) {
const prevBl = bindingLine;
bindingLine = decodeInteger(reader, bindingLine);
bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
const expression = decodeInteger(reader, 0);
expressionRanges.push([expression, bindingLine, bindingColumn]);
}
} else {
expressionRanges = [[expressionsCount]];
}
bindings.push(expressionRanges);
} while (hasMoreVlq(reader, semi));
}
range.bindings = bindings;
ranges.push(range);
stack.push(range);
}
genLine++;
reader.pos = semi + 1;
} while (reader.pos < length);
return ranges;
}
function encodeGeneratedRanges(ranges) {
if (ranges.length === 0) return "";
const writer = new StringWriter();
for (let i = 0; i < ranges.length; ) {
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
}
return writer.flush();
}
function _encodeGeneratedRanges(ranges, index, writer, state) {
const range = ranges[index];
const {
0: startLine,
1: startColumn,
2: endLine,
3: endColumn,
isScope,
callsite,
bindings
} = range;
if (state[0] < startLine) {
catchupLine(writer, state[0], startLine);
state[0] = startLine;
state[1] = 0;
} else if (index > 0) {
writer.write(comma);
}
state[1] = encodeInteger(writer, range[1], state[1]);
const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0);
encodeInteger(writer, fields, 0);
if (range.length === 6) {
const { 4: sourcesIndex, 5: scopesIndex } = range;
if (sourcesIndex !== state[2]) {
state[3] = 0;
}
state[2] = encodeInteger(writer, sourcesIndex, state[2]);
state[3] = encodeInteger(writer, scopesIndex, state[3]);
}
if (callsite) {
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite;
if (sourcesIndex !== state[4]) {
state[5] = 0;
state[6] = 0;
} else if (callLine !== state[5]) {
state[6] = 0;
}
state[4] = encodeInteger(writer, sourcesIndex, state[4]);
state[5] = encodeInteger(writer, callLine, state[5]);
state[6] = encodeInteger(writer, callColumn, state[6]);
}
if (bindings) {
for (const binding of bindings) {
if (binding.length > 1) encodeInteger(writer, -binding.length, 0);
const expression = binding[0][0];
encodeInteger(writer, expression, 0);
let bindingStartLine = startLine;
let bindingStartColumn = startColumn;
for (let i = 1; i < binding.length; i++) {
const expRange = binding[i];
bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine);
bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn);
encodeInteger(writer, expRange[0], 0);
}
}
}
for (index++; index < ranges.length; ) {
const next = ranges[index];
const { 0: l, 1: c } = next;
if (l > endLine || l === endLine && c >= endColumn) {
break;
}
index = _encodeGeneratedRanges(ranges, index, writer, state);
}
if (state[0] < endLine) {
catchupLine(writer, state[0], endLine);
state[0] = endLine;
state[1] = 0;
} else {
writer.write(comma);
}
state[1] = encodeInteger(writer, endColumn, state[1]);
return index;
}
function catchupLine(writer, lastLine, line) {
do {
writer.write(semicolon);
} while (++lastLine < line);
}
// src/sourcemap-codec.ts
function decode(mappings) {
const { length } = mappings;
const reader = new StringReader(mappings);
const decoded = [];
let genColumn = 0;
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
do {
const semi = reader.indexOf(";");
const line = [];
let sorted = true;
let lastCol = 0;
genColumn = 0;
while (reader.pos < semi) {
let seg;
genColumn = decodeInteger(reader, genColumn);
if (genColumn < lastCol) sorted = false;
lastCol = genColumn;
if (hasMoreVlq(reader, semi)) {
sourcesIndex = decodeInteger(reader, sourcesIndex);
sourceLine = decodeInteger(reader, sourceLine);
sourceColumn = decodeInteger(reader, sourceColumn);
if (hasMoreVlq(reader, semi)) {
namesIndex = decodeInteger(reader, namesIndex);
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
} else {
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
}
} else {
seg = [genColumn];
}
line.push(seg);
reader.pos++;
}
if (!sorted) sort(line);
decoded.push(line);
reader.pos = semi + 1;
} while (reader.pos <= length);
return decoded;
}
function sort(line) {
line.sort(sortComparator);
}
function sortComparator(a, b) {
return a[0] - b[0];
}
function encode(decoded) {
const writer = new StringWriter();
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
for (let i = 0; i < decoded.length; i++) {
const line = decoded[i];
if (i > 0) writer.write(semicolon);
if (line.length === 0) continue;
let genColumn = 0;
for (let j = 0; j < line.length; j++) {
const segment = line[j];
if (j > 0) writer.write(comma);
genColumn = encodeInteger(writer, segment[0], genColumn);
if (segment.length === 1) continue;
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
sourceLine = encodeInteger(writer, segment[2], sourceLine);
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
if (segment.length === 4) continue;
namesIndex = encodeInteger(writer, segment[4], namesIndex);
}
}
return writer.flush();
}
export {
decode,
decodeGeneratedRanges,
decodeOriginalScopes,
encode,
encodeGeneratedRanges,
encodeOriginalScopes
};
//# sourceMappingURL=sourcemap-codec.mjs.map

View File

@@ -0,0 +1,108 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "caracteres", verb: "ter" },
file: { unit: "bytes", verb: "ter" },
array: { unit: "itens", verb: "ter" },
set: { unit: "itens", verb: "ter" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "padrão",
email: "endereço de e-mail",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "data e hora ISO",
date: "data ISO",
time: "hora ISO",
duration: "duração ISO",
ipv4: "endereço IPv4",
ipv6: "endereço IPv6",
cidrv4: "faixa de IPv4",
cidrv6: "faixa de IPv6",
base64: "texto codificado em base64",
base64url: "URL codificada em base64",
json_string: "texto JSON",
e164: "número E.164",
jwt: "JWT",
template_literal: "entrada",
};
const TypeDictionary = {
nan: "NaN",
number: "número",
null: "nulo",
};
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 `Tipo inválido: esperado instanceof ${issue.expected}, recebido ${received}`;
}
return `Tipo inválido: esperado ${expected}, recebido ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Entrada inválida: esperado ${util.stringifyPrimitive(issue.values[0])}`;
return `Opção inválida: esperada uma das ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Muito grande: esperado que ${issue.origin ?? "valor"} tivesse ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`;
return `Muito grande: esperado que ${issue.origin ?? "valor"} fosse ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Muito pequeno: esperado que ${issue.origin} tivesse ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Muito pequeno: esperado que ${issue.origin} fosse ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with")
return `Texto inválido: deve começar com "${_issue.prefix}"`;
if (_issue.format === "ends_with")
return `Texto inválido: deve terminar com "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Texto inválido: deve incluir "${_issue.includes}"`;
if (_issue.format === "regex")
return `Texto inválido: deve corresponder ao padrão ${_issue.pattern}`;
return `${FormatDictionary[_issue.format] ?? issue.format} inválido`;
}
case "not_multiple_of":
return `Número inválido: deve ser múltiplo de ${issue.divisor}`;
case "unrecognized_keys":
return `Chave${issue.keys.length > 1 ? "s" : ""} desconhecida${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Chave inválida em ${issue.origin}`;
case "invalid_union":
return "Entrada inválida";
case "invalid_element":
return `Valor inválido em ${issue.origin}`;
default:
return `Campo inválido`;
}
};
};
export default function () {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,36 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
const literalTuna = z.literal("tuna");
const literalFortyTwo = z.literal(42);
const literalTrue = z.literal(true);
const terrificSymbol = Symbol("terrific");
const literalTerrificSymbol = z.literal(terrificSymbol);
test("passing validations", () => {
literalTuna.parse("tuna");
literalFortyTwo.parse(42);
literalTrue.parse(true);
literalTerrificSymbol.parse(terrificSymbol);
});
test("failing validations", () => {
expect(() => literalTuna.parse("shark")).toThrow();
expect(() => literalFortyTwo.parse(43)).toThrow();
expect(() => literalTrue.parse(false)).toThrow();
expect(() => literalTerrificSymbol.parse(Symbol("terrific"))).toThrow();
});
test("invalid_literal should have `received` field with data", () => {
const data = "shark";
const result = literalTuna.safeParse(data);
if (!result.success) {
const issue = result.error.issues[0];
if (issue.code === "invalid_literal") {
expect(issue.received).toBe(data);
}
}
});

View File

@@ -0,0 +1,38 @@
import {Buffer} from 'buffer';
import {serialize, deserialize, deserializeUnchecked} from 'borsh';
// Class wrapping a plain object
export class Struct {
constructor(properties: any) {
Object.assign(this, properties);
}
encode(): Buffer {
return Buffer.from(serialize(SOLANA_SCHEMA, this));
}
static decode(data: Buffer): any {
return deserialize(SOLANA_SCHEMA, this, data);
}
static decodeUnchecked(data: Buffer): any {
return deserializeUnchecked(SOLANA_SCHEMA, this, data);
}
}
// Class representing a Rust-compatible enum, since enums are only strings or
// numbers in pure JS
export class Enum extends Struct {
enum: string = '';
constructor(properties: any) {
super(properties);
if (Object.keys(properties).length !== 1) {
throw new Error('Enum can only take single value');
}
Object.keys(properties).map(key => {
this.enum = key;
});
}
}
export const SOLANA_SCHEMA: Map<Function, any> = new Map();

View File

@@ -0,0 +1,14 @@
/**
* Hand-written visitor implementations for nodes with runtime-dependent
* child ordering. Generated code in visitor.generated.ts and factory.generated.ts
* delegates to these functions.
*/
import type { JSDocParameterOrPropertyTag, Node, NodeArray } from "./ast.ts";
import type { Visitor } from "./visitor.generated.ts";
export type { Visitor };
export { visitEachChild, visitNode, visitNodes, visitNodesArray } from "./visitor.generated.ts";
declare function forEachChildOfJSDocParameterOrPropertyTag<T>(data: any, cbNode: (node: Node) => T, cbNodes: ((nodes: NodeArray<Node>) => T) | undefined): T | undefined;
export { forEachChildOfJSDocParameterOrPropertyTag as forEachChildOfJSDocParameterTag, forEachChildOfJSDocParameterOrPropertyTag as forEachChildOfJSDocPropertyTag };
declare function visitEachChildOfJSDocParameterOrPropertyTag(node: JSDocParameterOrPropertyTag, visitor: Visitor): JSDocParameterOrPropertyTag;
export { visitEachChildOfJSDocParameterOrPropertyTag as visitEachChildOfJSDocParameterTag, visitEachChildOfJSDocParameterOrPropertyTag as visitEachChildOfJSDocPropertyTag };
//# sourceMappingURL=visitor.d.ts.map

View File

@@ -0,0 +1,236 @@
import * as BufferLayout from '@solana/buffer-layout';
import type {Buffer} from 'buffer';
import * as Layout from './layout';
import {PublicKey} from './publickey';
import {toBuffer} from './utils/to-buffer';
export const VOTE_PROGRAM_ID = new PublicKey(
'Vote111111111111111111111111111111111111111',
);
export type Lockout = {
slot: number;
confirmationCount: number;
};
/**
* History of how many credits earned by the end of each epoch
*/
export type EpochCredits = Readonly<{
epoch: number;
credits: number;
prevCredits: number;
}>;
export type AuthorizedVoter = Readonly<{
epoch: number;
authorizedVoter: PublicKey;
}>;
type AuthorizedVoterRaw = Readonly<{
authorizedVoter: Uint8Array;
epoch: number;
}>;
type PriorVoters = Readonly<{
buf: PriorVoterRaw[];
idx: number;
isEmpty: number;
}>;
export type PriorVoter = Readonly<{
authorizedPubkey: PublicKey;
epochOfLastAuthorizedSwitch: number;
targetEpoch: number;
}>;
type PriorVoterRaw = Readonly<{
authorizedPubkey: Uint8Array;
epochOfLastAuthorizedSwitch: number;
targetEpoch: number;
}>;
export type BlockTimestamp = Readonly<{
slot: number;
timestamp: number;
}>;
type VoteAccountData = Readonly<{
authorizedVoters: AuthorizedVoterRaw[];
authorizedWithdrawer: Uint8Array;
commission: number;
epochCredits: EpochCredits[];
lastTimestamp: BlockTimestamp;
nodePubkey: Uint8Array;
priorVoters: PriorVoters;
rootSlot: number;
rootSlotValid: number;
votes: Lockout[];
}>;
/**
* See https://github.com/solana-labs/solana/blob/8a12ed029cfa38d4a45400916c2463fb82bbec8c/programs/vote_api/src/vote_state.rs#L68-L88
*
* @internal
*/
const VoteAccountLayout = BufferLayout.struct<VoteAccountData>([
Layout.publicKey('nodePubkey'),
Layout.publicKey('authorizedWithdrawer'),
BufferLayout.u8('commission'),
BufferLayout.nu64(), // votes.length
BufferLayout.seq<Lockout>(
BufferLayout.struct([
BufferLayout.nu64('slot'),
BufferLayout.u32('confirmationCount'),
]),
BufferLayout.offset(BufferLayout.u32(), -8),
'votes',
),
BufferLayout.u8('rootSlotValid'),
BufferLayout.nu64('rootSlot'),
BufferLayout.nu64(), // authorizedVoters.length
BufferLayout.seq<AuthorizedVoterRaw>(
BufferLayout.struct([
BufferLayout.nu64('epoch'),
Layout.publicKey('authorizedVoter'),
]),
BufferLayout.offset(BufferLayout.u32(), -8),
'authorizedVoters',
),
BufferLayout.struct<PriorVoters>(
[
BufferLayout.seq(
BufferLayout.struct([
Layout.publicKey('authorizedPubkey'),
BufferLayout.nu64('epochOfLastAuthorizedSwitch'),
BufferLayout.nu64('targetEpoch'),
]),
32,
'buf',
),
BufferLayout.nu64('idx'),
BufferLayout.u8('isEmpty'),
],
'priorVoters',
),
BufferLayout.nu64(), // epochCredits.length
BufferLayout.seq<EpochCredits>(
BufferLayout.struct([
BufferLayout.nu64('epoch'),
BufferLayout.nu64('credits'),
BufferLayout.nu64('prevCredits'),
]),
BufferLayout.offset(BufferLayout.u32(), -8),
'epochCredits',
),
BufferLayout.struct<BlockTimestamp>(
[BufferLayout.nu64('slot'), BufferLayout.nu64('timestamp')],
'lastTimestamp',
),
]);
type VoteAccountArgs = {
nodePubkey: PublicKey;
authorizedWithdrawer: PublicKey;
commission: number;
rootSlot: number | null;
votes: Lockout[];
authorizedVoters: AuthorizedVoter[];
priorVoters: PriorVoter[];
epochCredits: EpochCredits[];
lastTimestamp: BlockTimestamp;
};
/**
* VoteAccount class
*/
export class VoteAccount {
nodePubkey: PublicKey;
authorizedWithdrawer: PublicKey;
commission: number;
rootSlot: number | null;
votes: Lockout[];
authorizedVoters: AuthorizedVoter[];
priorVoters: PriorVoter[];
epochCredits: EpochCredits[];
lastTimestamp: BlockTimestamp;
/**
* @internal
*/
constructor(args: VoteAccountArgs) {
this.nodePubkey = args.nodePubkey;
this.authorizedWithdrawer = args.authorizedWithdrawer;
this.commission = args.commission;
this.rootSlot = args.rootSlot;
this.votes = args.votes;
this.authorizedVoters = args.authorizedVoters;
this.priorVoters = args.priorVoters;
this.epochCredits = args.epochCredits;
this.lastTimestamp = args.lastTimestamp;
}
/**
* Deserialize VoteAccount from the account data.
*
* @param buffer account data
* @return VoteAccount
*/
static fromAccountData(
buffer: Buffer | Uint8Array | Array<number>,
): VoteAccount {
const versionOffset = 4;
const va = VoteAccountLayout.decode(toBuffer(buffer), versionOffset);
let rootSlot: number | null = va.rootSlot;
if (!va.rootSlotValid) {
rootSlot = null;
}
return new VoteAccount({
nodePubkey: new PublicKey(va.nodePubkey),
authorizedWithdrawer: new PublicKey(va.authorizedWithdrawer),
commission: va.commission,
votes: va.votes,
rootSlot,
authorizedVoters: va.authorizedVoters.map(parseAuthorizedVoter),
priorVoters: getPriorVoters(va.priorVoters),
epochCredits: va.epochCredits,
lastTimestamp: va.lastTimestamp,
});
}
}
function parseAuthorizedVoter({
authorizedVoter,
epoch,
}: AuthorizedVoterRaw): AuthorizedVoter {
return {
epoch,
authorizedVoter: new PublicKey(authorizedVoter),
};
}
function parsePriorVoters({
authorizedPubkey,
epochOfLastAuthorizedSwitch,
targetEpoch,
}: PriorVoterRaw): PriorVoter {
return {
authorizedPubkey: new PublicKey(authorizedPubkey),
epochOfLastAuthorizedSwitch,
targetEpoch,
};
}
function getPriorVoters({buf, idx, isEmpty}: PriorVoters): PriorVoter[] {
if (isEmpty) {
return [];
}
return [
...buf.slice(idx + 1).map(parsePriorVoters),
...buf.slice(0, idx).map(parsePriorVoters),
];
}

View File

@@ -0,0 +1,4 @@
import EventEmitter from './index.js'
export { EventEmitter }
export default EventEmitter

View File

@@ -0,0 +1,21 @@
import { _ as _super_prop_base } from "./_super_prop_base.js";
function _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) _get = Reflect.get;
else {
_get = function get(target, property, receiver) {
var base = _super_prop_base(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) return desc.get.call(receiver || target);
return desc.value;
};
}
return _get(target, property, receiver || target);
}
export { _get as _ };

View File

@@ -0,0 +1,39 @@
{
"name": "split2",
"version": "4.2.0",
"description": "split a Text Stream into a Line Stream, using Stream 3",
"main": "index.js",
"scripts": {
"lint": "standard --verbose",
"unit": "nyc --lines 100 --branches 100 --functions 100 --check-coverage --reporter=text tape test.js",
"coverage": "nyc --reporter=html --reporter=cobertura --reporter=text tape test/test.js",
"test:report": "npm run lint && npm run unit:report",
"test": "npm run lint && npm run unit",
"legacy": "tape test.js"
},
"pre-commit": [
"test"
],
"website": "https://github.com/mcollina/split2",
"repository": {
"type": "git",
"url": "https://github.com/mcollina/split2.git"
},
"bugs": {
"url": "http://github.com/mcollina/split2/issues"
},
"engines": {
"node": ">= 10.x"
},
"author": "Matteo Collina <hello@matteocollina.com>",
"license": "ISC",
"devDependencies": {
"binary-split": "^1.0.3",
"callback-stream": "^1.1.0",
"fastbench": "^1.0.0",
"nyc": "^15.0.1",
"pre-commit": "^1.1.2",
"standard": "^17.0.0",
"tape": "^5.0.0"
}
}

View File

@@ -0,0 +1,35 @@
'use strict'
const { test } = require('node:test')
const { createWarning } = require('../')
const { withResolvers } = require('./promise')
test('emit should set the emitted state', t => {
t.plan(3)
const { promise, resolve } = withResolvers()
process.on('warning', onWarning)
function onWarning () {
t.fail('should not be called')
}
const warn = createWarning({
name: 'TestDeprecation',
code: 'CODE',
message: 'Hello world'
})
t.assert.ok(!warn.emitted)
warn.emitted = true
t.assert.ok(warn.emitted)
warn()
t.assert.ok(warn.emitted)
setImmediate(() => {
process.removeListener('warning', onWarning)
resolve()
})
return promise
})

View File

@@ -0,0 +1,32 @@
/**
* @typedef {import('estree').Node} Node
* @typedef {import('./sync.js').SyncHandler} SyncHandler
* @typedef {import('./async.js').AsyncHandler} AsyncHandler
*/
/**
* @param {Node} ast
* @param {{
* enter?: SyncHandler
* leave?: SyncHandler
* }} walker
* @returns {Node | null}
*/
export function walk(ast: Node, { enter, leave }: {
enter?: SyncHandler;
leave?: SyncHandler;
}): Node | null;
/**
* @param {Node} ast
* @param {{
* enter?: AsyncHandler
* leave?: AsyncHandler
* }} walker
* @returns {Promise<Node | null>}
*/
export function asyncWalk(ast: Node, { enter, leave }: {
enter?: AsyncHandler;
leave?: AsyncHandler;
}): Promise<Node | null>;
export type Node = import('estree').Node;
export type SyncHandler = import('./sync.js').SyncHandler;
export type AsyncHandler = import('./async.js').AsyncHandler;