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 @@
Please report any security vulnerabilities to security@dotenvx.com.

View File

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

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.safeDecodeAsync = exports.safeEncodeAsync = exports.safeDecode = exports.safeEncode = exports.decodeAsync = exports.encodeAsync = exports.decode = exports.encode = exports.safeParseAsync = exports.parseAsync = exports.safeParse = exports.parse = void 0;
var index_js_1 = require("../core/index.cjs");
Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return index_js_1.parse; } });
Object.defineProperty(exports, "safeParse", { enumerable: true, get: function () { return index_js_1.safeParse; } });
Object.defineProperty(exports, "parseAsync", { enumerable: true, get: function () { return index_js_1.parseAsync; } });
Object.defineProperty(exports, "safeParseAsync", { enumerable: true, get: function () { return index_js_1.safeParseAsync; } });
Object.defineProperty(exports, "encode", { enumerable: true, get: function () { return index_js_1.encode; } });
Object.defineProperty(exports, "decode", { enumerable: true, get: function () { return index_js_1.decode; } });
Object.defineProperty(exports, "encodeAsync", { enumerable: true, get: function () { return index_js_1.encodeAsync; } });
Object.defineProperty(exports, "decodeAsync", { enumerable: true, get: function () { return index_js_1.decodeAsync; } });
Object.defineProperty(exports, "safeEncode", { enumerable: true, get: function () { return index_js_1.safeEncode; } });
Object.defineProperty(exports, "safeDecode", { enumerable: true, get: function () { return index_js_1.safeDecode; } });
Object.defineProperty(exports, "safeEncodeAsync", { enumerable: true, get: function () { return index_js_1.safeEncodeAsync; } });
Object.defineProperty(exports, "safeDecodeAsync", { enumerable: true, get: function () { return index_js_1.safeDecodeAsync; } });

View File

@@ -0,0 +1,79 @@
export declare enum PredefinedFormats {
camelCase = 1,
strictCamelCase = 2,
PascalCase = 3,
StrictPascalCase = 4,
snake_case = 5,
UPPER_CASE = 6
}
export type PredefinedFormatsString = keyof typeof PredefinedFormats;
export declare enum UnderscoreOptions {
forbid = 1,
allow = 2,
require = 3,
requireDouble = 4,
allowDouble = 5,
allowSingleOrDouble = 6
}
export type UnderscoreOptionsString = keyof typeof UnderscoreOptions;
export declare enum Selectors {
variable = 1,
function = 2,
parameter = 4,
parameterProperty = 8,
classicAccessor = 16,
enumMember = 32,
classMethod = 64,
objectLiteralMethod = 128,
typeMethod = 256,
classProperty = 512,
objectLiteralProperty = 1024,
typeProperty = 2048,
autoAccessor = 4096,
class = 8192,
interface = 16384,
typeAlias = 32768,
enum = 65536,
typeParameter = 131072,
import = 262144
}
export type SelectorsString = keyof typeof Selectors;
export declare enum MetaSelectors {
default = -1,
variableLike = 7,
memberLike = 8184,
typeLike = 253952,
method = 448,
property = 3584,
accessor = 4112
}
export type MetaSelectorsString = keyof typeof MetaSelectors;
export type IndividualAndMetaSelectorsString = MetaSelectorsString | SelectorsString;
export declare enum Modifiers {
const = 1,
readonly = 2,
static = 4,
public = 8,
protected = 16,
private = 32,
'#private' = 64,
abstract = 128,
destructured = 256,
global = 512,
exported = 1024,
unused = 2048,
requiresQuotes = 4096,
override = 8192,
async = 16384,
default = 32768,
namespace = 65536
}
export type ModifiersString = keyof typeof Modifiers;
export declare enum TypeModifiers {
boolean = 131072,
string = 262144,
number = 524288,
function = 1048576,
array = 2097152
}
export type TypeModifiersString = keyof typeof TypeModifiers;

View File

@@ -0,0 +1,65 @@
{
"name": "@humanwhocodes/module-importer",
"version": "1.0.1",
"description": "Universal module importer for Node.js",
"main": "src/module-importer.cjs",
"module": "src/module-importer.js",
"type": "module",
"types": "dist/module-importer.d.ts",
"exports": {
"require": "./src/module-importer.cjs",
"import": "./src/module-importer.js"
},
"files": [
"dist",
"src"
],
"publishConfig": {
"access": "public"
},
"gitHooks": {
"pre-commit": "lint-staged"
},
"lint-staged": {
"*.js": [
"eslint --fix"
]
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/nzakas"
},
"scripts": {
"build": "rollup -c && tsc",
"prepare": "npm run build",
"lint": "eslint src/ tests/",
"test:unit": "c8 mocha tests/module-importer.test.js",
"test:build": "node tests/pkg.test.cjs && node tests/pkg.test.mjs",
"test": "npm run test:unit && npm run test:build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/humanwhocodes/module-importer.git"
},
"keywords": [
"modules",
"esm",
"commonjs"
],
"engines": {
"node": ">=12.22"
},
"author": "Nicholas C. Zaks",
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^18.7.6",
"c8": "7.12.0",
"chai": "4.3.6",
"eslint": "8.22.0",
"lint-staged": "13.0.3",
"mocha": "9.2.2",
"rollup": "2.78.0",
"typescript": "4.7.4",
"yorkie": "2.0.0"
}
}

View File

