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,97 @@
{
"name": "@vitest/mocker",
"type": "module",
"version": "4.1.10",
"description": "Vitest module mocker implementation",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/mocker",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
"directory": "packages/mocker"
},
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"keywords": [
"vitest",
"test",
"mock"
],
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./node": {
"types": "./dist/node.d.ts",
"default": "./dist/node.js"
},
"./browser": {
"types": "./dist/browser.d.ts",
"default": "./dist/browser.js"
},
"./redirect": {
"types": "./dist/redirect.d.ts",
"default": "./dist/redirect.js"
},
"./automock": {
"types": "./dist/automock.d.ts",
"default": "./dist/automock.js"
},
"./register": {
"types": "./dist/register.d.ts",
"default": "./dist/register.js"
},
"./auto-register": {
"types": "./dist/register.d.ts",
"default": "./dist/register.js"
},
"./transforms": {
"types": "./dist/transforms.d.ts",
"default": "./dist/transforms.js"
},
"./package.json": "./package.json"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"*.d.ts",
"dist"
],
"peerDependencies": {
"msw": "^2.4.9",
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"msw": {
"optional": true
},
"vite": {
"optional": true
}
},
"dependencies": {
"estree-walker": "^3.0.3",
"magic-string": "^0.30.21",
"@vitest/spy": "4.1.10"
},
"devDependencies": {
"@types/estree": "^1.0.8",
"acorn-walk": "^8.3.5",
"cjs-module-lexer": "^2.2.0",
"es-module-lexer": "^2.0.0",
"msw": "^2.12.10",
"pathe": "^2.0.3",
"vite": "^6.3.5",
"@vitest/utils": "4.1.10",
"@vitest/spy": "4.1.10"
},
"scripts": {
"build": "premove dist && rollup -c",
"dev": "rollup -c --watch"
}
}

View File

@@ -0,0 +1,211 @@
#!/usr/bin/env node
/**
* @fileoverview Main CLI that is run via the eslint command.
* @author Nicholas C. Zakas
*/
/* eslint no-console:off -- CLI */
"use strict";
const mod = require("node:module");
// to use V8's code cache to speed up instantiation time
mod.enableCompileCache?.();
// must do this initialization *before* other requires in order to work
if (process.argv.includes("--debug")) {
require("debug").enable("eslint:*,-eslint:code-path,eslintrc:*");
}
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Read data from stdin til the end.
*
* Note: See
* - https://github.com/nodejs/node/blob/master/doc/api/process.md#processstdin
* - https://github.com/nodejs/node/blob/master/doc/api/process.md#a-note-on-process-io
* - https://lists.gnu.org/archive/html/bug-gnu-emacs/2016-01/msg00419.html
* - https://github.com/nodejs/node/issues/7439 (historical)
*
* On Windows using `fs.readFileSync(STDIN_FILE_DESCRIPTOR, "utf8")` seems
* to read 4096 bytes before blocking and never drains to read further data.
*
* The investigation on the Emacs thread indicates:
*
* > Emacs on MS-Windows uses pipes to communicate with subprocesses; a
* > pipe on Windows has a 4K buffer. So as soon as Emacs writes more than
* > 4096 bytes to the pipe, the pipe becomes full, and Emacs then waits for
* > the subprocess to read its end of the pipe, at which time Emacs will
* > write the rest of the stuff.
* @returns {Promise<string>} The read text.
*/
function readStdin() {
return new Promise((resolve, reject) => {
let content = "";
let chunk = "";
process.stdin
.setEncoding("utf8")
.on("readable", () => {
while ((chunk = process.stdin.read()) !== null) {
content += chunk;
}
})
.on("end", () => resolve(content))
.on("error", reject);
});
}
/**
* Spawns an external command and propagates its exit status.
* @param {string} command The command to run.
* @param {string[]} args The command arguments.
* @throws {Error} If the command cannot be spawned.
* @returns {void}
*/
function spawnExternalCommand(command, args) {
const spawn = require("cross-spawn");
const result = spawn.sync(command, args, {
encoding: "utf8",
stdio: "inherit",
});
if (result.error) {
throw result.error;
}
if (result.signal) {
process.kill(process.pid, result.signal);
return;
}
process.exitCode = result.status ?? 0;
}
/**
* Get the error message of a given value.
* @param {any} error The value to get.
* @returns {string} The error message.
*/
function getErrorMessage(error) {
// Lazy loading because this is used only if an error happened.
const util = require("node:util");
// Foolproof -- third-party module might throw non-object.
if (typeof error !== "object" || error === null) {
return String(error);
}
// Use templates if `error.messageTemplate` is present.
if (typeof error.messageTemplate === "string") {
try {
const template = require(`../messages/${error.messageTemplate}.js`);
return template(error.messageData || {});
} catch {
// Ignore template error then fallback to use `error.stack`.
}
}
// Use the stacktrace if it's an error object.
if (typeof error.stack === "string") {
return error.stack;
}
// Otherwise, dump the object.
return util.format("%o", error);
}
/**
* Tracks error messages that are shown to the user so we only ever show the
* same message once.
* @type {Set<string>}
*/
const displayedErrors = new Set();
/**
* Tracks whether an unexpected error was caught
* @type {boolean}
*/
let hadFatalError = false;
/**
* Catch and report unexpected error.
* @param {any} error The thrown error object.
* @returns {void}
*/
function onFatalError(error) {
process.exitCode = 2;
hadFatalError = true;
const { version } = require("../package.json");
const message = `
Oops! Something went wrong! :(
ESLint: ${version}
${getErrorMessage(error)}`;
if (!displayedErrors.has(message)) {
console.error(message);
displayedErrors.add(message);
}
}
//------------------------------------------------------------------------------
// Execution
//------------------------------------------------------------------------------
(async function main() {
process.on("uncaughtException", onFatalError);
process.on("unhandledRejection", onFatalError);
// Call the config initializer if `--init` is present.
if (process.argv.includes("--init")) {
// `eslint --init` has been moved to `@eslint/create-config`
console.warn(
"You can also run this command directly using 'npm init @eslint/config@latest'.",
);
spawnExternalCommand("npm", ["init", "@eslint/config@latest"]);
return;
}
// start the MCP server if `--mcp` is present
if (process.argv.includes("--mcp")) {
console.warn(
"You can also run this command directly using 'npx @eslint/mcp@latest'.",
);
spawnExternalCommand("npx", ["@eslint/mcp@latest"]);
return;
}
// Otherwise, call the CLI.
const cli = require("../lib/cli");
const exitCode = await cli.execute(
process.argv,
process.argv.includes("--stdin") ? await readStdin() : void 0,
);
/*
* If an uncaught exception or unhandled rejection was detected in the meantime,
* keep the fatal exit code 2 that is already assigned to `process.exitCode`.
* Without this condition, exit code 2 (unsuccessful execution) could be overwritten with
* 1 (successful execution, lint problems found) or even 0 (successful execution, no lint problems found).
* This ensures that unexpected errors that seemingly don't affect the success
* of the execution will still cause a non-zero exit code, as it's a common
* practice and the default behavior of Node.js to exit with non-zero
* in case of an uncaught exception or unhandled rejection.
*
* Otherwise, assign the exit code returned from CLI.
*/
if (!hadFatalError) {
process.exitCode = exitCode;
}
})().catch(onFatalError);

View File

@@ -0,0 +1,15 @@
"use strict";
module.exports = function (it) {
const { directoryPath } = it;
return `
ESLint couldn't find a configuration file. To set up a configuration file for this project, please run:
npm init @eslint/config@latest
ESLint looked for configuration files in ${directoryPath} and its ancestors. If it found none, it then looked in your home directory.
If you think you already have a configuration file or if you need more help, please stop by the ESLint Discord server: https://eslint.org/chat
`.trimStart();
};

View File

@@ -0,0 +1,39 @@
'use strict'
const Benchmark = require('benchmark')
const sjson = require('..')
const internals = {
text: '{ "a": 5, "b": 6, "__proto__": { "x": 7 }, "c": { "d": 0, "e": "text", "__proto__": { "y": 8 }, "f": { "g": 2 } } }'
}
const suite = new Benchmark.Suite()
suite
.add('JSON.parse', () => {
JSON.parse(internals.text)
})
.add('secure-json-parse parse', () => {
sjson.parse(internals.text, { protoAction: 'remove' })
})
.add('secure-json-parse safeParse', () => {
sjson.safeParse(internals.text)
})
.add('reviver', () => {
JSON.parse(internals.text, internals.reviver)
})
.on('cycle', (event) => {
console.log(String(event.target))
})
.on('complete', function () {
console.log('Fastest is ' + this.filter('fastest').map('name'))
})
.run({ async: true })
internals.reviver = function (key, value) {
if (key === '__proto__') {
return undefined
}
return value
}

View File

@@ -0,0 +1,22 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
interface ErrorConstructor {
/**
* Indicates whether the argument provided is a built-in Error instance or not.
*/
isError(error: unknown): error is Error;
}

View File