@@ -0,0 +1,588 @@
//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
const path = __toESM(require("path"));
const fs = __toESM(require("fs"));
//#region src/utils.ts
function cleanPath(path$1) {
let normalized = (0, path.normalize)(path$1);
if (normalized.length > 1 && normalized[normalized.length - 1] === path.sep) normalized = normalized.substring(0, normalized.length - 1);
return normalized;
}
const SLASHES_REGEX = /[\\/]/g;
function convertSlashes(path$1, separator) {
return path$1.replace(SLASHES_REGEX, separator);
}
const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
function isRootDirectory(path$1) {
return path$1 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path$1);
}
function normalizePath(path$1, options) {
const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options;
const pathNeedsCleaning = process.platform === "win32" && path$1.includes("/") || path$1.startsWith(".");
if (resolvePaths) path$1 = (0, path.resolve)(path$1);
if (normalizePath$1 || pathNeedsCleaning) path$1 = cleanPath(path$1);
if (path$1 === ".") return "";
const needsSeperator = path$1[path$1.length - 1] !== pathSeparator;
return convertSlashes(needsSeperator ? path$1 + pathSeparator : path$1, pathSeparator);
}
//#endregion
//#region src/api/functions/join-path.ts
function joinPathWithBasePath(filename, directoryPath) {
return directoryPath + filename;
}
function joinPathWithRelativePath(root, options) {
return function(filename, directoryPath) {
const sameRoot = directoryPath.startsWith(root);
if (sameRoot) return directoryPath.slice(root.length) + filename;
else return convertSlashes((0, path.relative)(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
};
}
function joinPath(filename) {
return filename;
}
function joinDirectoryPath(filename, directoryPath, separator) {
return directoryPath + filename + separator;
}
function build$7(root, options) {
const { relativePaths, includeBasePath } = options;
return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath;
}
//#endregion
//#region src/api/functions/push-directory.ts
function pushDirectoryWithRelativePath(root) {
return function(directoryPath, paths) {
paths.push(directoryPath.substring(root.length) || ".");
};
}
function pushDirectoryFilterWithRelativePath(root) {
return function(directoryPath, paths, filters) {
const relativePath = directoryPath.substring(root.length) || ".";
if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath);
};
}
const pushDirectory = (directoryPath, paths) => {
paths.push(directoryPath || ".");
};
const pushDirectoryFilter = (directoryPath, paths, filters) => {
const path$1 = directoryPath || ".";
if (filters.every((filter) => filter(path$1, true))) paths.push(path$1);
};
const empty$2 = () => {};
function build$6(root, options) {
const { includeDirs, filters, relativePaths } = options;
if (!includeDirs) return empty$2;
if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root);
return filters && filters.length ? pushDirectoryFilter : pushDirectory;
}
//#endregion
//#region src/api/functions/push-file.ts
const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
if (filters.every((filter) => filter(filename, false))) counts.files++;
};
const pushFileFilter = (filename, paths, _counts, filters) => {
if (filters.every((filter) => filter(filename, false))) paths.push(filename);
};
const pushFileCount = (_filename, _paths, counts, _filters) => {
counts.files++;
};
const pushFile = (filename, paths) => {
paths.push(filename);
};
const empty$1 = () => {};
function build$5(options) {
const { excludeFiles, filters, onlyCounts } = options;
if (excludeFiles) return empty$1;
if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
else if (onlyCounts) return pushFileCount;
else return pushFile;
}
//#endregion
//#region src/api/functions/get-array.ts
const getArray = (paths) => {
return paths;
};
const getArrayGroup = () => {
return [""].slice(0, 0);
};
function build$4(options) {
return options.group ? getArrayGroup : getArray;
}
//#endregion
//#region src/api/functions/group-files.ts
const groupFiles = (groups, directory, files) => {
groups.push({
directory,
files,
dir: directory
});
};
const empty = () => {};
function build$3(options) {
return options.group ? groupFiles : empty;
}
//#endregion
//#region src/api/functions/resolve-symlink.ts
const resolveSymlinksAsync = function(path$1, state, callback$1) {
const { queue, fs: fs$1, options: { suppressErrors } } = state;
queue.enqueue();
fs$1.realpath(path$1, (error, resolvedPath) => {
if (error) return queue.dequeue(suppressErrors ? null : error, state);
fs$1.stat(resolvedPath, (error$1, stat) => {
if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
if (stat.isDirectory() && isRecursive(path$1, resolvedPath, state)) return queue.dequeue(null, state);
callback$1(stat, resolvedPath);
queue.dequeue(null, state);
});
});
};
const resolveSymlinks = function(path$1, state, callback$1) {
const { queue, fs: fs$1, options: { suppressErrors } } = state;
queue.enqueue();
try {
const resolvedPath = fs$1.realpathSync(path$1);
const stat = fs$1.statSync(resolvedPath);
if (stat.isDirectory() && isRecursive(path$1, resolvedPath, state)) return;
callback$1(stat, resolvedPath);
} catch (e) {
if (!suppressErrors) throw e;
}
};
function build$2(options, isSynchronous) {
if (!options.resolveSymlinks || options.excludeSymlinks) return null;
return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
}
function isRecursive(path$1, resolved, state) {
if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
let parent = (0, path.dirname)(path$1);
let depth = 1;
while (parent !== state.root && depth < 2) {
const resolvedPath = state.symlinks.get(parent);
const isSameRoot = !!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath));
if (isSameRoot) depth++;
else parent = (0, path.dirname)(parent);
}
state.symlinks.set(path$1, resolved);
return depth > 1;
}
function isRecursiveUsingRealPaths(resolved, state) {
return state.visited.includes(resolved + state.options.pathSeparator);
}
//#endregion
//#region src/api/functions/invoke-callback.ts
const onlyCountsSync = (state) => {
return state.counts;
};
const groupsSync = (state) => {
return state.groups;
};
const defaultSync = (state) => {
return state.paths;
};
const limitFilesSync = (state) => {
return state.paths.slice(0, state.options.maxFiles);
};
const onlyCountsAsync = (state, error, callback$1) => {
report(error, callback$1, state.counts, state.options.suppressErrors);
return null;
};
const defaultAsync = (state, error, callback$1) => {
report(error, callback$1, state.paths, state.options.suppressErrors);
return null;
};
const limitFilesAsync = (state, error, callback$1) => {
report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
return null;
};
const groupsAsync = (state, error, callback$1) => {
report(error, callback$1, state.groups, state.options.suppressErrors);
return null;
};
function report(error, callback$1, output, suppressErrors) {
if (error && !suppressErrors) callback$1(error, output);
else callback$1(null, output);
}
function build$1(options, isSynchronous) {
const { onlyCounts, group, maxFiles } = options;
if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync;
else if (group) return isSynchronous ? groupsSync : groupsAsync;
else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync;
else return isSynchronous ? defaultSync : defaultAsync;
}
//#endregion
//#region src/api/functions/walk-directory.ts
const readdirOpts = { withFileTypes: true };
const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
state.queue.enqueue();
if (currentDepth < 0) return state.queue.dequeue(null, state);
const { fs: fs$1 } = state;
state.visited.push(crawlPath);
state.counts.directories++;
fs$1.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
callback$1(entries, directoryPath, currentDepth);
state.queue.dequeue(state.options.suppressErrors ? null : error, state);
});
};
const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
const { fs: fs$1 } = state;
if (currentDepth < 0) return;
state.visited.push(crawlPath);
state.counts.directories++;
let entries = [];
try {
entries = fs$1.readdirSync(crawlPath || ".", readdirOpts);
} catch (e) {
if (!state.options.suppressErrors) throw e;
}
callback$1(entries, directoryPath, currentDepth);
};
function build(isSynchronous) {
return isSynchronous ? walkSync : walkAsync;
}
//#endregion
//#region src/api/queue.ts
/**
* This is a custom stateless queue to track concurrent async fs calls.
* It increments a counter whenever a call is queued and decrements it
* as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
*/
var Queue = class {
count = 0;
constructor(onQueueEmpty) {
this.onQueueEmpty = onQueueEmpty;
}
enqueue() {
this.count++;
return this.count;
}
dequeue(error, output) {
if (this.onQueueEmpty && (--this.count <= 0 || error)) {
this.onQueueEmpty(error, output);
if (error) {
output.controller.abort();
this.onQueueEmpty = void 0;
}
}
}
};
//#endregion
//#region src/api/counter.ts
var Counter = class {
_files = 0;
_directories = 0;
set files(num) {
this._files = num;
}
get files() {
return this._files;
}
set directories(num) {
this._directories = num;
}
get directories() {
return this._directories;
}
/**
* @deprecated use `directories` instead
*/
/* c8 ignore next 3 */
get dirs() {
return this._directories;
}
};
//#endregion
//#region src/api/aborter.ts
/**
* AbortController is not supported on Node 14 so we use this until we can drop
* support for Node 14.
*/
var Aborter = class {
aborted = false;
abort() {
this.aborted = true;
}
};
//#endregion
//#region src/api/walker.ts
var Walker = class {
root;
isSynchronous;
state;
joinPath;
pushDirectory;
pushFile;
getArray;
groupFiles;
resolveSymlink;
walkDirectory;
callbackInvoker;
constructor(root, options, callback$1) {
this.isSynchronous = !callback$1;
this.callbackInvoker = build$1(options, this.isSynchronous);
this.root = normalizePath(root, options);
this.state = {
root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1),
paths: [""].slice(0, 0),
groups: [],
counts: new Counter(),
options,
queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
symlinks: /* @__PURE__ */ new Map(),
visited: [""].slice(0, 0),
controller: new Aborter(),
fs: options.fs || fs
};
this.joinPath = build$7(this.root, options);
this.pushDirectory = build$6(this.root, options);
this.pushFile = build$5(options);
this.getArray = build$4(options);
this.groupFiles = build$3(options);
this.resolveSymlink = build$2(options, this.isSynchronous);
this.walkDirectory = build(this.isSynchronous);
}
start() {
this.pushDirectory(this.root, this.state.paths, this.state.options.filters);
this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk);
return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
}
walk = (entries, directoryPath, depth) => {
const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
const files = this.getArray(this.state.paths);
for (let i = 0; i < entries.length; ++i) {
const entry = entries[i];
if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
const filename = this.joinPath(entry.name, directoryPath);
this.pushFile(filename, files, this.state.counts, filters);
} else if (entry.isDirectory()) {
let path$1 = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
if (exclude && exclude(entry.name, path$1)) continue;
this.pushDirectory(path$1, paths, filters);
this.walkDirectory(this.state, path$1, path$1, depth - 1, this.walk);
} else if (this.resolveSymlink && entry.isSymbolicLink()) {
let path$1 = joinPathWithBasePath(entry.name, directoryPath);
this.resolveSymlink(path$1, this.state, (stat, resolvedPath) => {
if (stat.isDirectory()) {
resolvedPath = normalizePath(resolvedPath, this.state.options);
if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path$1 + pathSeparator)) return;
this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path$1 + pathSeparator, depth - 1, this.walk);
} else {
resolvedPath = useRealPaths ? resolvedPath : path$1;
const filename = (0, path.basename)(resolvedPath);
const directoryPath$1 = normalizePath((0, path.dirname)(resolvedPath), this.state.options);
resolvedPath = this.joinPath(filename, directoryPath$1);
this.pushFile(resolvedPath, files, this.state.counts, filters);
}
});
}
}
this.groupFiles(this.state.groups, directoryPath, files);
};
};
//#endregion
//#region src/api/async.ts
function promise(root, options) {
return new Promise((resolve$1, reject) => {
callback(root, options, (err, output) => {
if (err) return reject(err);
resolve$1(output);
});
});
}
function callback(root, options, callback$1) {
let walker = new Walker(root, options, callback$1);
walker.start();
}
//#endregion
//#region src/api/sync.ts
function sync(root, options) {
const walker = new Walker(root, options);
return walker.start();
}
//#endregion
//#region src/builder/api-builder.ts
var APIBuilder = class {
constructor(root, options) {
this.root = root;
this.options = options;
}
withPromise() {
return promise(this.root, this.options);
}
withCallback(cb) {
callback(this.root, this.options, cb);
}
sync() {
return sync(this.root, this.options);
}
};
//#endregion
//#region src/builder/index.ts
let pm = null;
/* c8 ignore next 6 */
try {
require.resolve("picomatch");
pm = require("picomatch");
} catch {}
var Builder = class {
globCache = {};
options = {
maxDepth: Infinity,
suppressErrors: true,
pathSeparator: path.sep,
filters: []
};
globFunction;
constructor(options) {
this.options = {
...this.options,
...options
};
this.globFunction = this.options.globFunction;
}
group() {
this.options.group = true;
return this;
}
withPathSeparator(separator) {
this.options.pathSeparator = separator;
return this;
}
withBasePath() {
this.options.includeBasePath = true;
return this;
}
withRelativePaths() {
this.options.relativePaths = true;
return this;
}
withDirs() {
this.options.includeDirs = true;
return this;
}
withMaxDepth(depth) {
this.options.maxDepth = depth;
return this;
}
withMaxFiles(limit) {
this.options.maxFiles = limit;
return this;
}
withFullPaths() {
this.options.resolvePaths = true;
this.options.includeBasePath = true;
return this;
}
withErrors() {
this.options.suppressErrors = false;
return this;
}
withSymlinks({ resolvePaths = true } = {}) {
this.options.resolveSymlinks = true;
this.options.useRealPaths = resolvePaths;
return this.withFullPaths();
}
withAbortSignal(signal) {
this.options.signal = signal;
return this;
}
normalize() {
this.options.normalizePath = true;
return this;
}
filter(predicate) {
this.options.filters.push(predicate);
return this;
}
onlyDirs() {
this.options.excludeFiles = true;
this.options.includeDirs = true;
return this;
}
exclude(predicate) {
this.options.exclude = predicate;
return this;
}
onlyCounts() {
this.options.onlyCounts = true;
return this;
}
crawl(root) {
return new APIBuilder(root || ".", this.options);
}
withGlobFunction(fn) {
this.globFunction = fn;
return this;
}
/**
* @deprecated Pass options using the constructor instead:
* ```ts
* new fdir(options).crawl("/path/to/root");
* ```
* This method will be removed in v7.0
*/
/* c8 ignore next 4 */
crawlWithOptions(root, options) {
this.options = {
...this.options,
...options
};
return new APIBuilder(root || ".", this.options);
}
glob(...patterns) {
if (this.globFunction) return this.globWithOptions(patterns);
return this.globWithOptions(patterns, ...[{ dot: true }]);
}
globWithOptions(patterns, ...options) {
const globFn = this.globFunction || pm;
/* c8 ignore next 5 */
if (!globFn) throw new Error("Please specify a glob function to use glob matching.");
var isMatch = this.globCache[patterns.join("\0")];
if (!isMatch) {
isMatch = globFn(patterns, ...options);
this.globCache[patterns.join("\0")] = isMatch;
}
this.options.filters.push((path$1) => isMatch(path$1));
return this;
}
};
//#endregion
exports.fdir = Builder;

View File

@@ -0,0 +1,123 @@
# eslint-visitor-keys
[![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys)
[![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys)
[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/eslint/js/actions)
Constants and utilities about visitor keys to traverse AST.
## 💿 Installation
Use [npm] to install.
```bash
$ npm install eslint-visitor-keys
```
### Requirements
- [Node.js] `^20.19.0`, `^22.13.0`, or `>=24`
## 📖 Usage
To use in an ESM file:
```js
import * as evk from "eslint-visitor-keys";
```
To use in a CommonJS file:
```js
const evk = require("eslint-visitor-keys");
```
### evk.KEYS
> type: `{ [type: string]: string[] | undefined }`
Visitor keys. This keys are frozen.
This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes.
For example:
```
console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"]
```
### evk.getKeys(node)
> type: `(node: object) => string[]`
Get the visitor keys of a given AST node.
This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`.
This will be used to traverse unknown nodes.
For example:
```js
const node = {
type: "AssignmentExpression",
left: { type: "Identifier", name: "foo" },
right: { type: "Literal", value: 0 },
};
console.log(evk.getKeys(node)); // → ["type", "left", "right"]
```
### evk.unionWith(additionalKeys)
> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }`
Make the union set with `evk.KEYS` and the given keys.
- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that.
- It removes duplicated keys as keeping the first one.
For example:
```js
console.log(
evk.unionWith({
MethodDefinition: ["decorators"],
}),
); // → { ..., MethodDefinition: ["decorators", "key", "value"], ... }
```
## 📰 Change log
See [GitHub releases](https://github.com/eslint/js/releases).
## 🍻 Contributing
Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/).
### Development commands
- `npm test` runs tests and measures code coverage.
- `npm run lint` checks source codes with ESLint.
- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser.
[npm]: https://www.npmjs.com/
[Node.js]: https://nodejs.org/
[ESTree]: https://github.com/estree/estree
<!-- 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> <a href="https://shopify.engineering/"><img src="https://avatars.githubusercontent.com/u/8085" alt="Shopify" 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="https://depot.dev"><img src="https://images.opencollective.com/depot/39125a1/logo.png" alt="Depot" height="32"></a> <a href="https://www.n-ix.com/"><img src="https://images.opencollective.com/n-ix-ltd/575a7a5/logo.png" alt="N-iX Ltd" 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,993 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/mini";
import type { util } from "zod/v4/core";
test("z.boolean", () => {
const a = z.boolean();
expect(z.parse(a, true)).toEqual(true);
expect(z.parse(a, false)).toEqual(false);
expect(() => z.parse(a, 123)).toThrow();
expect(() => z.parse(a, "true")).toThrow();
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<boolean>();
});
test("z.bigint", () => {
const a = z.bigint();
expect(z.parse(a, BigInt(123))).toEqual(BigInt(123));
expect(() => z.parse(a, 123)).toThrow();
expect(() => z.parse(a, "123")).toThrow();
});
test("z.symbol", () => {
const a = z.symbol();
const sym = Symbol();
expect(z.parse(a, sym)).toEqual(sym);
expect(() => z.parse(a, "symbol")).toThrow();
});
test("z.date", () => {
const a = z.date();
const date = new Date();
expect(z.parse(a, date)).toEqual(date);
expect(() => z.parse(a, "date")).toThrow();
});
test("z.coerce.string", () => {
const a = z.coerce.string();
expect(z.parse(a, 123)).toEqual("123");
expect(z.parse(a, true)).toEqual("true");
expect(z.parse(a, null)).toEqual("null");
expect(z.parse(a, undefined)).toEqual("undefined");
});
test("z.coerce.number", () => {
const a = z.coerce.number();
expect(z.parse(a, "123")).toEqual(123);
expect(z.parse(a, "123.45")).toEqual(123.45);
expect(z.parse(a, true)).toEqual(1);
expect(z.parse(a, false)).toEqual(0);
expect(() => z.parse(a, "abc")).toThrow();
});
test("z.coerce.boolean", () => {
const a = z.coerce.boolean();
// test booleans
expect(z.parse(a, true)).toEqual(true);
expect(z.parse(a, false)).toEqual(false);
expect(z.parse(a, "true")).toEqual(true);
expect(z.parse(a, "false")).toEqual(true);
expect(z.parse(a, 1)).toEqual(true);
expect(z.parse(a, 0)).toEqual(false);
expect(z.parse(a, {})).toEqual(true);
expect(z.parse(a, [])).toEqual(true);
expect(z.parse(a, undefined)).toEqual(false);
expect(z.parse(a, null)).toEqual(false);
expect(z.parse(a, "")).toEqual(false);
});
test("z.coerce.bigint", () => {
const a = z.coerce.bigint();
expect(z.parse(a, "123")).toEqual(BigInt(123));
expect(z.parse(a, 123)).toEqual(BigInt(123));
expect(() => z.parse(a, "abc")).toThrow();
});
test("z.coerce.date", () => {
const a = z.coerce.date();
const date = new Date();
expect(z.parse(a, date.toISOString())).toEqual(date);
expect(z.parse(a, date.getTime())).toEqual(date);
expect(() => z.parse(a, "invalid date")).toThrow();
});
test("z.iso.datetime", () => {
const d1 = "2021-01-01T00:00:00Z";
const d2 = "2021-01-01T00:00:00.123Z";
const d3 = "2021-01-01T00:00:00";
const d4 = "2021-01-01T00:00:00+07:00";
const d5 = "bad data";
// local: false, offset: false, precision: null
const a = z.iso.datetime();
expect(z.safeParse(a, d1).success).toEqual(true);
expect(z.safeParse(a, d2).success).toEqual(true);
expect(z.safeParse(a, d3).success).toEqual(false);
expect(z.safeParse(a, d4).success).toEqual(false);
expect(z.safeParse(a, d5).success).toEqual(false);
const b = z.iso.datetime({ local: true });
expect(z.safeParse(b, d1).success).toEqual(true);
expect(z.safeParse(b, d2).success).toEqual(true);
expect(z.safeParse(b, d3).success).toEqual(true);
expect(z.safeParse(b, d4).success).toEqual(false);
expect(z.safeParse(b, d5).success).toEqual(false);
const c = z.iso.datetime({ offset: true });
expect(z.safeParse(c, d1).success).toEqual(true);
expect(z.safeParse(c, d2).success).toEqual(true);
expect(z.safeParse(c, d3).success).toEqual(false);
expect(z.safeParse(c, d4).success).toEqual(true);
expect(z.safeParse(c, d5).success).toEqual(false);
const d = z.iso.datetime({ precision: 3 });
expect(z.safeParse(d, d1).success).toEqual(false);
expect(z.safeParse(d, d2).success).toEqual(true);
expect(z.safeParse(d, d3).success).toEqual(false);
expect(z.safeParse(d, d4).success).toEqual(false);
expect(z.safeParse(d, d5).success).toEqual(false);
});
test("z.iso.date", () => {
const d1 = "2021-01-01";
const d2 = "bad data";
const a = z.iso.date();
expect(z.safeParse(a, d1).success).toEqual(true);
expect(z.safeParse(a, d2).success).toEqual(false);
const b = z.string().check(z.iso.date());
expect(z.safeParse(b, d1).success).toEqual(true);
expect(z.safeParse(b, d2).success).toEqual(false);
});
test("z.iso.time", () => {
const d1 = "00:00:00";
const d2 = "00:00:00.123";
const d3 = "bad data";
const a = z.iso.time();
expect(z.safeParse(a, d1).success).toEqual(true);
expect(z.safeParse(a, d2).success).toEqual(true);
expect(z.safeParse(a, d3).success).toEqual(false);
const b = z.iso.time({ precision: 3 });
expect(z.safeParse(b, d1).success).toEqual(false);
expect(z.safeParse(b, d2).success).toEqual(true);
expect(z.safeParse(b, d3).success).toEqual(false);
const c = z.string().check(z.iso.time());
expect(z.safeParse(c, d1).success).toEqual(true);
expect(z.safeParse(c, d2).success).toEqual(true);
expect(z.safeParse(c, d3).success).toEqual(false);
});
test("z.iso.duration", () => {
const d1 = "P3Y6M4DT12H30M5S";
const d2 = "bad data";
const a = z.iso.duration();
expect(z.safeParse(a, d1).success).toEqual(true);
expect(z.safeParse(a, d2).success).toEqual(false);
const b = z.string().check(z.iso.duration());
expect(z.safeParse(b, d1).success).toEqual(true);
expect(z.safeParse(b, d2).success).toEqual(false);
});
test("z.undefined", () => {
const a = z.undefined();
expect(z.parse(a, undefined)).toEqual(undefined);
expect(() => z.parse(a, "undefined")).toThrow();
});
test("z.null", () => {
const a = z.null();
expect(z.parse(a, null)).toEqual(null);
expect(() => z.parse(a, "null")).toThrow();
});
test("z.any", () => {
const a = z.any();
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, 123)).toEqual(123);
expect(z.parse(a, true)).toEqual(true);
expect(z.parse(a, null)).toEqual(null);
expect(z.parse(a, undefined)).toEqual(undefined);
z.parse(a, {});
z.parse(a, []);
z.parse(a, Symbol());
z.parse(a, new Date());
});
test("z.unknown", () => {
const a = z.unknown();
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, 123)).toEqual(123);
expect(z.parse(a, true)).toEqual(true);
expect(z.parse(a, null)).toEqual(null);
expect(z.parse(a, undefined)).toEqual(undefined);
z.parse(a, {});
z.parse(a, []);
z.parse(a, Symbol());
z.parse(a, new Date());
});
test("z.never", () => {
const a = z.never();
expect(() => z.parse(a, "hello")).toThrow();
});
test("z.void", () => {
const a = z.void();
expect(z.parse(a, undefined)).toEqual(undefined);
expect(() => z.parse(a, null)).toThrow();
});
test("z.array", () => {
const a = z.array(z.string());
expect(z.parse(a, ["hello", "world"])).toEqual(["hello", "world"]);
expect(() => z.parse(a, [123])).toThrow();
expect(() => z.parse(a, "hello")).toThrow();
});
test("z.union", () => {
const a = z.union([z.string(), z.number()]);
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, 123)).toEqual(123);
expect(() => z.parse(a, true)).toThrow();
});
test("z.union([]) / z.xor([]) / z.discriminatedUnion(_, []) construct and reject all input", () => {
for (const schema of [z.union([]), z.xor([])]) {
const r = schema.safeParse("anything");
expect(r.success).toEqual(false);
if (!r.success) {
expect(r.error.issues[0].code).toBe("invalid_union");
expect((r.error.issues[0] as any).errors).toEqual([]);
}
}
const disc = z.discriminatedUnion("type", [] as any);
const r = disc.safeParse({ type: "x" });
expect(r.success).toEqual(false);
if (!r.success) {
expect(r.error.issues[0].code).toBe("invalid_union");
expect((r.error.issues[0] as any).errors).toEqual([]);
expect((r.error.issues[0] as any).options).toEqual([]);
}
});
test("z.discriminatedUnion rejects object options missing the discriminator at type level", () => {
// @ts-expect-error missing discriminator property
z.discriminatedUnion("type", [z.object({ value: z.string() })]);
});
test("z.intersection", () => {
const a = z.intersection(z.object({ a: z.string() }), z.object({ b: z.number() }));
expect(z.parse(a, { a: "hello", b: 123 })).toEqual({ a: "hello", b: 123 });
expect(() => z.parse(a, { a: "hello" })).toThrow();
expect(() => z.parse(a, { b: 123 })).toThrow();
expect(() => z.parse(a, "hello")).toThrow();
});
test("z.tuple", () => {
const a = z.tuple([z.string(), z.number()]);
expect(z.parse(a, ["hello", 123])).toEqual(["hello", 123]);
expect(() => z.parse(a, ["hello", "world"])).toThrow();
expect(() => z.parse(a, [123, 456])).toThrow();
expect(() => z.parse(a, "hello")).toThrow();
// tuple with rest
const b = z.tuple([z.string(), z.number(), z.optional(z.string())], z.boolean());
type b = z.output<typeof b>;
expectTypeOf<b>().toEqualTypeOf<[string, number, (string | undefined)?, ...boolean[]]>();
const datas = [
["hello", 123],
["hello", 123, "world"],
["hello", 123, "world", true],
["hello", 123, "world", true, false, true],
];
for (const data of datas) {
expect(z.parse(b, data)).toEqual(data);
}
expect(() => z.parse(b, ["hello", 123, 123])).toThrow();
expect(() => z.parse(b, ["hello", 123, "world", 123])).toThrow();
// tuple with readonly args
const cArgs = [z.string(), z.number(), z.optional(z.string())] as const;
const c = z.tuple(cArgs, z.boolean());
type c = z.output<typeof c>;
expectTypeOf<c>().toEqualTypeOf<[string, number, (string | undefined)?, ...boolean[]]>();
});
test("z.record", () => {
// record schema with enum keys
const a = z.record(z.string(), z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<Record<string, string>>();
const b = z.record(z.union([z.string(), z.number(), z.symbol()]), z.string());
type b = z.output<typeof b>;
expectTypeOf<b>().toEqualTypeOf<Record<string | number | symbol, string>>();
expect(z.parse(b, { a: "hello", 1: "world", [Symbol.for("asdf")]: "symbol" })).toEqual({
a: "hello",
1: "world",
[Symbol.for("asdf")]: "symbol",
});
// enum keys
const c = z.record(z.enum(["a", "b", "c"]), z.string());
type c = z.output<typeof c>;
expectTypeOf<c>().toEqualTypeOf<Record<"a" | "b" | "c", string>>();
expect(z.parse(c, { a: "hello", b: "world", c: "world" })).toEqual({
a: "hello",
b: "world",
c: "world",
});
// missing keys
expect(() => z.parse(c, { a: "hello", b: "world" })).toThrow();
// extra keys
expect(() => z.parse(c, { a: "hello", b: "world", c: "world", d: "world" })).toThrow();
// literal union keys
const d = z.record(z.union([z.literal("a"), z.literal(0)]), z.string());
type d = z.output<typeof d>;
expectTypeOf<d>().toEqualTypeOf<Record<"a" | 0, string>>();
expect(z.parse(d, { a: "hello", 0: "world" })).toEqual({
a: "hello",
0: "world",
});
// TypeScript enum keys
enum Enum {
A = 0,
B = "hi",
}
const e = z.record(z.enum(Enum), z.string());
type e = z.output<typeof e>;
expectTypeOf<e>().toEqualTypeOf<Record<Enum, string>>();
expect(z.parse(e, { [Enum.A]: "hello", [Enum.B]: "world" })).toEqual({
[Enum.A]: "hello",
[Enum.B]: "world",
});
// v3-compat single-arg form: z.record(valueType) defaults keyType to z.string()
const f = (z.record as any)(z.number());
expect(f._zod.def.keyType._zod.def.type).toEqual("string");
expect(f._zod.def.valueType._zod.def.type).toEqual("number");
expect(z.parse(f, { a: 1, b: 2 })).toEqual({ a: 1, b: 2 });
});
test("z.map", () => {
const a = z.map(z.string(), z.number());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<Map<string, number>>();
expect(z.parse(a, new Map([["hello", 123]]))).toEqual(new Map([["hello", 123]]));
expect(() => z.parse(a, new Map([["hello", "world"]]))).toThrow();
expect(() => z.parse(a, new Map([[1243, "world"]]))).toThrow();
expect(() => z.parse(a, "hello")).toThrow();
const r1 = z.safeParse(a, new Map([[123, 123]]));
expect(r1.error?.issues[0].code).toEqual("invalid_type");
expect(r1.error?.issues[0].path).toEqual([123]);
const r2: any = z.safeParse(a, new Map([[BigInt(123), 123]]));
expect(r2.error!.issues[0].code).toEqual("invalid_key");
expect(r2.error!.issues[0].path).toEqual([]);
const r3: any = z.safeParse(a, new Map([["hello", "world"]]));
expect(r3.error!.issues[0].code).toEqual("invalid_type");
expect(r3.error!.issues[0].path).toEqual(["hello"]);
});
test("z.map invalid_element", () => {
const a = z.map(z.bigint(), z.number());
const r1 = z.safeParse(a, new Map([[BigInt(123), BigInt(123)]]));
expect(r1.error!.issues[0].code).toEqual("invalid_element");
expect(r1.error!.issues[0].path).toEqual([]);
});
test("z.map async", async () => {
const a = z.map(z.string().check(z.refine(async () => true)), z.number().check(z.refine(async () => true)));
const d1 = new Map([["hello", 123]]);
expect(await z.parseAsync(a, d1)).toEqual(d1);
await expect(z.parseAsync(a, new Map([[123, 123]]))).rejects.toThrow();
await expect(z.parseAsync(a, new Map([["hi", "world"]]))).rejects.toThrow();
await expect(z.parseAsync(a, new Map([[1243, "world"]]))).rejects.toThrow();
await expect(z.parseAsync(a, "hello")).rejects.toThrow();
const r = await z.safeParseAsync(a, new Map([[123, 123]]));
expect(r.success).toEqual(false);
expect(r.error!.issues[0].code).toEqual("invalid_type");
expect(r.error!.issues[0].path).toEqual([123]);
});
test("z.set", () => {
const a = z.set(z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<Set<string>>();
expect(z.parse(a, new Set(["hello", "world"]))).toEqual(new Set(["hello", "world"]));
expect(() => z.parse(a, new Set([123]))).toThrow();
expect(() => z.parse(a, ["hello", "world"])).toThrow();
expect(() => z.parse(a, "hello")).toThrow();
const b = z.set(z.number());
expect(z.parse(b, new Set([1, 2, 3]))).toEqual(new Set([1, 2, 3]));
expect(() => z.parse(b, new Set(["hello"]))).toThrow();
expect(() => z.parse(b, [1, 2, 3])).toThrow();
expect(() => z.parse(b, 123)).toThrow();
});
test("z.enum", () => {
const a = z.enum(["A", "B", "C"]);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<"A" | "B" | "C">();
expect(z.parse(a, "A")).toEqual("A");
expect(z.parse(a, "B")).toEqual("B");
expect(z.parse(a, "C")).toEqual("C");
expect(() => z.parse(a, "D")).toThrow();
expect(() => z.parse(a, 123)).toThrow();
// expect(a.enum.A).toEqual("A");
// expect(a.enum.B).toEqual("B");
// expect(a.enum.C).toEqual("C");
// expect((a.enum as any).D).toEqual(undefined);
});
test("z.enum - native", () => {
enum NativeEnum {
A = "A",
B = "B",
C = "C",
}
const a = z.enum(NativeEnum);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<NativeEnum>();
expect(z.parse(a, NativeEnum.A)).toEqual(NativeEnum.A);
expect(z.parse(a, NativeEnum.B)).toEqual(NativeEnum.B);
expect(z.parse(a, NativeEnum.C)).toEqual(NativeEnum.C);
expect(() => z.parse(a, "D")).toThrow();
expect(() => z.parse(a, 123)).toThrow();
// test a.enum
a;
// expect(a.enum.A).toEqual(NativeEnum.A);
// expect(a.enum.B).toEqual(NativeEnum.B);
// expect(a.enum.C).toEqual(NativeEnum.C);
});
test("z.nativeEnum", () => {
enum NativeEnum {
A = "A",
B = "B",
C = "C",
}
const a = z.nativeEnum(NativeEnum);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<NativeEnum>();
expect(z.parse(a, NativeEnum.A)).toEqual(NativeEnum.A);
expect(z.parse(a, NativeEnum.B)).toEqual(NativeEnum.B);
expect(z.parse(a, NativeEnum.C)).toEqual(NativeEnum.C);
expect(() => z.parse(a, "D")).toThrow();
expect(() => z.parse(a, 123)).toThrow();
// test a.enum
a;
// expect(a.enum.A).toEqual(NativeEnum.A);
// expect(a.enum.B).toEqual(NativeEnum.B);
// expect(a.enum.C).toEqual(NativeEnum.C);
});
test("z.literal", () => {
const a = z.literal("hello");
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<"hello">();
expect(z.parse(a, "hello")).toEqual("hello");
expect(() => z.parse(a, "world")).toThrow();
expect(() => z.parse(a, 123)).toThrow();
z.literal(["adf"] as const);
});
test("z.file", () => {
const a = z.file();
const file = new File(["content"], "filename.txt", { type: "text/plain" });
expect(z.parse(a, file)).toEqual(file);
expect(() => z.parse(a, "file")).toThrow();
expect(() => z.parse(a, 123)).toThrow();
});
test("z.transform", () => {
const a = z.pipe(
z.string(),
z.transform((val) => val.toUpperCase())
);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(z.parse(a, "hello")).toEqual("HELLO");
expect(() => z.parse(a, 123)).toThrow();
});
test("z.transform async", async () => {
const a = z.pipe(
z.string(),
z.transform(async (val) => val.toUpperCase())
);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(await z.parseAsync(a, "hello")).toEqual("HELLO");
await expect(() => z.parseAsync(a, 123)).rejects.toThrow();
});
test("z.preprocess", () => {
const a = z.pipe(
z.transform((val) => String(val).toUpperCase()),
z.string()
);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(z.parse(a, 123)).toEqual("123");
expect(z.parse(a, true)).toEqual("TRUE");
expect(z.parse(a, BigInt(1234))).toEqual("1234");
// expect(() => z.parse(a, Symbol("asdf"))).toThrow();
});
// test("z.preprocess async", () => {
// const a = z.preprocess(async (val) => String(val), z.string());
// type a = z.output<typeof a>;
// expectTypeOf<a>().toEqualTypeOf<string>();
// expect(z.parse(a, 123)).toEqual("123");
// expect(z.parse(a, true)).toEqual("true");
// expect(() => z.parse(a, {})).toThrow();
// });
test("z.optional", () => {
const a = z.optional(z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string | undefined>();
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, undefined)).toEqual(undefined);
expect(() => z.parse(a, 123)).toThrow();
});
test("z.nullable", () => {
const a = z.nullable(z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string | null>();
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, null)).toEqual(null);
expect(() => z.parse(a, 123)).toThrow();
});
test("z.default", () => {
const a = z._default(z.string(), "default");
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(z.parse(a, undefined)).toEqual("default");
expect(z.parse(a, "hello")).toEqual("hello");
expect(() => z.parse(a, 123)).toThrow();
const b = z._default(z.string(), () => "default");
expect(z.parse(b, undefined)).toEqual("default");
expect(z.parse(b, "hello")).toEqual("hello");
expect(() => z.parse(b, 123)).toThrow();
});
test("z.catch", () => {
const a = z.catch(z.string(), "default");
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, 123)).toEqual("default");
const b = z.catch(z.string(), () => "default");
expect(z.parse(b, "hello")).toEqual("hello");
expect(z.parse(b, 123)).toEqual("default");
const c = z.catch(z.string(), (ctx) => {
return `${ctx.error.issues.length}issues`;
});
expect(z.parse(c, 1234)).toEqual("1issues");
});
test("z.nan", () => {
const a = z.nan();
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<number>();
expect(z.parse(a, Number.NaN)).toEqual(Number.NaN);
expect(() => z.parse(a, 123)).toThrow();
expect(() => z.parse(a, "NaN")).toThrow();
});
test("z.pipe", () => {
const a = z.pipe(
z.pipe(
z.string(),
z.transform((val) => val.length)
),
z.number()
);
type a_in = z.input<typeof a>;
expectTypeOf<a_in>().toEqualTypeOf<string>();
type a_out = z.output<typeof a>;
expectTypeOf<a_out>().toEqualTypeOf<number>();
expect(z.parse(a, "123")).toEqual(3);
expect(z.parse(a, "hello")).toEqual(5);
expect(() => z.parse(a, 123)).toThrow();
});
test("z.readonly", () => {
const a = z.readonly(z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<Readonly<string>>();
expect(z.parse(a, "hello")).toEqual("hello");
expect(() => z.parse(a, 123)).toThrow();
});
test("z.templateLiteral", () => {
const a = z.templateLiteral([z.string(), z.number()]);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<`${string}${number}`>();
expect(z.parse(a, "hello123")).toEqual("hello123");
expect(() => z.parse(a, "hello")).toThrow();
expect(() => z.parse(a, 123)).toThrow();
// multipart
const b = z.templateLiteral([z.string(), z.number(), z.string()]);
type b = z.output<typeof b>;
expectTypeOf<b>().toEqualTypeOf<`${string}${number}${string}`>();
expect(z.parse(b, "hello123world")).toEqual("hello123world");
expect(z.parse(b, "123")).toEqual("123");
expect(() => z.parse(b, "hello")).toThrow();
expect(() => z.parse(b, 123)).toThrow();
// include boolean
const c = z.templateLiteral([z.string(), z.boolean()]);
type c = z.output<typeof c>;
expectTypeOf<c>().toEqualTypeOf<`${string}${boolean}`>();
expect(z.parse(c, "hellotrue")).toEqual("hellotrue");
expect(z.parse(c, "hellofalse")).toEqual("hellofalse");
expect(() => z.parse(c, "hello")).toThrow();
expect(() => z.parse(c, 123)).toThrow();
// include literal prefix
const d = z.templateLiteral([z.literal("hello"), z.number()]);
type d = z.output<typeof d>;
expectTypeOf<d>().toEqualTypeOf<`hello${number}`>();
expect(z.parse(d, "hello123")).toEqual("hello123");
expect(() => z.parse(d, 123)).toThrow();
expect(() => z.parse(d, "world123")).toThrow();
// include literal union
const e = z.templateLiteral([z.literal(["aa", "bb"]), z.number()]);
type e = z.output<typeof e>;
expectTypeOf<e>().toEqualTypeOf<`aa${number}` | `bb${number}`>();
expect(z.parse(e, "aa123")).toEqual("aa123");
expect(z.parse(e, "bb123")).toEqual("bb123");
expect(() => z.parse(e, "cc123")).toThrow();
expect(() => z.parse(e, 123)).toThrow();
});
// this returns both a schema and a check
test("z.custom", () => {
const a = z.custom((val) => {
return typeof val === "string";
});
expect(z.parse(a, "hello")).toEqual("hello");
expect(() => z.parse(a, 123)).toThrow();
const b = z.string().check(z.custom((val) => val.length > 3));
expect(z.parse(b, "hello")).toEqual("hello");
expect(() => z.parse(b, "hi")).toThrow();
});
test("z.check", () => {
// this is a more flexible version of z.custom that accepts an arbitrary _parse logic
// the function should return core.$ZodResult
const a = z.any().check(
z.check<string>((ctx) => {
if (typeof ctx.value === "string") return;
ctx.issues.push({
code: "custom",
origin: "custom",
message: "Expected a string",
input: ctx.value,
});
})
);
expect(z.safeParse(a, "hello")).toMatchObject({
success: true,
data: "hello",
});
expect(z.safeParse(a, 123)).toMatchObject({
success: false,
error: { issues: [{ code: "custom", message: "Expected a string" }] },
});
});
test("z.with (alias for z.check)", () => {
// .with() should work exactly the same as .check()
const a = z.any().with(
z.check<string>((ctx) => {
if (typeof ctx.value === "string") return;
ctx.issues.push({
code: "custom",
origin: "custom",
message: "Expected a string",
input: ctx.value,
});
})
);
expect(z.safeParse(a, "hello")).toMatchObject({
success: true,
data: "hello",
});
expect(z.safeParse(a, 123)).toMatchObject({
success: false,
error: { issues: [{ code: "custom", message: "Expected a string" }] },
});
// Test with refine
const b = z.string().with(z.refine((val) => val.length > 3, "Must be longer than 3"));
expect(z.safeParse(b, "hello").success).toBe(true);
expect(z.safeParse(b, "hi").success).toBe(false);
// Test with function
const c = z.string().with(({ value, issues }) => {
if (value.length <= 3) {
issues.push({
code: "custom",
input: value,
message: "Must be longer than 3",
});
}
});
expect(z.safeParse(c, "hello").success).toBe(true);
expect(z.safeParse(c, "hi").success).toBe(false);
});
test("z.instanceof", () => {
class A {}
const a = z.instanceof(A);
expect(z.parse(a, new A())).toBeInstanceOf(A);
expect(() => z.parse(a, {})).toThrow();
});
test("z.refine", () => {
const a = z.number().check(
z.refine((val) => val > 3),
z.refine((val) => val < 10)
);
expect(z.parse(a, 5)).toEqual(5);
expect(() => z.parse(a, 2)).toThrow();
expect(() => z.parse(a, 11)).toThrow();
expect(() => z.parse(a, "hi")).toThrow();
});
// test("z.superRefine", () => {
// const a = z.number([
// z.superRefine((val, ctx) => {
// if (val < 3) {
// return ctx.addIssue({
// code: "custom",
// origin: "custom",
// message: "Too small",
// input: val,
// });
// }
// if (val > 10) {
// return ctx.addIssue("Too big");
// }
// }),
// ]);
// expect(z.parse(a, 5)).toEqual(5);
// expect(() => z.parse(a, 2)).toThrow();
// expect(() => z.parse(a, 11)).toThrow();
// expect(() => z.parse(a, "hi")).toThrow();
// });
test("z.transform", () => {
const a = z.transform((val: number) => {
return `${val}`;
});
type a_in = z.input<typeof a>;
expectTypeOf<a_in>().toEqualTypeOf<number>();
type a_out = z.output<typeof a>;
expectTypeOf<a_out>().toEqualTypeOf<string>();
expect(z.parse(a, 123)).toEqual("123");
});
test("z.$brand()", () => {
const a = z.string().brand<"my-brand">();
type a = z.output<typeof a>;
const branded = (_: a) => {};
// @ts-expect-error
branded("asdf");
});
test("z.lazy", () => {
const a = z.lazy(() => z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(z.parse(a, "hello")).toEqual("hello");
expect(() => z.parse(a, 123)).toThrow();
});
// schema that validates JSON-like data
test("z.json", () => {
const a = z.json();
type a = z.output<typeof a>;
a._zod.output;
expectTypeOf<a>().toEqualTypeOf<util.JSONType>();
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, 123)).toEqual(123);
expect(z.parse(a, true)).toEqual(true);
expect(z.parse(a, null)).toEqual(null);
expect(z.parse(a, {})).toEqual({});
expect(z.parse(a, { a: "hello" })).toEqual({ a: "hello" });
expect(z.parse(a, [1, 2, 3])).toEqual([1, 2, 3]);
expect(z.parse(a, [{ a: "hello" }])).toEqual([{ a: "hello" }]);
// fail cases
expect(() => z.parse(a, new Date())).toThrow();
expect(() => z.parse(a, Symbol())).toThrow();
expect(() => z.parse(a, { a: new Date() })).toThrow();
expect(() => z.parse(a, undefined)).toThrow();
expect(() => z.parse(a, { a: undefined })).toThrow();
});
test("z.stringbool", () => {
const a = z.stringbool();
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 });
const b = z.stringbool({
truthy: ["y"],
falsy: ["n"],
});
expect(z.parse(b, "y")).toEqual(true);
expect(z.parse(b, "n")).toEqual(false);
expect(z.safeParse(b, "true")).toMatchObject({ success: false });
expect(z.safeParse(b, "false")).toMatchObject({ success: false });
const c = z.stringbool({
case: "sensitive",
});
expect(z.parse(c, "true")).toEqual(true);
expect(z.safeParse(c, "TRUE")).toMatchObject({ success: false });
});
// promise
test("z.promise", async () => {
const a = z.promise(z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<Promise<string>>();
expect(await z.safeParseAsync(a, Promise.resolve("hello"))).toMatchObject({
success: true,
data: "hello",
});
expect(await z.safeParseAsync(a, Promise.resolve(123))).toMatchObject({
success: false,
});
const b = z.string();
expect(() => z.parse(b, Promise.resolve("hello"))).toThrow();
});
// test("type assertions", () => {
// const schema = z.pipe(
// z.string(),
// z.transform((val) => val.length)
// );
// schema.assertInput<string>();
// // @ts-expect-error
// schema.assertInput<number>();
// schema.assertOutput<number>();
// // @ts-expect-error
// schema.assertOutput<string>();
// });
test("z.pipe type enforcement", () => {
z.pipe(
z.pipe(
z.string().check(z.regex(/asdf/)),
z.transform((v) => new Date(v))
),
z.date().check(z.maximum(new Date()))
);
});
test("def typing", () => {
z.string().def.type satisfies "string";
z.email().def.format satisfies "email";
z.number().def.type satisfies "number";
z.float64().def.format satisfies z.core.$ZodNumberFormats;
z.bigint().def.type satisfies "bigint";
z.boolean().def.type satisfies "boolean";
z.date().def.type satisfies "date";
z.symbol().def.type satisfies "symbol";
z.undefined().def.type satisfies "undefined";
z.nullable(z.string()).def.type satisfies "nullable";
z.null().def.type satisfies "null";
z.any().def.type satisfies "any";
z.unknown().def.type satisfies "unknown";
z.never().def.type satisfies "never";
z.void().def.type satisfies "void";
z.array(z.string()).def.type satisfies "array";
z.object({ key: z.string() }).def.type satisfies "object";
z.union([z.string(), z.number()]).def.type satisfies "union";
z.intersection(z.string(), z.number()).def.type satisfies "intersection";
z.tuple([z.string(), z.number()]).def.type satisfies "tuple";
z.record(z.string(), z.number()).def.type satisfies "record";
z.map(z.string(), z.number()).def.type satisfies "map";
z.set(z.string()).def.type satisfies "set";
z.literal("example").def.type satisfies "literal";
expectTypeOf(z.literal("example").def.values).toEqualTypeOf<"example"[]>();
z.enum(["a", "b", "c"]).def.type satisfies "enum";
z.promise(z.string()).def.type satisfies "promise";
z.lazy(() => z.string()).def.type satisfies "lazy";
z.optional(z.string()).def.type satisfies "optional";
z._default(z.string(), "default").def.type satisfies "default";
z.templateLiteral([z.literal("a"), z.literal("b")]).def.type satisfies "template_literal";
z.custom<string>((val) => typeof val === "string").def.type satisfies "custom";
z.transform((val) => val as string).def.type satisfies "transform";
z.nonoptional(z.string()).def.type satisfies "nonoptional";
z.readonly(z.unknown()).def.type satisfies "readonly";
z.nan().def.type satisfies "nan";
z.pipe(z.unknown(), z.number()).def.type satisfies "pipe";
z.success(z.string()).def.type satisfies "success";
z.catch(z.string(), "fallback").def.type satisfies "catch";
z.file().def.type satisfies "file";
});
test("defaulted object schema returns shallow clone", () => {
const schema = z._default(
z.object({
a: z.string(),
}),
{ a: "x" }
);
const result1 = schema.parse(undefined);
const result2 = schema.parse(undefined);
expect(result1).not.toBe(result2);
expect(result1).toEqual(result2);
});
test("runtime type property exists and returns correct values", () => {
const stringSchema = z.string();
expect(stringSchema.type).toBe("string");
});
test("type narrowing works with type property", () => {
type ArrayOrRecord = z.ZodMiniArray<z.ZodMiniString> | z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniAny>;
const arraySchema = z.array(z.string()) as ArrayOrRecord;
if (arraySchema.type === "array") {
expectTypeOf(arraySchema).toEqualTypeOf<z.ZodMiniArray<z.ZodMiniString<unknown>>>();
expect(arraySchema.def.element).toBeDefined();
}
});

View File

@@ -0,0 +1,11 @@
export type Options = [
{
allowDestructuring?: boolean;
allowedNames?: string[];
}
];
export type MessageIds = 'thisAssignment' | 'thisDestructure';
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,7 @@
// @ts-ignore -- @vitest/browser-playwright might not be installed
export * from '@vitest/browser-playwright/context'
// @ts-ignore -- @vitest/browser-webdriverio might not be installed
export * from '@vitest/browser-webdriverio/context'
// @ts-ignore -- @vitest/browser-preview might not be installed
export * from '@vitest/browser-preview/context'
export { BrowserCommands, CDPSession, FsOptions } from 'vitest/internal/browser'

View File

@@ -0,0 +1,112 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ZodError_js_1 = require("../ZodError.cjs");
const util_js_1 = require("../helpers/util.cjs");
const errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodError_js_1.ZodIssueCode.invalid_type:
if (issue.received === util_js_1.ZodParsedType.undefined) {
message = "Required";
}
else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodError_js_1.ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_js_1.util.jsonStringifyReplacer)}`;
break;
case ZodError_js_1.ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util_js_1.util.joinValues(issue.keys, ", ")}`;
break;
case ZodError_js_1.ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodError_js_1.ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util_js_1.util.joinValues(issue.options)}`;
break;
case ZodError_js_1.ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util_js_1.util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodError_js_1.ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodError_js_1.ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodError_js_1.ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodError_js_1.ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
}
else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
}
else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
}
else {
util_js_1.util.assertNever(issue.validation);
}
}
else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
}
else {
message = "Invalid";
}
break;
case ZodError_js_1.ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "bigint")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
else
message = "Invalid input";
break;
case ZodError_js_1.ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
else
message = "Invalid input";
break;
case ZodError_js_1.ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodError_js_1.ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodError_js_1.ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodError_js_1.ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util_js_1.util.assertNever(issue);
}
return { message };
};
exports.default = errorMap;
module.exports = exports.default;

View File

@@ -0,0 +1,57 @@
'use strict'
const test = require('node:test')
const assert = require('node:assert')
const { sink, once } = require('./helper')
const pino = require('../')
const level = 50
const name = 'error'
test('default merge strategy', async () => {
const stream = sink()
const instance = pino({
base: {},
mixin () {
return { tag: 'k8s' }
}
}, stream)
instance.level = name
instance[name]({
tag: 'local'
}, 'test')
const result = await once(stream, 'data')
assert.ok(new Date(result.time) <= new Date(), 'time is greater than Date.now()')
delete result.time
assert.deepEqual(result, {
level,
msg: 'test',
tag: 'local'
})
})
test('custom merge strategy with mixin priority', async () => {
const stream = sink()
const instance = pino({
base: {},
mixin () {
return { tag: 'k8s' }
},
mixinMergeStrategy (mergeObject, mixinObject) {
return Object.assign(mergeObject, mixinObject)
}
}, stream)
instance.level = name
instance[name]({
tag: 'local'
}, 'test')
const result = await once(stream, 'data')
assert.ok(new Date(result.time) <= new Date(), 'time is greater than Date.now()')
delete result.time
assert.deepEqual(result, {
level,
msg: 'test',
tag: 'k8s'
})
})

View File

@@ -0,0 +1 @@
{"version":3,"file":"commentDirectiveType.js","sourceRoot":"","sources":["../../src/enums/commentDirectiveType.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,IAAI,oBAAyB,CAAC;AACrC,CAAC,UAAU,oBAAoB;IAC3B,oBAAoB,CAAC,oBAAoB,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,GAAG,aAAa,CAAC;IAC9E,oBAAoB,CAAC,oBAAoB,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC;AACxE,CAAC,CAAC,CAAC,oBAAoB,IAAI,CAAC,oBAAoB,GAAG,EAAE,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1,44 @@
/**
* Get original stacktrace without source map support the most performant way.
* - Create only 1 stack frame.
* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms).
*/
function createSimpleStackTrace(options) {
const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {};
const limit = Error.stackTraceLimit;
const prepareStackTrace = Error.prepareStackTrace;
Error.stackTraceLimit = stackTraceLimit;
Error.prepareStackTrace = (e) => e.stack;
const err = new Error(message);
const stackTrace = err.stack || "";
Error.prepareStackTrace = prepareStackTrace;
Error.stackTraceLimit = limit;
return stackTrace;
}
function filterOutComments(s) {
const result = [];
let commentState = "none";
for (let i = 0; i < s.length; ++i) {
if (commentState === "singleline") {
if (s[i] === "\n") {
commentState = "none";
}
} else if (commentState === "multiline") {
if (s[i - 1] === "*" && s[i] === "/") {
commentState = "none";
}
} else if (commentState === "none") {
if (s[i] === "/" && s[i + 1] === "/") {
commentState = "singleline";
} else if (s[i] === "/" && s[i + 1] === "*") {
commentState = "multiline";
i += 2;
} else {
result.push(s[i]);
}
}
}
return result.join("");
}
export { createSimpleStackTrace as c, filterOutComments as f };

View File

@@ -0,0 +1,369 @@
/**
* @fileoverview Disallows or enforces spaces inside of object literals.
* @author Jamund Ferguson
* @deprecated in ESLint v8.53.0
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "object-curly-spacing",
url: "https://eslint.style/rules/object-curly-spacing",
},
},
],
},
type: "layout",
docs: {
description: "Enforce consistent spacing inside braces",
recommended: false,
url: "https://eslint.org/docs/latest/rules/object-curly-spacing",
},
fixable: "whitespace",
schema: [
{
enum: ["always", "never"],
},
{
type: "object",
properties: {
arraysInObjects: {
type: "boolean",
},
objectsInObjects: {
type: "boolean",
},
},
additionalProperties: false,
},
],
messages: {
requireSpaceBefore: "A space is required before '{{token}}'.",
requireSpaceAfter: "A space is required after '{{token}}'.",
unexpectedSpaceBefore:
"There should be no space before '{{token}}'.",
unexpectedSpaceAfter: "There should be no space after '{{token}}'.",
},
},
create(context) {
const spaced = context.options[0] === "always",
sourceCode = context.sourceCode;
/**
* Determines whether an option is set, relative to the spacing option.
* If spaced is "always", then check whether option is set to false.
* If spaced is "never", then check whether option is set to true.
* @param {Object} option The option to exclude.
* @returns {boolean} Whether or not the property is excluded.
*/
function isOptionSet(option) {
return context.options[1]
? context.options[1][option] === !spaced
: false;
}
const options = {
spaced,
arraysInObjectsException: isOptionSet("arraysInObjects"),
objectsInObjectsException: isOptionSet("objectsInObjects"),
};
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
/**
* Reports that there shouldn't be a space after the first token
* @param {ASTNode} node The node to report in the event of an error.
* @param {Token} token The token to use for the report.
* @returns {void}
*/
function reportNoBeginningSpace(node, token) {
const nextToken = context.sourceCode.getTokenAfter(token, {
includeComments: true,
});
context.report({
node,
loc: { start: token.loc.end, end: nextToken.loc.start },
messageId: "unexpectedSpaceAfter",
data: {
token: token.value,
},
fix(fixer) {
return fixer.removeRange([
token.range[1],
nextToken.range[0],
]);
},
});
}
/**
* Reports that there shouldn't be a space before the last token
* @param {ASTNode} node The node to report in the event of an error.
* @param {Token} token The token to use for the report.
* @returns {void}
*/
function reportNoEndingSpace(node, token) {
const previousToken = context.sourceCode.getTokenBefore(token, {
includeComments: true,
});
context.report({
node,
loc: { start: previousToken.loc.end, end: token.loc.start },
messageId: "unexpectedSpaceBefore",
data: {
token: token.value,
},
fix(fixer) {
return fixer.removeRange([
previousToken.range[1],
token.range[0],
]);
},
});
}
/**
* Reports that there should be a space after the first token
* @param {ASTNode} node The node to report in the event of an error.
* @param {Token} token The token to use for the report.
* @returns {void}
*/
function reportRequiredBeginningSpace(node, token) {
context.report({
node,
loc: token.loc,
messageId: "requireSpaceAfter",
data: {
token: token.value,
},
fix(fixer) {
return fixer.insertTextAfter(token, " ");
},
});
}
/**
* Reports that there should be a space before the last token
* @param {ASTNode} node The node to report in the event of an error.
* @param {Token} token The token to use for the report.
* @returns {void}
*/
function reportRequiredEndingSpace(node, token) {
context.report({
node,
loc: token.loc,
messageId: "requireSpaceBefore",
data: {
token: token.value,
},
fix(fixer) {
return fixer.insertTextBefore(token, " ");
},
});
}
/**
* Determines if spacing in curly braces is valid.
* @param {ASTNode} node The AST node to check.
* @param {Token} first The first token to check (should be the opening brace)
* @param {Token} second The second token to check (should be first after the opening brace)
* @param {Token} penultimate The penultimate token to check (should be last before closing brace)
* @param {Token} last The last token to check (should be closing brace)
* @returns {void}
*/
function validateBraceSpacing(node, first, second, penultimate, last) {
if (astUtils.isTokenOnSameLine(first, second)) {
const firstSpaced = sourceCode.isSpaceBetween(first, second);
if (options.spaced && !firstSpaced) {
reportRequiredBeginningSpace(node, first);
}
if (!options.spaced && firstSpaced && second.type !== "Line") {
reportNoBeginningSpace(node, first);
}
}
if (astUtils.isTokenOnSameLine(penultimate, last)) {
const shouldCheckPenultimate =
(options.arraysInObjectsException &&
astUtils.isClosingBracketToken(penultimate)) ||
(options.objectsInObjectsException &&
astUtils.isClosingBraceToken(penultimate));
const penultimateType =
shouldCheckPenultimate &&
sourceCode.getNodeByRangeIndex(penultimate.range[0]).type;
const closingCurlyBraceMustBeSpaced =
(options.arraysInObjectsException &&
penultimateType === "ArrayExpression") ||
(options.objectsInObjectsException &&
(penultimateType === "ObjectExpression" ||
penultimateType === "ObjectPattern"))
? !options.spaced
: options.spaced;
const lastSpaced = sourceCode.isSpaceBetween(penultimate, last);
if (closingCurlyBraceMustBeSpaced && !lastSpaced) {
reportRequiredEndingSpace(node, last);
}
if (!closingCurlyBraceMustBeSpaced && lastSpaced) {
reportNoEndingSpace(node, last);
}
}
}
/**
* Gets '}' token of an object node.
*
* Because the last token of object patterns might be a type annotation,
* this traverses tokens preceded by the last property, then returns the
* first '}' token.
* @param {ASTNode} node The node to get. This node is an
* ObjectExpression or an ObjectPattern. And this node has one or
* more properties.
* @returns {Token} '}' token.
*/
function getClosingBraceOfObject(node) {
const lastProperty = node.properties.at(-1);
return sourceCode.getTokenAfter(
lastProperty,
astUtils.isClosingBraceToken,
);
}
/**
* Reports a given object node if spacing in curly braces is invalid.
* @param {ASTNode} node An ObjectExpression or ObjectPattern node to check.
* @returns {void}
*/
function checkForObject(node) {
if (node.properties.length === 0) {
return;
}
const first = sourceCode.getFirstToken(node),
last = getClosingBraceOfObject(node),
second = sourceCode.getTokenAfter(first, {
includeComments: true,
}),
penultimate = sourceCode.getTokenBefore(last, {
includeComments: true,
});
validateBraceSpacing(node, first, second, penultimate, last);
}
/**
* Reports a given import node if spacing in curly braces is invalid.
* @param {ASTNode} node An ImportDeclaration node to check.
* @returns {void}
*/
function checkForImport(node) {
if (node.specifiers.length === 0) {
return;
}
let firstSpecifier = node.specifiers[0];
const lastSpecifier = node.specifiers.at(-1);
if (lastSpecifier.type !== "ImportSpecifier") {
return;
}
if (firstSpecifier.type !== "ImportSpecifier") {
firstSpecifier = node.specifiers[1];
}
const first = sourceCode.getTokenBefore(firstSpecifier),
last = sourceCode.getTokenAfter(
lastSpecifier,
astUtils.isNotCommaToken,
),
second = sourceCode.getTokenAfter(first, {
includeComments: true,
}),
penultimate = sourceCode.getTokenBefore(last, {
includeComments: true,
});
validateBraceSpacing(node, first, second, penultimate, last);
}
/**
* Reports a given export node if spacing in curly braces is invalid.
* @param {ASTNode} node An ExportNamedDeclaration node to check.
* @returns {void}
*/
function checkForExport(node) {
if (node.specifiers.length === 0) {
return;
}
const firstSpecifier = node.specifiers[0],
lastSpecifier = node.specifiers.at(-1),
first = sourceCode.getTokenBefore(firstSpecifier),
last = sourceCode.getTokenAfter(
lastSpecifier,
astUtils.isNotCommaToken,
),
second = sourceCode.getTokenAfter(first, {
includeComments: true,
}),
penultimate = sourceCode.getTokenBefore(last, {
includeComments: true,
});
validateBraceSpacing(node, first, second, penultimate, last);
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
// var {x} = y;
ObjectPattern: checkForObject,
// var y = {x: 'y'}
ObjectExpression: checkForObject,
// import {y} from 'x';
ImportDeclaration: checkForImport,
// export {name} from 'yo';
ExportNamedDeclaration: checkForExport,
};
},
};

View File

@@ -0,0 +1,9 @@
import ws from "./ws";
const handler = {
scheme: "wss",
domainHost: ws.domainHost,
parse: ws.parse,
serialize: ws.serialize
};
export default handler;
//# sourceMappingURL=wss.js.map

View File

@@ -0,0 +1,27 @@
'use strict'
const split = require('./')
const bench = require('fastbench')
const binarySplit = require('binary-split')
const fs = require('fs')
function benchSplit (cb) {
fs.createReadStream('package.json')
.pipe(split())
.on('end', cb)
.resume()
}
function benchBinarySplit (cb) {
fs.createReadStream('package.json')
.pipe(binarySplit())
.on('end', cb)
.resume()
}
const run = bench([
benchSplit,
benchBinarySplit
], 10000)
run(run)

View File

@@ -0,0 +1,297 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeToCurve = exports.hashToCurve = exports.secp256k1_hasher = exports.schnorr = exports.secp256k1 = void 0;
/**
* SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
*
* Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
* check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const sha2_js_1 = require("@noble/hashes/sha2.js");
const utils_js_1 = require("@noble/hashes/utils.js");
const _shortw_utils_ts_1 = require("./_shortw_utils.js");
const hash_to_curve_ts_1 = require("./abstract/hash-to-curve.js");
const modular_ts_1 = require("./abstract/modular.js");
const weierstrass_ts_1 = require("./abstract/weierstrass.js");
const utils_ts_1 = require("./utils.js");
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
h: BigInt(1),
a: BigInt(0),
b: BigInt(7),
Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
basises: [
[BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
[BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
* √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
* (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
*/
function sqrtMod(y) {
const P = secp256k1_CURVE.p;
// prettier-ignore
const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
// prettier-ignore
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
const b2 = (y * y * y) % P; // x^3, 11
const b3 = (b2 * b2 * y) % P; // x^7
const b6 = ((0, modular_ts_1.pow2)(b3, _3n, P) * b3) % P;
const b9 = ((0, modular_ts_1.pow2)(b6, _3n, P) * b3) % P;
const b11 = ((0, modular_ts_1.pow2)(b9, _2n, P) * b2) % P;
const b22 = ((0, modular_ts_1.pow2)(b11, _11n, P) * b11) % P;
const b44 = ((0, modular_ts_1.pow2)(b22, _22n, P) * b22) % P;
const b88 = ((0, modular_ts_1.pow2)(b44, _44n, P) * b44) % P;
const b176 = ((0, modular_ts_1.pow2)(b88, _88n, P) * b88) % P;
const b220 = ((0, modular_ts_1.pow2)(b176, _44n, P) * b44) % P;
const b223 = ((0, modular_ts_1.pow2)(b220, _3n, P) * b3) % P;
const t1 = ((0, modular_ts_1.pow2)(b223, _23n, P) * b22) % P;
const t2 = ((0, modular_ts_1.pow2)(t1, _6n, P) * b2) % P;
const root = (0, modular_ts_1.pow2)(t2, _2n, P);
if (!Fpk1.eql(Fpk1.sqr(root), y))
throw new Error('Cannot find square root');
return root;
}
const Fpk1 = (0, modular_ts_1.Field)(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
* secp256k1 curve, ECDSA and ECDH methods.
*
* Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
*
* @example
* ```js
* import { secp256k1 } from '@noble/curves/secp256k1';
* const { secretKey, publicKey } = secp256k1.keygen();
* const msg = new TextEncoder().encode('hello');
* const sig = secp256k1.sign(msg, secretKey);
* const isValid = secp256k1.verify(sig, msg, publicKey) === true;
* ```
*/
exports.secp256k1 = (0, _shortw_utils_ts_1.createCurve)({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha2_js_1.sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
let tagP = TAGGED_HASH_PREFIXES[tag];
if (tagP === undefined) {
const tagH = (0, sha2_js_1.sha256)((0, utils_ts_1.utf8ToBytes)(tag));
tagP = (0, utils_ts_1.concatBytes)(tagH, tagH);
TAGGED_HASH_PREFIXES[tag] = tagP;
}
return (0, sha2_js_1.sha256)((0, utils_ts_1.concatBytes)(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => exports.secp256k1.Point)();
const hasEven = (y) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
const { Fn, BASE } = Pointk1;
const d_ = (0, weierstrass_ts_1._normFnElement)(Fn, priv);
const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
return { scalar, bytes: pointToBytes(p) };
}
/**
* lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
* @returns valid point checked for being on-curve
*/
function lift_x(x) {
const Fp = Fpk1;
if (!Fp.isValidNot0(x))
throw new Error('invalid x: Fail if x ≥ p');
const xx = Fp.create(x * x);
const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
// Return the unique point P such that x(P) = x and
// y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
if (!hasEven(y))
y = Fp.neg(y);
const p = Pointk1.fromAffine({ x, y });
p.assertValidity();
return p;
}
const num = utils_ts_1.bytesToNumberBE;
/**
* Create tagged hash, convert it to bigint, reduce modulo-n.
*/
function challenge(...args) {
return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
* Schnorr public key is just `x` coordinate of Point as per BIP340.
*/
function schnorrGetPublicKey(secretKey) {
return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
* Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
* auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
*/
function schnorrSign(message, secretKey, auxRand = (0, utils_js_1.randomBytes)(32)) {
const { Fn } = Pointk1;
const m = (0, utils_ts_1.ensureBytes)('message', message);
const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
const a = (0, utils_ts_1.ensureBytes)('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
// Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
sig.set(rx, 0);
sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
// If Verify(bytes(P), m, sig) (see below) returns failure, abort
if (!schnorrVerify(sig, m, px))
throw new Error('sign: Invalid signature produced');
return sig;
}
/**
* Verifies Schnorr signature.
* Will swallow errors & return false except for initial type validation of arguments.
*/
function schnorrVerify(signature, message, publicKey) {
const { Fn, BASE } = Pointk1;
const sig = (0, utils_ts_1.ensureBytes)('signature', signature, 64);
const m = (0, utils_ts_1.ensureBytes)('message', message);
const pub = (0, utils_ts_1.ensureBytes)('publicKey', publicKey, 32);
try {
const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
if (!(0, utils_ts_1.inRange)(r, _1n, secp256k1_CURVE.p))
return false;
const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
if (!(0, utils_ts_1.inRange)(s, _1n, secp256k1_CURVE.n))
return false;
// int(challenge(bytes(r)||bytes(P)||m))%n
const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
// R = s⋅G - e⋅P, where -eP == (n-e)P
const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
const { x, y } = R.toAffine();
// Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
if (R.is0() || !hasEven(y) || x !== r)
return false;
return true;
}
catch (error) {
return false;
}
}
/**
* Schnorr signatures over secp256k1.
* https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
* @example
* ```js
* import { schnorr } from '@noble/curves/secp256k1';
* const { secretKey, publicKey } = schnorr.keygen();
* // const publicKey = schnorr.getPublicKey(secretKey);
* const msg = new TextEncoder().encode('hello');
* const sig = schnorr.sign(msg, secretKey);
* const isValid = schnorr.verify(sig, msg, publicKey);
* ```
*/
exports.schnorr = (() => {
const size = 32;
const seedLength = 48;
const randomSecretKey = (seed = (0, utils_js_1.randomBytes)(seedLength)) => {
return (0, modular_ts_1.mapHashToField)(seed, secp256k1_CURVE.n);
};
// TODO: remove
exports.secp256k1.utils.randomSecretKey;
function keygen(seed) {
const secretKey = randomSecretKey(seed);
return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
}
return {
keygen,
getPublicKey: schnorrGetPublicKey,
sign: schnorrSign,
verify: schnorrVerify,
Point: Pointk1,
utils: {
randomSecretKey: randomSecretKey,
randomPrivateKey: randomSecretKey,
taggedHash,
// TODO: remove
lift_x,
pointToBytes,
numberToBytesBE: utils_ts_1.numberToBytesBE,
bytesToNumberBE: utils_ts_1.bytesToNumberBE,
mod: modular_ts_1.mod,
},
lengths: {
secretKey: size,
publicKey: size,
publicKeyHasPrefix: false,
signature: size * 2,
seed: seedLength,
},
};
})();
const isoMap = /* @__PURE__ */ (() => (0, hash_to_curve_ts_1.isogenyMap)(Fpk1, [
// xNum
[
'0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
'0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
'0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
'0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
],
// xDen
[
'0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
'0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
'0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
],
// yNum
[
'0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
'0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
'0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
'0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
],
// yDen
[
'0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
'0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
'0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
'0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => (0, weierstrass_ts_1.mapToCurveSimpleSWU)(Fpk1, {
A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
B: BigInt('1771'),
Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
exports.secp256k1_hasher = (() => (0, hash_to_curve_ts_1.createHasher)(exports.secp256k1.Point, (scalars) => {
const { x, y } = mapSWU(Fpk1.create(scalars[0]));
return isoMap(x, y);
}, {
DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
p: Fpk1.ORDER,
m: 1,
k: 128,
expand: 'xmd',
hash: sha2_js_1.sha256,
}))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
exports.hashToCurve = (() => exports.secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
exports.encodeToCurve = (() => exports.secp256k1_hasher.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_export_star.cjs",
"module": "../../esm/_export_star.js"
}

View File

@@ -0,0 +1,219 @@
/**
* @fileoverview Rule to count multiple spaces in regular expressions
* @author Matt DuVall <http://www.mattduvall.com/>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
const regexpp = require("@eslint-community/regexpp");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const regExpParser = new regexpp.RegExpParser();
const DOUBLE_SPACE = / {2}/u;
/**
* Check if node is a string
* @param {ASTNode} node node to evaluate
* @returns {boolean} True if its a string
* @private
*/
function isString(node) {
return node && node.type === "Literal" && typeof node.value === "string";
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Disallow multiple spaces in regular expressions",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-regex-spaces",
},
schema: [],
fixable: "code",
messages: {
multipleSpaces: "Spaces are hard to count. Use {{{length}}}.",
},
},
create(context) {
const sourceCode = context.sourceCode;
/**
* Validate regular expression
* @param {ASTNode} nodeToReport Node to report.
* @param {string} pattern Regular expression pattern to validate.
* @param {string} rawPattern Raw representation of the pattern in the source code.
* @param {number} rawPatternStartRange Start range of the pattern in the source code.
* @param {string} flags Regular expression flags.
* @returns {void}
* @private
*/
function checkRegex(
nodeToReport,
pattern,
rawPattern,
rawPatternStartRange,
flags,
) {
// Skip if there are no consecutive spaces in the source code, to avoid reporting e.g., RegExp(' \ ').
if (!DOUBLE_SPACE.test(rawPattern)) {
return;
}
const characterClassNodes = [];
let regExpAST;
try {
regExpAST = regExpParser.parsePattern(
pattern,
0,
pattern.length,
{
unicode: flags.includes("u"),
unicodeSets: flags.includes("v"),
},
);
} catch {
// Ignore regular expressions with syntax errors
return;
}
regexpp.visitRegExpAST(regExpAST, {
onCharacterClassEnter(ccNode) {
characterClassNodes.push(ccNode);
},
});
const spacesPattern = /( {2,})(?: [+*{?]|[^+*{?]|$)/gu;
let match;
while ((match = spacesPattern.exec(pattern))) {
const {
1: { length },
index,
} = match;
// Report only consecutive spaces that are not in character classes.
if (
characterClassNodes.every(
({ start, end }) => index < start || end <= index,
)
) {
context.report({
node: nodeToReport,
messageId: "multipleSpaces",
data: { length },
fix(fixer) {
if (pattern !== rawPattern) {
return null;
}
return fixer.replaceTextRange(
[
rawPatternStartRange + index,
rawPatternStartRange + index + length,
],
` {${length}}`,
);
},
});
// Report only the first occurrence of consecutive spaces
return;
}
}
}
/**
* Validate regular expression literals
* @param {ASTNode} node node to validate
* @returns {void}
* @private
*/
function checkLiteral(node) {
if (node.regex) {
const pattern = node.regex.pattern;
const rawPattern = node.raw.slice(1, node.raw.lastIndexOf("/"));
const rawPatternStartRange = node.range[0] + 1;
const flags = node.regex.flags;
checkRegex(
node,
pattern,
rawPattern,
rawPatternStartRange,
flags,
);
}
}
/**
* Validate strings passed to the RegExp constructor
* @param {ASTNode} node node to validate
* @returns {void}
* @private
*/
function checkFunction(node) {
const scope = sourceCode.getScope(node);
const regExpVar = astUtils.getVariableByName(scope, "RegExp");
const shadowed = regExpVar && regExpVar.defs.length > 0;
const patternNode = node.arguments[0];
if (
node.callee.type === "Identifier" &&
node.callee.name === "RegExp" &&
isString(patternNode) &&
!shadowed
) {
const pattern = patternNode.value;
const rawPattern = patternNode.raw.slice(1, -1);
const rawPatternStartRange = patternNode.range[0] + 1;
let flags;
if (node.arguments.length < 2) {
// It has no flags.
flags = "";
} else {
const flagsNode = node.arguments[1];
if (isString(flagsNode)) {
flags = flagsNode.value;
} else {
// The flags cannot be determined.
return;
}
}
checkRegex(
node,
pattern,
rawPattern,
rawPatternStartRange,
flags,
);
}
}
return {
Literal: checkLiteral,
CallExpression: checkFunction,
NewExpression: checkFunction,
};
},
};

View File

@@ -0,0 +1,136 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
const util = __importStar(require("../core/util.cjs"));
const error = () => {
const Sizable = {
string: { unit: "χαρακτήρες", verb: "να έχει" },
file: { unit: "bytes", verb: "να έχει" },
array: { unit: "στοιχεία", verb: "να έχει" },
set: { unit: "στοιχεία", verb: "να έχει" },
map: { unit: "καταχωρήσεις", verb: "να έχει" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "είσοδος",
email: "διεύθυνση email",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO ημερομηνία και ώρα",
date: "ISO ημερομηνία",
time: "ISO ώρα",
duration: "ISO διάρκεια",
ipv4: "διεύθυνση IPv4",
ipv6: "διεύθυνση IPv6",
mac: "διεύθυνση MAC",
cidrv4: "εύρος IPv4",
cidrv6: "εύρος IPv6",
base64: "συμβολοσειρά κωδικοποιημένη σε base64",
base64url: "συμβολοσειρά κωδικοποιημένη σε base64url",
json_string: "συμβολοσειρά JSON",
e164: "αριθμός E.164",
jwt: "JWT",
template_literal: "είσοδος",
};
const TypeDictionary = {
nan: "NaN",
};
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 (typeof issue.expected === "string" && /^[A-Z]/.test(issue.expected)) {
return `Μη έγκυρη είσοδος: αναμενόταν instanceof ${issue.expected}, λήφθηκε ${received}`;
}
return `Μη έγκυρη είσοδος: αναμενόταν ${expected}, λήφθηκε ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Μη έγκυρη είσοδος: αναμενόταν ${util.stringifyPrimitive(issue.values[0])}`;
return `Μη έγκυρη επιλογή: αναμενόταν ένα από ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Πολύ μεγάλο: αναμενόταν ${issue.origin ?? "τιμή"} να έχει ${adj}${issue.maximum.toString()} ${sizing.unit ?? "στοιχεία"}`;
return `Πολύ μεγάλο: αναμενόταν ${issue.origin ?? "τιμή"} να είναι ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Πολύ μικρό: αναμενόταν ${issue.origin} να έχει ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Πολύ μικρό: αναμενόταν ${issue.origin} να είναι ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with") {
return `Μη έγκυρη συμβολοσειρά: πρέπει να ξεκινά με "${_issue.prefix}"`;
}
if (_issue.format === "ends_with")
return `Μη έγκυρη συμβολοσειρά: πρέπει να τελειώνει με "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Μη έγκυρη συμβολοσειρά: πρέπει να περιέχει "${_issue.includes}"`;
if (_issue.format === "regex")
return `Μη έγκυρη συμβολοσειρά: πρέπει να ταιριάζει με το μοτίβο ${_issue.pattern}`;
return `Μη έγκυρο: ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Μη έγκυρος αριθμός: πρέπει να είναι πολλαπλάσιο του ${issue.divisor}`;
case "unrecognized_keys":
return `Άγνωστ${issue.keys.length > 1 ? "α" : "ο"} κλειδ${issue.keys.length > 1 ? "ιά" : "ί"}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Μη έγκυρο κλειδί στο ${issue.origin}`;
case "invalid_union":
return "Μη έγκυρη είσοδος";
case "invalid_element":
return `Μη έγκυρη τιμή στο ${issue.origin}`;
default:
return `Μη έγκυρη είσοδος`;
}
};
};
function default_1() {
return {
localeError: error(),
};
}
module.exports = exports.default;