@@ -0,0 +1,81 @@
/**
* @fileoverview Rule to check for properties whose identifier ends with the string Sync
* @author Matt DuVall<http://mattduvall.com/>
* @deprecated in ESLint v7.0.0
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Node.js rules were moved out of ESLint core.",
url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules",
deprecatedSince: "7.0.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"eslint-plugin-n now maintains deprecated Node.js-related rules.",
plugin: {
name: "eslint-plugin-n",
url: "https://github.com/eslint-community/eslint-plugin-n",
},
rule: {
name: "no-sync",
url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-sync.md",
},
},
],
},
type: "suggestion",
docs: {
description: "Disallow synchronous methods",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-sync",
},
schema: [
{
type: "object",
properties: {
allowAtRootLevel: {
type: "boolean",
default: false,
},
},
additionalProperties: false,
},
],
messages: {
noSync: "Unexpected sync method: '{{propertyName}}'.",
},
},
create(context) {
const selector =
context.options[0] && context.options[0].allowAtRootLevel
? ":function MemberExpression[property.name=/.*Sync$/]"
: "MemberExpression[property.name=/.*Sync$/]";
return {
[selector](node) {
context.report({
node,
messageId: "noSync",
data: {
propertyName: node.property.name,
},
});
},
};
},
};

View File

@@ -0,0 +1,19 @@
// Code generated by Herebyfile.mjs generate:enums from internal/core/compileroptions.go. DO NOT EDIT.
export var ModuleKind;
(function (ModuleKind) {
ModuleKind[ModuleKind["None"] = 0] = "None";
ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
ModuleKind[ModuleKind["System"] = 4] = "System";
ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
ModuleKind[ModuleKind["ES2022"] = 7] = "ES2022";
ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
ModuleKind[ModuleKind["Node16"] = 100] = "Node16";
ModuleKind[ModuleKind["Node18"] = 101] = "Node18";
ModuleKind[ModuleKind["Node20"] = 102] = "Node20";
ModuleKind[ModuleKind["NodeNext"] = 199] = "NodeNext";
ModuleKind[ModuleKind["Preserve"] = 200] = "Preserve";
})(ModuleKind || (ModuleKind = {}));
//# sourceMappingURL=moduleKind.js.map

View File

@@ -0,0 +1,4 @@
import { SolanaErrorCode } from './codes';
export declare function getHumanReadableErrorMessage<TErrorCode extends SolanaErrorCode>(code: TErrorCode, context?: object): string;
export declare function getErrorMessage<TErrorCode extends SolanaErrorCode>(code: TErrorCode, context?: Record<string, unknown>): string;
//# sourceMappingURL=message-formatter.d.ts.map

View File

@@ -0,0 +1,21 @@
'use strict'
const SemVer = require('../classes/semver')
const inc = (version, release, options, identifier, identifierBase) => {
if (typeof (options) === 'string') {
identifierBase = identifier
identifier = options
options = undefined
}
try {
return new SemVer(
version instanceof SemVer ? version.version : version,
options
).inc(release, identifier, identifierBase).version
} catch (er) {
return null
}
}
module.exports = inc

View File

@@ -0,0 +1,116 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Array<T> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: T, fromIndex?: number): boolean;
}
interface ReadonlyArray<T> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: T, fromIndex?: number): boolean;
}
interface Int8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8ClampedArray {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int16Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint16Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float64Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}

View File

@@ -0,0 +1,11 @@
/**
* Shared utilities for the TypeScript API client.
*/
import getExePath from "#getExePath";
export function isSpawnOptions(options) {
return !("pipe" in options);
}
export function resolveExePath(options) {
return options.tsserverPath ?? getExePath();
}
//# sourceMappingURL=options.js.map

View File

@@ -0,0 +1,19 @@
'use strict'
/**
* Listens for an event on an object and resolves a promise when the event is emitted.
* @param {Object} emitter - The object to listen to.
* @param {string} event - The name of the event to listen for.
* @param {Function} fn - The function to call when the event is emitted.
* @returns {Promise} A promise that resolves when the event is emitted.
*/
function once (emitter, event, fn) {
return new Promise(resolve => {
emitter.on(event, (...args) => {
fn(...args)
resolve()
})
})
}
module.exports = { once }

View File

@@ -0,0 +1,207 @@
'use strict'
const defaults = require('./defaults')
const { isDate } = require('util/types')
function escapeElement(elementRepresentation) {
const escaped = elementRepresentation.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
return '"' + escaped + '"'
}
// convert a JS array to a postgres array literal
// uses comma separator so won't work for types like box that use
// a different array separator.
function arrayString(val) {
let result = '{'
for (let i = 0; i < val.length; i++) {
if (i > 0) {
result += ','
}
let item = val[i]
if (item == null) {
result += 'NULL'
} else if (Array.isArray(item)) {
result += arrayString(item)
} else if (ArrayBuffer.isView(item)) {
if (!(item instanceof Buffer)) {
item = Buffer.from(item.buffer, item.byteOffset, item.byteLength)
}
result += '\\\\x' + item.toString('hex')
} else {
result += escapeElement(prepareValue(item))
}
}
result += '}'
return result
}
// converts values from javascript types
// to their 'raw' counterparts for use as a postgres parameter
// note: you can override this function to provide your own conversion mechanism
// for complex types, etc...
const prepareValue = function (val, seen) {
// null and undefined are both null for postgres
if (val == null) {
return null
}
if (typeof val === 'object') {
if (val instanceof Buffer) {
return val
}
if (ArrayBuffer.isView(val)) {
return Buffer.from(val.buffer, val.byteOffset, val.byteLength)
}
if (isDate(val)) {
if (defaults.parseInputDatesAsUTC) {
return dateToStringUTC(val)
} else {
return dateToString(val)
}
}
if (Array.isArray(val)) {
return arrayString(val)
}
return prepareObject(val, seen)
}
return val.toString()
}
function prepareObject(val, seen) {
if (val && typeof val.toPostgres === 'function') {
seen = seen || []
if (seen.indexOf(val) !== -1) {
throw new Error('circular reference detected while preparing "' + val + '" for query')
}
seen.push(val)
return prepareValue(val.toPostgres(prepareValue), seen)
}
return JSON.stringify(val)
}
function dateToString(date) {
let offset = -date.getTimezoneOffset()
let year = date.getFullYear()
const isBCYear = year < 1
if (isBCYear) year = Math.abs(year) + 1 // negative years are 1 off their BC representation
let ret =
String(year).padStart(4, '0') +
'-' +
String(date.getMonth() + 1).padStart(2, '0') +
'-' +
String(date.getDate()).padStart(2, '0') +
'T' +
String(date.getHours()).padStart(2, '0') +
':' +
String(date.getMinutes()).padStart(2, '0') +
':' +
String(date.getSeconds()).padStart(2, '0') +
'.' +
String(date.getMilliseconds()).padStart(3, '0')
if (offset < 0) {
ret += '-'
offset *= -1
} else {
ret += '+'
}
ret += String(Math.floor(offset / 60)).padStart(2, '0') + ':' + String(offset % 60).padStart(2, '0')
if (isBCYear) ret += ' BC'
return ret
}
function dateToStringUTC(date) {
let year = date.getUTCFullYear()
const isBCYear = year < 1
if (isBCYear) year = Math.abs(year) + 1 // negative years are 1 off their BC representation
let ret =
String(year).padStart(4, '0') +
'-' +
String(date.getUTCMonth() + 1).padStart(2, '0') +
'-' +
String(date.getUTCDate()).padStart(2, '0') +
'T' +
String(date.getUTCHours()).padStart(2, '0') +
':' +
String(date.getUTCMinutes()).padStart(2, '0') +
':' +
String(date.getUTCSeconds()).padStart(2, '0') +
'.' +
String(date.getUTCMilliseconds()).padStart(3, '0')
ret += '+00:00'
if (isBCYear) ret += ' BC'
return ret
}
function normalizeQueryConfig(config, values, callback) {
// can take in strings or config objects
config = typeof config === 'string' ? { text: config } : config
if (values) {
if (typeof values === 'function') {
config.callback = values
} else {
config.values = values
}
}
if (callback) {
config.callback = callback
}
return config
}
// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
const escapeIdentifier = function (str) {
return '"' + str.replace(/"/g, '""') + '"'
}
const escapeLiteral = function (str) {
let hasBackslash = false
let escaped = "'"
if (str == null) {
return "''"
}
if (typeof str !== 'string') {
return "''"
}
for (let i = 0; i < str.length; i++) {
const c = str[i]
if (c === "'") {
escaped += c + c
} else if (c === '\\') {
escaped += c + c
hasBackslash = true
} else {
escaped += c
}
}
escaped += "'"
if (hasBackslash === true) {
escaped = ' E' + escaped
}
return escaped
}
module.exports = {
prepareValue: function prepareValueWrapper(value) {
// this ensures that extra arguments do not get passed into prepareValue
// by accident, eg: from calling values.map(utils.prepareValue)
return prepareValue(value)
},
normalizeQueryConfig,
escapeIdentifier,
escapeLiteral,
}

View File

@@ -0,0 +1,270 @@
"use strict";
var _to_array = require("./_to_array.cjs");
var _to_property_key = require("./_to_property_key.cjs");
var _type_of = require("./_type_of.cjs");
function _decorate(decorators, factory, superClass) {
var r = factory(function initialize(O) {
_initializeInstanceElements(O, decorated.elements);
}, superClass);
var decorated = _decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators);
_initializeClassElements(r.F, decorated.elements);
return _runClassFinishers(r.F, decorated.finishers);
}
function _createElementDescriptor(def) {
var key = _to_property_key._(def.key);
var descriptor;
if (def.kind === "method") {
descriptor = { value: def.value, writable: true, configurable: true, enumerable: false };
Object.defineProperty(def.value, "name", { value: _type_of._(key) === "symbol" ? "" : key, configurable: true });
} else if (def.kind === "get") descriptor = { get: def.value, configurable: true, enumerable: false };
else if (def.kind === "set") descriptor = { set: def.value, configurable: true, enumerable: false };
else if (def.kind === "field") descriptor = { configurable: true, writable: true, enumerable: true };
var element = { kind: def.kind === "field" ? "field" : "method", key: key, placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", descriptor: descriptor };
if (def.decorators) element.decorators = def.decorators;
if (def.kind === "field") element.initializer = def.value;
return element;
}
function _coalesceGetterSetter(element, other) {
if (element.descriptor.get !== undefined) other.descriptor.get = element.descriptor.get;
else other.descriptor.set = element.descriptor.set;
}
function _coalesceClassElements(elements) {
var newElements = [];
var isSameElement = function isSameElement(other) {
return other.kind === "method" && other.key === element.key && other.placement === element.placement;
};
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var other;
if (element.kind === "method" && (other = newElements.find(isSameElement))) {
if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) {
if (_hasDecorators(element) || _hasDecorators(other)) {
throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated.");
}
other.descriptor = element.descriptor;
} else {
if (_hasDecorators(element)) {
if (_hasDecorators(other)) {
throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ").");
}
other.decorators = element.decorators;
}
_coalesceGetterSetter(element, other);
}
} else {
newElements.push(element);
}
}
return newElements;
}
function _hasDecorators(element) {
return element.decorators && element.decorators.length;
}
function _isDataDescriptor(desc) {
return desc !== undefined && !(desc.value === undefined && desc.writable === undefined);
}
function _initializeClassElements(F, elements) {
var proto = F.prototype;
["method", "field"].forEach(function(kind) {
elements.forEach(function(element) {
var placement = element.placement;
if (element.kind === kind && (placement === "static" || placement === "prototype")) {
var receiver = placement === "static" ? F : proto;
_defineClassElement(receiver, element);
}
});
});
}
function _initializeInstanceElements(O, elements) {
["method", "field"].forEach(function(kind) {
elements.forEach(function(element) {
if (element.kind === kind && element.placement === "own") _defineClassElement(O, element);
});
});
}
function _defineClassElement(receiver, element) {
var descriptor = element.descriptor;
if (element.kind === "field") {
var initializer = element.initializer;
descriptor = { enumerable: descriptor.enumerable, writable: descriptor.writable, configurable: descriptor.configurable, value: initializer === void 0 ? void 0 : initializer.call(receiver) };
}
Object.defineProperty(receiver, element.key, descriptor);
}
function _decorateClass(elements, decorators) {
var newElements = [];
var finishers = [];
var placements = { static: [], prototype: [], own: [] };
elements.forEach(function(element) {
_addElementPlacement(element, placements);
});
elements.forEach(function(element) {
if (!_hasDecorators(element)) return newElements.push(element);
var elementFinishersExtras = _decorateElement(element, placements);
newElements.push(elementFinishersExtras.element);
newElements.push.apply(newElements, elementFinishersExtras.extras);
finishers.push.apply(finishers, elementFinishersExtras.finishers);
});
if (!decorators) return { elements: newElements, finishers: finishers };
var result = _decorateConstructor(newElements, decorators);
finishers.push.apply(finishers, result.finishers);
result.finishers = finishers;
return result;
}
function _addElementPlacement(element, placements, silent) {
var keys = placements[element.placement];
if (!silent && keys.indexOf(element.key) !== -1) throw new TypeError("Duplicated element (" + element.key + ")");
keys.push(element.key);
}
function _decorateElement(element, placements) {
var extras = [];
var finishers = [];
for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) {
var keys = placements[element.placement];
keys.splice(keys.indexOf(element.key), 1);
var elementObject = _fromElementDescriptor(element);
var elementFinisherExtras = _toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject);
element = elementFinisherExtras.element;
_addElementPlacement(element, placements);
if (elementFinisherExtras.finisher) finishers.push(elementFinisherExtras.finisher);
var newExtras = elementFinisherExtras.extras;
if (newExtras) {
for (var j = 0; j < newExtras.length; j++) _addElementPlacement(newExtras[j], placements);
extras.push.apply(extras, newExtras);
}
}
return { element: element, finishers: finishers, extras: extras };
}
function _decorateConstructor(elements, decorators) {
var finishers = [];
for (var i = decorators.length - 1; i >= 0; i--) {
var obj = _fromClassDescriptor(elements);
var elementsAndFinisher = _toClassDescriptor((0, decorators[i])(obj) || obj);
if (elementsAndFinisher.finisher !== undefined) finishers.push(elementsAndFinisher.finisher);
if (elementsAndFinisher.elements !== undefined) {
elements = elementsAndFinisher.elements;
for (var j = 0; j < elements.length - 1; j++) {
for (var k = j + 1; k < elements.length; k++) {
if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) {
throw new TypeError("Duplicated element (" + elements[j].key + ")");
}
}
}
}
}
return { elements: elements, finishers: finishers };
}
function _fromElementDescriptor(element) {
var obj = { kind: element.kind, key: element.key, placement: element.placement, descriptor: element.descriptor };
var desc = { value: "Descriptor", configurable: true };
Object.defineProperty(obj, Symbol.toStringTag, desc);
if (element.kind === "field") obj.initializer = element.initializer;
return obj;
}
function _toElementDescriptors(elementObjects) {
if (elementObjects === undefined) return;
return _to_array._(elementObjects).map(function(elementObject) {
var element = _toElementDescriptor(elementObject);
_disallowProperty(elementObject, "finisher", "An element descriptor");
_disallowProperty(elementObject, "extras", "An element descriptor");
return element;
});
}
function _toElementDescriptor(elementObject) {
var kind = String(elementObject.kind);
if (kind !== "method" && kind !== "field") {
throw new TypeError("An element descriptor's .kind property must be either \"method\" or" + " \"field\", but a decorator created an element descriptor with" + " .kind \"" + kind + "\"");
}
var key = _to_property_key._(elementObject.key);
var placement = String(elementObject.placement);
if (placement !== "static" && placement !== "prototype" && placement !== "own") {
throw new TypeError(
"An element descriptor's .placement property must be one of \"static\","
+ " \"prototype\" or \"own\", but a decorator created an element descriptor"
+ " with .placement \""
+ placement
+ "\""
);
}
var descriptor = elementObject.descriptor;
_disallowProperty(elementObject, "elements", "An element descriptor");
var element = { kind: kind, key: key, placement: placement, descriptor: Object.assign({}, descriptor) };
if (kind !== "field") _disallowProperty(elementObject, "initializer", "A method descriptor");
else {
_disallowProperty(descriptor, "get", "The property descriptor of a field descriptor");
_disallowProperty(descriptor, "set", "The property descriptor of a field descriptor");
_disallowProperty(descriptor, "value", "The property descriptor of a field descriptor");
element.initializer = elementObject.initializer;
}
return element;
}
function _toElementFinisherExtras(elementObject) {
var element = _toElementDescriptor(elementObject);
var finisher = _optionalCallableProperty(elementObject, "finisher");
var extras = _toElementDescriptors(elementObject.extras);
return { element: element, finisher: finisher, extras: extras };
}
function _fromClassDescriptor(elements) {
var obj = { kind: "class", elements: elements.map(_fromElementDescriptor) };
var desc = { value: "Descriptor", configurable: true };
Object.defineProperty(obj, Symbol.toStringTag, desc);
return obj;
}
function _toClassDescriptor(obj) {
var kind = String(obj.kind);
if (kind !== "class") {
throw new TypeError("A class descriptor's .kind property must be \"class\", but a decorator" + " created a class descriptor with .kind \"" + kind + "\"");
}
_disallowProperty(obj, "key", "A class descriptor");
_disallowProperty(obj, "placement", "A class descriptor");
_disallowProperty(obj, "descriptor", "A class descriptor");
_disallowProperty(obj, "initializer", "A class descriptor");
_disallowProperty(obj, "extras", "A class descriptor");
var finisher = _optionalCallableProperty(obj, "finisher");
var elements = _toElementDescriptors(obj.elements);
return { elements: elements, finisher: finisher };
}
function _disallowProperty(obj, name, objectType) {
if (obj[name] !== undefined) throw new TypeError(objectType + " can't have a ." + name + " property.");
}
function _optionalCallableProperty(obj, name) {
var value = obj[name];
if (value !== undefined && typeof value !== "function") {
throw new TypeError("Expected '" + name + "' to be a function");
}
return value;
}
function _runClassFinishers(constructor, finishers) {
for (var i = 0; i < finishers.length; i++) {
var newConstructor = (0, finishers[i])(constructor);
if (newConstructor !== undefined) {
if (typeof newConstructor !== "function") throw new TypeError("Finishers must return a constructor.");
constructor = newConstructor;
}
}
return constructor;
}
exports._ = _decorate;