View File

@@ -0,0 +1,50 @@
'use strict'
const formatters = {
level (label, number) {
return {
log: {
level: label
}
}
},
bindings (bindings) {
return {
process: {
pid: bindings.pid
},
host: {
name: bindings.hostname
}
}
},
log (obj) {
return { foo: 'bar', ...obj }
}
}
const bench = require('fastbench')
const pino = require('../')
delete require.cache[require.resolve('../')]
const pinoNoFormatters = require('../')(pino.destination('/dev/null'))
delete require.cache[require.resolve('../')]
const pinoFormatters = require('../')({ formatters }, pino.destination('/dev/null'))
const max = 10
const run = bench([
function benchPinoNoFormatters (cb) {
for (var i = 0; i < max; i++) {
pinoNoFormatters.info({ hello: 'world' })
}
setImmediate(cb)
},
function benchPinoFormatters (cb) {
for (var i = 0; i < max; i++) {
pinoFormatters.info({ hello: 'world' })
}
setImmediate(cb)
}
], 10000)
run(run)

View File

@@ -0,0 +1,187 @@
/**
* @fileoverview Enforces that a return statement is present in property getters.
* @author Aladdin-ADD(hh_2013@foxmail.com)
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
const { isAnySegmentReachable } = require("./utils/code-path-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
defaultOptions: [
{
allowImplicit: false,
},
],
docs: {
description: "Enforce `return` statements in getters",
recommended: true,
url: "https://eslint.org/docs/latest/rules/getter-return",
},
fixable: null,
schema: [
{
type: "object",
properties: {
allowImplicit: {
type: "boolean",
},
},
additionalProperties: false,
},
],
messages: {
expected: "Expected to return a value in {{name}}.",
expectedAlways: "Expected {{name}} to always return a value.",
},
},
create(context) {
const [{ allowImplicit }] = context.options;
const sourceCode = context.sourceCode;
let funcInfo = {
upper: null,
codePath: null,
hasReturn: false,
shouldCheck: false,
node: null,
currentSegments: [],
};
/**
* Checks whether or not the last code path segment is reachable.
* Then reports this function if the segment is reachable.
*
* If the last code path segment is reachable, there are paths which are not
* returned or thrown.
* @param {ASTNode} node A node to check.
* @returns {void}
*/
function checkLastSegment(node) {
if (
funcInfo.shouldCheck &&
isAnySegmentReachable(funcInfo.currentSegments)
) {
context.report({
node,
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
messageId: funcInfo.hasReturn
? "expectedAlways"
: "expected",
data: {
name: astUtils.getFunctionNameWithKind(funcInfo.node),
},
});
}
}
/**
* Checks whether a node means a getter function.
* @param {ASTNode} node a node to check.
* @returns {boolean} if node means a getter, return true; else return false.
*/
function isGetter(node) {
const parent = node.parent;
if (
TARGET_NODE_TYPE.test(node.type) &&
node.body.type === "BlockStatement"
) {
if (parent.kind === "get") {
return true;
}
if (
parent.type === "Property" &&
astUtils.getStaticPropertyName(parent) === "get" &&
parent.parent.type === "ObjectExpression" &&
astUtils.isPropertyDescriptor(parent.parent, sourceCode)
) {
// Getter in a property descriptor
return true;
}
}
return false;
}
return {
// Stacks this function's information.
onCodePathStart(codePath, node) {
funcInfo = {
upper: funcInfo,
codePath,
hasReturn: false,
shouldCheck: isGetter(node),
node,
currentSegments: new Set(),
};
},
// Pops this function's information.
onCodePathEnd() {
funcInfo = funcInfo.upper;
},
onUnreachableCodePathSegmentStart(segment) {
funcInfo.currentSegments.add(segment);
},
onUnreachableCodePathSegmentEnd(segment) {
funcInfo.currentSegments.delete(segment);
},
onCodePathSegmentStart(segment) {
funcInfo.currentSegments.add(segment);
},
onCodePathSegmentEnd(segment) {
funcInfo.currentSegments.delete(segment);
},
// Checks the return statement is valid.
ReturnStatement(node) {
if (funcInfo.shouldCheck) {
funcInfo.hasReturn = true;
// if allowImplicit: false, should also check node.argument
if (!allowImplicit && !node.argument) {
context.report({
node,
messageId: "expected",
data: {
name: astUtils.getFunctionNameWithKind(
funcInfo.node,
),
},
});
}
}
},
// Reports a given function if the last path is reachable.
"FunctionExpression:exit": checkLastSegment,
"ArrowFunctionExpression:exit": checkLastSegment,
};
},
};