View File

@@ -0,0 +1,126 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
const builtInArrays = new Set([
'Float32Array',
'Float64Array',
'Int16Array',
'Int32Array',
'Int8Array',
'Uint16Array',
'Uint32Array',
'Uint8Array',
'Uint8ClampedArray',
]);
exports.default = (0, util_1.createRule)({
name: 'consistent-generic-constructors',
meta: {
type: 'suggestion',
docs: {
description: 'Enforce specifying generic type arguments on type annotation or constructor name of a constructor call',
recommended: 'stylistic',
},
fixable: 'code',
messages: {
preferConstructor: 'The generic type arguments should be specified as part of the constructor type arguments.',
preferTypeAnnotation: 'The generic type arguments should be specified as part of the type annotation.',
},
schema: [
{
type: 'string',
description: 'Which constructor call syntax to prefer.',
enum: ['type-annotation', 'constructor'],
},
],
},
defaultOptions: ['constructor'],
create(context, [mode]) {
return {
'VariableDeclarator,PropertyDefinition,AccessorProperty,:matches(FunctionDeclaration,FunctionExpression) > AssignmentPattern'(node) {
function getLHSRHS() {
switch (node.type) {
case utils_1.AST_NODE_TYPES.VariableDeclarator:
return [node.id, node.init];
case utils_1.AST_NODE_TYPES.PropertyDefinition:
case utils_1.AST_NODE_TYPES.AccessorProperty:
return [node, node.value];
case utils_1.AST_NODE_TYPES.AssignmentPattern:
return [node.left, node.right];
default:
throw new Error(`Unhandled node type: ${node.type}`);
}
}
function isBuiltInArray(typeName) {
return (builtInArrays.has(typeName.name) &&
(0, util_1.isReferenceToGlobalFunction)(typeName.name, typeName, context.sourceCode));
}
const [lhsName, rhs] = getLHSRHS();
const lhs = lhsName.typeAnnotation?.typeAnnotation;
if (rhs?.type !== utils_1.AST_NODE_TYPES.NewExpression ||
rhs.callee.type !== utils_1.AST_NODE_TYPES.Identifier) {
return;
}
if (lhs &&
(lhs.type !== utils_1.AST_NODE_TYPES.TSTypeReference ||
lhs.typeName.type !== utils_1.AST_NODE_TYPES.Identifier ||
lhs.typeName.name !== rhs.callee.name ||
isBuiltInArray(lhs.typeName))) {
return;
}
if (mode === 'type-annotation') {
if (!lhs && rhs.typeArguments) {
const { callee, typeArguments } = rhs;
const typeAnnotation = context.sourceCode.getText(callee) +
context.sourceCode.getText(typeArguments);
context.report({
node,
messageId: 'preferTypeAnnotation',
fix(fixer) {
function getIDToAttachAnnotation() {
if (node.type !== utils_1.AST_NODE_TYPES.PropertyDefinition &&
node.type !== utils_1.AST_NODE_TYPES.AccessorProperty) {
return lhsName;
}
if (!node.computed) {
return node.key;
}
// If the property's computed, we have to attach the
// annotation after the square bracket, not the enclosed expression
return (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.key), util_1.NullThrowsReasons.MissingToken(']', 'key'));
}
return [
fixer.remove(typeArguments),
fixer.insertTextAfter(getIDToAttachAnnotation(), `: ${typeAnnotation}`),
];
},
});
}
return;
}
const isolatedDeclarations = context.languageOptions.parserOptions.isolatedDeclarations;
if (!isolatedDeclarations && lhs?.typeArguments && !rhs.typeArguments) {
const hasParens = context.sourceCode.getTokenAfter(rhs.callee)?.value === '(';
const extraComments = new Set(context.sourceCode.getCommentsInside(lhs.parent));
context.sourceCode
.getCommentsInside(lhs.typeArguments)
.forEach(c => extraComments.delete(c));
context.report({
node,
messageId: 'preferConstructor',
*fix(fixer) {
yield fixer.remove(lhs.parent);
for (const comment of extraComments) {
yield fixer.insertTextAfter(rhs.callee, context.sourceCode.getText(comment));
}
yield fixer.insertTextAfter(rhs.callee, context.sourceCode.getText(lhs.typeArguments));
if (!hasParens) {
yield fixer.insertTextAfter(rhs.callee, '()');
}
},
});
}
},
};
},
});

View File

@@ -0,0 +1,81 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
const promSchema = z.promise(
z.object({
name: z.string(),
age: z.number(),
})
);
test("promise inference", () => {
type promSchemaType = z.infer<typeof promSchema>;
expectTypeOf<promSchemaType>().toEqualTypeOf<Promise<{ name: string; age: number }>>();
});
test("promise parsing success", async () => {
// expect(() => promSchema.parse(Promise.resolve({ name: "Bobby", age: 10 }))).toThrow();
const pr = promSchema.parseAsync(Promise.resolve({ name: "Bobby", age: 10 }));
expect(pr).toBeInstanceOf(Promise);
const result = await pr;
expect(result).toMatchInlineSnapshot(`
{
"age": 10,
"name": "Bobby",
}
`);
});
test("promise parsing fail", async () => {
const bad = await promSchema.safeParseAsync(Promise.resolve({ name: "Bobby", age: "10" }));
expect(bad.success).toBe(false);
expect(bad.error).toBeInstanceOf(z.ZodError);
});
test("promise parsing fail 2", async () => {
const result = await promSchema.safeParseAsync(Promise.resolve({ name: "Bobby", age: "10" }));
expect(result.success).toBe(false);
expect(result.error).toBeInstanceOf(z.ZodError);
});
test("promise parsing fail", () => {
const bad = () => promSchema.parse({ then: () => {}, catch: {} });
expect(bad).toThrow();
});
test("sync promise parsing", () => {
expect(() => z.promise(z.string()).parse(Promise.resolve("asfd"))).toThrow();
});
const asyncFunction = z.function({
input: z.tuple([]),
output: promSchema,
});
test("async function pass", async () => {
const validatedFunction = asyncFunction.implementAsync(async () => {
return { name: "jimmy", age: 14 };
});
await expect(validatedFunction()).resolves.toEqual({
name: "jimmy",
age: 14,
});
});
test("async function fail", async () => {
const validatedFunction = asyncFunction.implementAsync(() => {
return Promise.resolve("asdf" as any);
});
await expect(validatedFunction()).rejects.toBeInstanceOf(z.core.$ZodError);
});
test("async promise parsing", () => {
const res = z.promise(z.number()).parseAsync(Promise.resolve(12));
expect(res).toBeInstanceOf(Promise);
});
test("resolves", () => {
const foo = z.literal("foo");
const res = z.promise(foo);
expect(res.unwrap()).toEqual(foo);
});