View File

@@ -0,0 +1,37 @@
'use strict'
/**
* This file is packaged using pkg in order to test if worker.js works in that context.
* Note: We can't use node:test here because it crashes inside pkg bundles due to V8 internals.
*/
const assert = require('node:assert')
const { join } = require('path')
const { file } = require('../helper')
const ThreadStream = require('../..')
globalThis.__bundlerPathsOverrides = {
'thread-stream-worker': join(__dirname, '..', 'custom-worker.js')
}
const dest = file()
process.on('uncaughtException', (error) => {
console.error(error)
process.exit(1)
})
const stream = new ThreadStream({
filename: join(__dirname, '..', 'to-file.js'),
workerData: { dest },
sync: true
})
stream.worker.removeAllListeners('message')
stream.worker.once('message', (message) => {
assert.strictEqual(message.code, 'CUSTOM-WORKER-CALLED')
console.log('pkg test passed')
process.exit(0)
})
stream.end()

View File

@@ -0,0 +1,62 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.es2015_iterable = void 0;
const base_config_1 = require("./base-config");
const es2015_symbol_1 = require("./es2015.symbol");
exports.es2015_iterable = {
libs: [es2015_symbol_1.es2015_symbol],
variables: [
['SymbolConstructor', base_config_1.TYPE],
['IteratorYieldResult', base_config_1.TYPE],
['IteratorReturnResult', base_config_1.TYPE],
['IteratorResult', base_config_1.TYPE],
['Iterator', base_config_1.TYPE],
['Iterable', base_config_1.TYPE],
['IterableIterator', base_config_1.TYPE],
['IteratorObject', base_config_1.TYPE],
['BuiltinIteratorReturn', base_config_1.TYPE],
['ArrayIterator', base_config_1.TYPE],
['Array', base_config_1.TYPE],
['ArrayConstructor', base_config_1.TYPE],
['ReadonlyArray', base_config_1.TYPE],
['IArguments', base_config_1.TYPE],
['MapIterator', base_config_1.TYPE],
['Map', base_config_1.TYPE],
['ReadonlyMap', base_config_1.TYPE],
['MapConstructor', base_config_1.TYPE],
['WeakMap', base_config_1.TYPE],
['WeakMapConstructor', base_config_1.TYPE],
['SetIterator', base_config_1.TYPE],
['Set', base_config_1.TYPE],
['ReadonlySet', base_config_1.TYPE],
['SetConstructor', base_config_1.TYPE],
['WeakSet', base_config_1.TYPE],
['WeakSetConstructor', base_config_1.TYPE],
['Promise', base_config_1.TYPE],
['PromiseConstructor', base_config_1.TYPE],
['StringIterator', base_config_1.TYPE],
['String', base_config_1.TYPE],
['Int8Array', base_config_1.TYPE],
['Int8ArrayConstructor', base_config_1.TYPE],
['Uint8Array', base_config_1.TYPE],
['Uint8ArrayConstructor', base_config_1.TYPE],
['Uint8ClampedArray', base_config_1.TYPE],
['Uint8ClampedArrayConstructor', base_config_1.TYPE],
['Int16Array', base_config_1.TYPE],
['Int16ArrayConstructor', base_config_1.TYPE],
['Uint16Array', base_config_1.TYPE],
['Uint16ArrayConstructor', base_config_1.TYPE],
['Int32Array', base_config_1.TYPE],
['Int32ArrayConstructor', base_config_1.TYPE],
['Uint32Array', base_config_1.TYPE],
['Uint32ArrayConstructor', base_config_1.TYPE],
['Float32Array', base_config_1.TYPE],
['Float32ArrayConstructor', base_config_1.TYPE],
['Float64Array', base_config_1.TYPE],
['Float64ArrayConstructor', base_config_1.TYPE],
],
};