View File

@@ -0,0 +1,93 @@
{
"name": "buffer",
"description": "Node.js Buffer API, for the browser",
"version": "6.0.3",
"author": {
"name": "Feross Aboukhadijeh",
"email": "feross@feross.org",
"url": "https://feross.org"
},
"bugs": {
"url": "https://github.com/feross/buffer/issues"
},
"contributors": [
"Romain Beauxis <toots@rastageeks.org>",
"James Halliday <mail@substack.net>"
],
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.2.1"
},
"devDependencies": {
"airtap": "^3.0.0",
"benchmark": "^2.1.4",
"browserify": "^17.0.0",
"concat-stream": "^2.0.0",
"hyperquest": "^2.1.3",
"is-buffer": "^2.0.5",
"is-nan": "^1.3.0",
"split": "^1.0.1",
"standard": "*",
"tape": "^5.0.1",
"through2": "^4.0.2",
"uglify-js": "^3.11.5"
},
"homepage": "https://github.com/feross/buffer",
"jspm": {
"map": {
"./index.js": {
"node": "@node/buffer"
}
}
},
"keywords": [
"arraybuffer",
"browser",
"browserify",
"buffer",
"compatible",
"dataview",
"uint8array"
],
"license": "MIT",
"main": "index.js",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "git://github.com/feross/buffer.git"
},
"scripts": {
"perf": "browserify --debug perf/bracket-notation.js > perf/bundle.js && open perf/index.html",
"perf-node": "node perf/bracket-notation.js && node perf/concat.js && node perf/copy-big.js && node perf/copy.js && node perf/new-big.js && node perf/new.js && node perf/readDoubleBE.js && node perf/readFloatBE.js && node perf/readUInt32LE.js && node perf/slice.js && node perf/writeFloatBE.js",
"size": "browserify -r ./ | uglifyjs -c -m | gzip | wc -c",
"test": "standard && node ./bin/test.js",
"test-browser-old": "airtap -- test/*.js",
"test-browser-old-local": "airtap --local -- test/*.js",
"test-browser-new": "airtap -- test/*.js test/node/*.js",
"test-browser-new-local": "airtap --local -- test/*.js test/node/*.js",
"test-node": "tape test/*.js test/node/*.js",
"update-authors": "./bin/update-authors.sh"
},
"standard": {
"ignore": [
"test/node/**/*.js",
"test/common.js",
"test/_polyfill.js",
"perf/**/*.js"
]
},
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
}

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.withoutProjectParserOptions = withoutProjectParserOptions;
/**
* Removes options that prompt the parser to parse the project with type
* information. In other words, you can use this if you are invoking the parser
* directly, to ensure that one file will be parsed in isolation, which is much,
* much faster.
*
* @see https://github.com/typescript-eslint/typescript-eslint/issues/8428
*/
function withoutProjectParserOptions(opts) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- The variables are meant to be omitted
const { EXPERIMENTAL_useProjectService, project, projectService, ...rest } = opts;
return rest;
}

View File

@@ -0,0 +1,6 @@
{
"type": "module",
"main": "index.cjs",
"module": "index.js",
"react-native": "index.js"
}

View File

@@ -0,0 +1,35 @@
{
"keys-while": {
"name": "keys-while",
"browser": "Chrome Mobile 55.0.2883 (Android 6.0.0)",
"suite": "iter",
"hz": 50801.098785564085,
"success": true,
"fastest": true,
"rme": 0.028921852048030095,
"rhz": 1,
"sampleSize": 141
},
"keys-for": {
"name": "keys-for",
"browser": "Chrome Mobile 55.0.2883 (Android 6.0.0)",
"suite": "iter",
"hz": 48275.00969473481,
"success": true,
"fastest": false,
"rme": 0.0235223967226664,
"rhz": 0.9502749123302997,
"sampleSize": 140
},
"incr-for": {
"name": "incr-for",
"browser": "Chrome Mobile 55.0.2883 (Android 6.0.0)",
"suite": "iter",
"hz": 16517.995894922962,
"success": true,
"fastest": false,
"rme": 0.01887891379164421,
"rhz": 0.32515036662192837,
"sampleSize": 141
}
}