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,7 @@
import type * as errors from "../core/errors.js";
import km from "./km.js";
/** @deprecated Use `km` instead. */
export default function (): { localeError: errors.$ZodErrorMap } {
return km();
}

View File

@@ -0,0 +1,139 @@
"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: "ბაიტი", verb: "უნდა შეიცავდეს" },
array: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" },
set: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "შეყვანა",
email: "ელ-ფოსტის მისამართი",
url: "URL",
emoji: "ემოჯი",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "თარიღი-დრო",
date: "თარიღი",
time: "დრო",
duration: "ხანგრძლივობა",
ipv4: "IPv4 მისამართი",
ipv6: "IPv6 მისამართი",
cidrv4: "IPv4 დიაპაზონი",
cidrv6: "IPv6 დიაპაზონი",
base64: "base64-კოდირებული ველი",
base64url: "base64url-კოდირებული ველი",
json_string: "JSON ველი",
e164: "E.164 ნომერი",
jwt: "JWT",
template_literal: "შეყვანა",
};
const TypeDictionary = {
nan: "NaN",
number: "რიცხვი",
string: "ველი",
boolean: "ბულეანი",
function: "ფუნქცია",
array: "მასივი",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `არასწორი შეყვანა: მოსალოდნელი 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 ?? "მნიშვნელობა"} ${sizing.verb} ${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} ${sizing.verb} ${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 ? "ები" : "ი"}: ${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,3 @@
import * as z from "../v4/mini/external.cjs";
export * from "../v4/mini/external.cjs";
export { z };

View File

@@ -0,0 +1 @@
{"version":3,"file":"empty.js","sourceRoot":"","sources":["../src/empty.ts"],"names":[],"mappings":";;AAAA,kFAAkF;AAClF,0CAA0C;AAC1C,kBAAe,EAAE,CAAA"}

View File

@@ -0,0 +1,151 @@
export { ObjectSchema } from "@eslint/object-schema";
export type PropertyDefinition = $eslintobjectschema.PropertyDefinition;
export type ObjectDefinition = $eslintobjectschema.ObjectDefinition;
export type ConfigObject = $typests.ConfigObject;
export type FileMatcher = $typests.FileMatcher;
export type FilesMatcher = $typests.FilesMatcher;
export type ExtraConfigType = $typests.ExtraConfigType;
export type MinimatchOptions = $minimatch.MinimatchOptions;
export type ObjectSchemaInstance = ObjectSchema;
/**
* Represents an array of config objects and provides method for working with
* those config objects.
*/
export class ConfigArray extends Array<any> {
/**
* Creates a new instance of ConfigArray.
* @param {Iterable|Function|Object} configs An iterable yielding config
* objects, or a config function, or a config object.
* @param {Object} options The options for the ConfigArray.
* @param {string} [options.basePath="/"] The absolute path of the config file directory.
* Defaults to `"/"`.
* @param {boolean} [options.normalized=false] Flag indicating if the
* configs have already been normalized.
* @param {ObjectDefinition} [options.schema] The additional schema
* definitions to use for the ConfigArray schema.
* @param {ReadonlyArray<ExtraConfigType>} [options.extraConfigTypes] List of config types supported.
* @throws {TypeError} When the `basePath` is not a non-empty string,
*/
constructor(configs: Iterable<any> | Function | any, { basePath, normalized, schema: customSchema, extraConfigTypes, }?: {
basePath?: string;
normalized?: boolean;
schema?: ObjectDefinition;
extraConfigTypes?: ReadonlyArray<ExtraConfigType>;
});
/**
* The path of the config file that this array was loaded from.
* This is used to calculate filename matches.
* @property basePath
* @type {string}
*/
basePath: string;
/**
* The supported config types.
* @type {ReadonlyArray<ExtraConfigType>}
*/
extraConfigTypes: ReadonlyArray<ExtraConfigType>;
/**
* Returns the `files` globs from every config object in the array.
* This can be used to determine which files will be matched by a
* config array or to use as a glob pattern when no patterns are provided
* for a command line interface.
* @returns {Array<FilesMatcher>} An array of matchers.
*/
get files(): Array<FilesMatcher>;
/**
* Returns ignore matchers that should always be ignored regardless of
* the matching `files` fields in any configs. This is necessary to mimic
* the behavior of things like .gitignore and .eslintignore, allowing a
* globbing operation to be faster.
* @returns {Array<{ basePath?: string, name?: string, ignores: FileMatcher[] }>} An array of config objects representing global ignores.
*/
get ignores(): Array<{
basePath?: string;
name?: string;
ignores: FileMatcher[];
}>;
/**
* Indicates if the config array has been normalized.
* @returns {boolean} True if the config array is normalized, false if not.
*/
isNormalized(): boolean;
/**
* Normalizes a config array by flattening embedded arrays and executing
* config functions.
* @param {Object} [context] The context object for config functions.
* @returns {Promise<ConfigArray>} The current ConfigArray instance.
*/
normalize(context?: any): Promise<ConfigArray>;
/**
* Normalizes a config array by flattening embedded arrays and executing
* config functions.
* @param {Object} [context] The context object for config functions.
* @returns {ConfigArray} The current ConfigArray instance.
*/
normalizeSync(context?: any): ConfigArray;
/**
* Returns the config object for a given file path and a status that can be used to determine why a file has no config.
* @param {string} filePath The path of a file to get a config for.
* @returns {{ config?: Object, status: "ignored"|"external"|"unconfigured"|"matched" }}
* An object with an optional property `config` and property `status`.
* `config` is the config object for the specified file as returned by {@linkcode ConfigArray.getConfig},
* `status` a is one of the constants returned by {@linkcode ConfigArray.getConfigStatus}.
*/
getConfigWithStatus(filePath: string): {
config?: any;
status: "ignored" | "external" | "unconfigured" | "matched";
};
/**
* Returns the config object for a given file path.
* @param {string} filePath The path of a file to get a config for.
* @returns {Object|undefined} The config object for this file or `undefined`.
*/
getConfig(filePath: string): any | undefined;
/**
* Determines whether a file has a config or why it doesn't.
* @param {string} filePath The path of the file to check.
* @returns {"ignored"|"external"|"unconfigured"|"matched"} One of the following values:
* * `"ignored"`: the file is ignored
* * `"external"`: the file is outside the base path
* * `"unconfigured"`: the file is not matched by any config
* * `"matched"`: the file has a matching config
*/
getConfigStatus(filePath: string): "ignored" | "external" | "unconfigured" | "matched";
/**
* Determines if the given filepath is ignored based on the configs.
* @param {string} filePath The path of a file to check.
* @returns {boolean} True if the path is ignored, false if not.
* @deprecated Use `isFileIgnored` instead.
*/
isIgnored(filePath: string): boolean;
/**
* Determines if the given filepath is ignored based on the configs.
* @param {string} filePath The path of a file to check.
* @returns {boolean} True if the path is ignored, false if not.
*/
isFileIgnored(filePath: string): boolean;
/**
* Determines if the given directory is ignored based on the configs.
* This checks only default `ignores` that don't have `files` in the
* same config. A pattern such as `/foo` be considered to ignore the directory
* while a pattern such as `/foo/**` is not considered to ignore the
* directory because it is matching files.
* @param {string} directoryPath The path of a directory to check.
* @returns {boolean} True if the directory is ignored, false if not. Will
* return true for any directory that is not inside of `basePath`.
* @throws {Error} When the `ConfigArray` is not normalized.
*/
isDirectoryIgnored(directoryPath: string): boolean;
#private;
}
export namespace ConfigArraySymbol {
let isNormalized: symbol;
let configCache: symbol;
let schema: symbol;
let finalizeConfig: symbol;
let preprocessConfig: symbol;
}
import type * as $eslintobjectschema from "@eslint/object-schema";
import type * as $typests from "./types.cts";
import type * as $minimatch from "minimatch";
import { ObjectSchema } from '@eslint/object-schema';

View File

@@ -0,0 +1,11 @@
import type { TSESTree } from '@typescript-eslint/utils';
import type { SourceCode } from '@typescript-eslint/utils/ts-eslint';
/**
* Determines whether an opening parenthesis `(`, bracket `[` or backtick ``` ` ``` needs to be preceded by a semicolon.
* This opening parenthesis or bracket should be at the start of an `ExpressionStatement`, a `MethodDefinition` or at
* the start of the body of an `ArrowFunctionExpression`.
* @param sourceCode The source code object.
* @param node A node at the position where an opening parenthesis or bracket will be inserted.
* @returns Whether a semicolon is required before the opening parenthesis or bracket.
*/
export declare function needsPrecedingSemicolon(sourceCode: SourceCode, node: TSESTree.Node): boolean;

View File

@@ -0,0 +1,35 @@
{
"keys-while": {
"name": "keys-while",
"browser": "Firefox 54.0.0 (Windows 7 0.0.0)",
"suite": "iter",
"hz": 51288.89848137886,
"success": true,
"fastest": true,
"rme": 0.02056985493082276,
"rhz": 1,
"sampleSize": 167
},
"keys-for": {
"name": "keys-for",
"browser": "Firefox 54.0.0 (Windows 7 0.0.0)",
"suite": "iter",
"hz": 50917.49218801942,
"success": true,
"fastest": true,
"rme": 0.0218368615440906,
"rhz": 0.9927585441614761,
"sampleSize": 170
},
"incr-for": {
"name": "incr-for",
"browser": "Firefox 54.0.0 (Windows 7 0.0.0)",
"suite": "iter",
"hz": 4396.20812127132,
"success": true,
"fastest": false,
"rme": 0.011792452259220165,
"rhz": 0.08571461371640539,
"sampleSize": 173
}
}

View File

@@ -0,0 +1,193 @@
'use strict'
const bench = require('fastbench')
const pino = require('../')
const bunyan = require('bunyan')
const bole = require('bole')('bench')
const winston = require('winston')
const fs = require('node:fs')
const dest = fs.createWriteStream('/dev/null')
const plogNodeStream = pino(dest)
delete require.cache[require.resolve('../')]
const plogDest = require('../')(pino.destination('/dev/null'))
delete require.cache[require.resolve('../')]
const plogMinLength = require('../')(pino.destination({ dest: '/dev/null', sync: false, minLength: 4096 }))
delete require.cache[require.resolve('../')]
const deep = require('../package.json')
deep.deep = Object.assign({}, JSON.parse(JSON.stringify(deep)))
deep.deep.deep = Object.assign({}, JSON.parse(JSON.stringify(deep)))
deep.deep.deep.deep = Object.assign({}, JSON.parse(JSON.stringify(deep)))
const blog = bunyan.createLogger({
name: 'myapp',
streams: [{
level: 'trace',
stream: dest
}]
})
require('bole').output({
level: 'info',
stream: dest
}).setFastTime(true)
const chill = winston.createLogger({
transports: [
new winston.transports.Stream({
stream: fs.createWriteStream('/dev/null')
})
]
})
const max = 10
const run = bench([
function benchBunyanInterpolate (cb) {
for (var i = 0; i < max; i++) {
blog.info('hello %s', 'world')
}
setImmediate(cb)
},
function benchWinstonInterpolate (cb) {
for (var i = 0; i < max; i++) {
chill.log('info', 'hello %s', 'world')
}
setImmediate(cb)
},
function benchBoleInterpolate (cb) {
for (var i = 0; i < max; i++) {
bole.info('hello %s', 'world')
}
setImmediate(cb)
},
function benchPinoInterpolate (cb) {
for (var i = 0; i < max; i++) {
plogDest.info('hello %s', 'world')
}
setImmediate(cb)
},
function benchPinoMinLengthInterpolate (cb) {
for (var i = 0; i < max; i++) {
plogMinLength.info('hello %s', 'world')
}
setImmediate(cb)
},
function benchPinoNodeStreamInterpolate (cb) {
for (var i = 0; i < max; i++) {
plogNodeStream.info('hello %s', 'world')
}
setImmediate(cb)
},
function benchBunyanInterpolateAll (cb) {
for (var i = 0; i < max; i++) {
blog.info('hello %s %j %d', 'world', { obj: true }, 4)
}
setImmediate(cb)
},
function benchWinstonInterpolateAll (cb) {
for (var i = 0; i < max; i++) {
chill.log('info', 'hello %s %j %d', 'world', { obj: true }, 4)
}
setImmediate(cb)
},
function benchBoleInterpolateAll (cb) {
for (var i = 0; i < max; i++) {
bole.info('hello %s %j %d', 'world', { obj: true }, 4)
}
setImmediate(cb)
},
function benchPinoInterpolateAll (cb) {
for (var i = 0; i < max; i++) {
plogDest.info('hello %s %j %d', 'world', { obj: true }, 4)
}
setImmediate(cb)
},
function benchPinoMinLengthInterpolateAll (cb) {
for (var i = 0; i < max; i++) {
plogMinLength.info('hello %s %j %d', 'world', { obj: true }, 4)
}
setImmediate(cb)
},
function benchPinoNodeStreamInterpolateAll (cb) {
for (var i = 0; i < max; i++) {
plogNodeStream.info('hello %s %j %d', 'world', { obj: true }, 4)
}
setImmediate(cb)
},
function benchBunyanInterpolateExtra (cb) {
for (var i = 0; i < max; i++) {
blog.info('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' })
}
setImmediate(cb)
},
function benchWinstonInterpolateExtra (cb) {
for (var i = 0; i < max; i++) {
chill.log('info', 'hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' })
}
setImmediate(cb)
},
function benchBoleInterpolateExtra (cb) {
for (var i = 0; i < max; i++) {
bole.info('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' })
}
setImmediate(cb)
},
function benchPinoInterpolateExtra (cb) {
for (var i = 0; i < max; i++) {
plogDest.info('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' })
}
setImmediate(cb)
},
function benchPinoMinLengthInterpolateExtra (cb) {
for (var i = 0; i < max; i++) {
plogMinLength.info('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' })
}
setImmediate(cb)
},
function benchPinoNodeStreamInterpolateExtra (cb) {
for (var i = 0; i < max; i++) {
plogNodeStream.info('hello %s %j %d', 'world', { obj: true }, 4, { another: 'obj' })
}
setImmediate(cb)
},
function benchBunyanInterpolateDeep (cb) {
for (var i = 0; i < max; i++) {
blog.info('hello %j', deep)
}
setImmediate(cb)
},
function benchWinstonInterpolateDeep (cb) {
for (var i = 0; i < max; i++) {
chill.log('info', 'hello %j', deep)
}
setImmediate(cb)
},
function benchBoleInterpolateDeep (cb) {
for (var i = 0; i < max; i++) {
bole.info('hello %j', deep)
}
setImmediate(cb)
},
function benchPinoInterpolateDeep (cb) {
for (var i = 0; i < max; i++) {
plogDest.info('hello %j', deep)
}
setImmediate(cb)
},
function benchPinoMinLengthInterpolateDeep (cb) {
for (var i = 0; i < max; i++) {
plogMinLength.info('hello %j', deep)
}
setImmediate(cb)
},
function benchPinoNodeStreamInterpolateDeep (cb) {
for (var i = 0; i < max; i++) {
plogNodeStream.info('hello %j', deep)
}
setImmediate(cb)
}
], 10000)
run(run)

View File

@@ -0,0 +1,30 @@
"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScopeManager = exports.Visitor = exports.Reference = exports.PatternVisitor = exports.analyze = void 0;
var analyze_1 = require("./analyze");
Object.defineProperty(exports, "analyze", { enumerable: true, get: function () { return analyze_1.analyze; } });
__exportStar(require("./definition"), exports);
var PatternVisitor_1 = require("./referencer/PatternVisitor");
Object.defineProperty(exports, "PatternVisitor", { enumerable: true, get: function () { return PatternVisitor_1.PatternVisitor; } });
var Reference_1 = require("./referencer/Reference");
Object.defineProperty(exports, "Reference", { enumerable: true, get: function () { return Reference_1.Reference; } });
var Visitor_1 = require("./referencer/Visitor");
Object.defineProperty(exports, "Visitor", { enumerable: true, get: function () { return Visitor_1.Visitor; } });
__exportStar(require("./scope"), exports);
var ScopeManager_1 = require("./ScopeManager");
Object.defineProperty(exports, "ScopeManager", { enumerable: true, get: function () { return ScopeManager_1.ScopeManager; } });
__exportStar(require("./variable"), exports);

View File

@@ -0,0 +1,202 @@
/**
* @fileoverview Rule to validate spacing before function paren.
* @author Mathias Schreck <https://github.com/lo1tuma>
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
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: "space-before-function-paren",
url: "https://eslint.style/rules/space-before-function-paren",
},
},
],
},
type: "layout",
docs: {
description:
"Enforce consistent spacing before `function` definition opening parenthesis",
recommended: false,
url: "https://eslint.org/docs/latest/rules/space-before-function-paren",
},
fixable: "whitespace",
schema: [
{
oneOf: [
{
enum: ["always", "never"],
},
{
type: "object",
properties: {
anonymous: {
enum: ["always", "never", "ignore"],
},
named: {
enum: ["always", "never", "ignore"],
},
asyncArrow: {
enum: ["always", "never", "ignore"],
},
},
additionalProperties: false,
},
],
},
],
messages: {
unexpectedSpace: "Unexpected space before function parentheses.",
missingSpace: "Missing space before function parentheses.",
},
},
create(context) {
const sourceCode = context.sourceCode;
const baseConfig =
typeof context.options[0] === "string"
? context.options[0]
: "always";
const overrideConfig =
typeof context.options[0] === "object" ? context.options[0] : {};
/**
* Determines whether a function has a name.
* @param {ASTNode} node The function node.
* @returns {boolean} Whether the function has a name.
*/
function isNamedFunction(node) {
if (node.id) {
return true;
}
const parent = node.parent;
return (
parent.type === "MethodDefinition" ||
(parent.type === "Property" &&
(parent.kind === "get" ||
parent.kind === "set" ||
parent.method))
);
}
/**
* Gets the config for a given function
* @param {ASTNode} node The function node
* @returns {string} "always", "never", or "ignore"
*/
function getConfigForFunction(node) {
if (node.type === "ArrowFunctionExpression") {
// Always ignore non-async functions and arrow functions without parens, e.g. async foo => bar
if (
node.async &&
astUtils.isOpeningParenToken(
sourceCode.getFirstToken(node, { skip: 1 }),
)
) {
return overrideConfig.asyncArrow || baseConfig;
}
} else if (isNamedFunction(node)) {
return overrideConfig.named || baseConfig;
// `generator-star-spacing` should warn anonymous generators. E.g. `function* () {}`
} else if (!node.generator) {
return overrideConfig.anonymous || baseConfig;
}
return "ignore";
}
/**
* Checks the parens of a function node
* @param {ASTNode} node A function node
* @returns {void}
*/
function checkFunction(node) {
const functionConfig = getConfigForFunction(node);
if (functionConfig === "ignore") {
return;
}
const rightToken = sourceCode.getFirstToken(
node,
astUtils.isOpeningParenToken,
);
const leftToken = sourceCode.getTokenBefore(rightToken);
const hasSpacing = sourceCode.isSpaceBetween(leftToken, rightToken);
if (hasSpacing && functionConfig === "never") {
context.report({
node,
loc: {
start: leftToken.loc.end,
end: rightToken.loc.start,
},
messageId: "unexpectedSpace",
fix(fixer) {
const comments =
sourceCode.getCommentsBefore(rightToken);
// Don't fix anything if there's a single line comment between the left and the right token
if (comments.some(comment => comment.type === "Line")) {
return null;
}
return fixer.replaceTextRange(
[leftToken.range[1], rightToken.range[0]],
comments.reduce(
(text, comment) =>
text + sourceCode.getText(comment),
"",
),
);
},
});
} else if (!hasSpacing && functionConfig === "always") {
context.report({
node,
loc: rightToken.loc,
messageId: "missingSpace",
fix: fixer => fixer.insertTextAfter(leftToken, " "),
});
}
}
return {
ArrowFunctionExpression: checkFunction,
FunctionDeclaration: checkFunction,
FunctionExpression: checkFunction,
};
},
};

View File

@@ -0,0 +1,81 @@
/*! *****************************************************************************
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 PromiseConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Promise<any>;
/**
* Creates a new Promise.
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used to resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T extends readonly unknown[] | []>(values: T): Promise<{ -readonly [P in keyof T]: Awaited<T[P]>; }>;
// see: lib.es2015.iterable.d.ts
// all<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
* or rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
race<T extends readonly unknown[] | []>(values: T): Promise<Awaited<T[number]>>;
// see: lib.es2015.iterable.d.ts
// race<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject<T = never>(reason?: any): Promise<T>;
/**
* Creates a new resolved promise.
* @returns A resolved promise.
*/
resolve(): Promise<void>;
/**
* Creates a new resolved promise for the provided value.
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T): Promise<Awaited<T>>;
/**
* Creates a new resolved promise for the provided value.
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T | PromiseLike<T>): Promise<Awaited<T>>;
}
declare var Promise: PromiseConstructor;

View File

@@ -0,0 +1,55 @@
# Blue Oak Model License
Version 1.0.0
## Purpose
This license gives everyone as much permission to work with
this software as possible, while protecting contributors
from liability.
## Acceptance
In order to receive this license, you must agree to its
rules. The rules of this license are both obligations
under that agreement and conditions to your license.
You must not do anything with this software that triggers
a rule that you cannot or will not follow.
## Copyright
Each contributor licenses you to do everything with this
software that would otherwise infringe that contributor's
copyright in it.
## Notices
You must ensure that everyone who gets a copy of
any part of this software from you, with or without
changes, also gets the text of this license or a link to
<https://blueoakcouncil.org/license/1.0.0>.
## Excuse
If anyone notifies you in writing that you have not
complied with [Notices](#notices), you can keep your
license by taking all practical steps to comply within 30
days after the notice. If you do not do so, your license
ends immediately.
## Patent
Each contributor licenses you to do everything with this
software that would otherwise infringe any patent claims
they can license or become able to license.
## Reliability
No contributor can revoke this license.
## No Liability
**_As far as the law allows, this software comes as is,
without any warranty or condition, and no contributor
will be liable to anyone for any damages related to this
software or this license, under any kind of legal claim._**

View File

@@ -0,0 +1,21 @@
import type { TSESTree } from '@typescript-eslint/types';
import type { VisitorKeys } from '@typescript-eslint/visitor-keys';
export interface VisitorOptions {
childVisitorKeys?: VisitorKeys | null;
visitChildrenEvenIfSelectorExists?: boolean;
}
export declare abstract class VisitorBase {
#private;
constructor(options: VisitorOptions);
/**
* Default method for visiting children.
* @param node the node whose children should be visited
* @param excludeArr a list of keys to not visit
*/
visitChildren<T extends TSESTree.Node>(node: T | null | undefined, excludeArr?: (keyof T)[]): void;
/**
* Dispatching node.
*/
visit(node: TSESTree.Node | null | undefined): void;
}
export type { VisitorKeys } from '@typescript-eslint/visitor-keys';

View File

@@ -0,0 +1,22 @@
'use strict';
var test = require('tape');
var stringify = require('../');
test('toJSON function', function (t) {
t.plan(1);
var obj = { one: 1, two: 2, toJSON: function() { return { one: 1 }; } };
t.equal(stringify(obj), '{"one":1}' );
});
test('toJSON returns string', function (t) {
t.plan(1);
var obj = { one: 1, two: 2, toJSON: function() { return 'one'; } };
t.equal(stringify(obj), '"one"');
});
test('toJSON returns array', function (t) {
t.plan(1);
var obj = { one: 1, two: 2, toJSON: function() { return ['one']; } };
t.equal(stringify(obj), '["one"]');
});

View File

@@ -0,0 +1,18 @@
/**
* @fileoverview exports for config helpers
* @author Nicholas C. Zakas
*/
"use strict";
const {
defineConfig,
globalIgnores,
includeIgnoreFile,
} = require("@eslint/config-helpers");
module.exports = {
defineConfig,
globalIgnores,
includeIgnoreFile,
};

View File

@@ -0,0 +1,175 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
const literalStringSchema = z.literal("asdf");
const literalNumberSchema = z.literal(12);
const literalBooleanSchema = z.literal(true);
const literalBigIntSchema = z.literal(BigInt(42));
const stringSchema = z.string();
const numberSchema = z.number();
const bigintSchema = z.bigint();
const booleanSchema = z.boolean();
const dateSchema = z.date();
const symbolSchema = z.symbol();
const nullSchema = z.null();
const undefinedSchema = z.undefined();
const stringSchemaOptional = z.string().optional();
const stringSchemaNullable = z.string().nullable();
const numberSchemaOptional = z.number().optional();
const numberSchemaNullable = z.number().nullable();
const bigintSchemaOptional = z.bigint().optional();
const bigintSchemaNullable = z.bigint().nullable();
const booleanSchemaOptional = z.boolean().optional();
const booleanSchemaNullable = z.boolean().nullable();
const dateSchemaOptional = z.date().optional();
const dateSchemaNullable = z.date().nullable();
const symbolSchemaOptional = z.symbol().optional();
const symbolSchemaNullable = z.symbol().nullable();
test("literal string schema", () => {
expect(literalStringSchema.parse("asdf")).toBe("asdf");
expect(() => literalStringSchema.parse("not_asdf")).toThrow();
expect(() => literalStringSchema.parse(123)).toThrow();
expect(() => literalStringSchema.parse(true)).toThrow();
expect(() => literalStringSchema.parse({})).toThrow();
});
test("literal number schema", () => {
expect(literalNumberSchema.parse(12)).toBe(12);
expect(() => literalNumberSchema.parse(13)).toThrow();
expect(() => literalNumberSchema.parse("foo")).toThrow();
expect(() => literalNumberSchema.parse(true)).toThrow();
expect(() => literalNumberSchema.parse({})).toThrow();
});
test("literal boolean schema", () => {
expect(literalBooleanSchema.parse(true)).toBe(true);
expect(() => literalBooleanSchema.parse(false)).toThrow();
expect(() => literalBooleanSchema.parse("asdf")).toThrow();
expect(() => literalBooleanSchema.parse(123)).toThrow();
expect(() => literalBooleanSchema.parse({})).toThrow();
});
test("literal bigint schema", () => {
expect(literalBigIntSchema.parse(BigInt(42))).toBe(BigInt(42));
expect(() => literalBigIntSchema.parse(BigInt(43))).toThrow();
expect(() => literalBigIntSchema.parse("asdf")).toThrow();
expect(() => literalBigIntSchema.parse(123)).toThrow();
expect(() => literalBigIntSchema.parse({})).toThrow();
});
test("string schema", () => {
stringSchema.parse("foo");
expect(() => stringSchema.parse(Math.random())).toThrow();
expect(() => stringSchema.parse(true)).toThrow();
expect(() => stringSchema.parse(undefined)).toThrow();
expect(() => stringSchema.parse(null)).toThrow();
});
test("number schema", () => {
numberSchema.parse(Math.random());
expect(() => numberSchema.parse("foo")).toThrow();
expect(() => numberSchema.parse(BigInt(17))).toThrow();
expect(() => numberSchema.parse(true)).toThrow();
expect(() => numberSchema.parse(undefined)).toThrow();
expect(() => numberSchema.parse(null)).toThrow();
});
test("bigint schema", () => {
bigintSchema.parse(BigInt(17));
expect(() => bigintSchema.parse("foo")).toThrow();
expect(() => bigintSchema.parse(Math.random())).toThrow();
expect(() => bigintSchema.parse(true)).toThrow();
expect(() => bigintSchema.parse(undefined)).toThrow();
expect(() => bigintSchema.parse(null)).toThrow();
});
test("boolean schema", () => {
booleanSchema.parse(true);
expect(() => booleanSchema.parse("foo")).toThrow();
expect(() => booleanSchema.parse(Math.random())).toThrow();
expect(() => booleanSchema.parse(undefined)).toThrow();
expect(() => booleanSchema.parse(null)).toThrow();
});
test("date schema", async () => {
dateSchema.parse(new Date());
expect(() => dateSchema.parse("foo")).toThrow();
expect(() => dateSchema.parse(Math.random())).toThrow();
expect(() => dateSchema.parse(true)).toThrow();
expect(() => dateSchema.parse(undefined)).toThrow();
expect(() => dateSchema.parse(null)).toThrow();
expect(await dateSchema.safeParseAsync(new Date("invalid"))).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"expected": "date",
"code": "invalid_type",
"received": "Invalid Date",
"path": [],
"message": "Invalid input: expected date, received Date"
}
]],
"success": false,
}
`);
});
test("symbol schema", () => {
symbolSchema.parse(Symbol("foo"));
expect(() => symbolSchema.parse("foo")).toThrow();
expect(() => symbolSchema.parse(Math.random())).toThrow();
expect(() => symbolSchema.parse(true)).toThrow();
expect(() => symbolSchema.parse(new Date())).toThrow();
expect(() => symbolSchema.parse(undefined)).toThrow();
expect(() => symbolSchema.parse(null)).toThrow();
});
test("undefined schema", () => {
undefinedSchema.parse(undefined);
expect(() => undefinedSchema.parse("foo")).toThrow();
expect(() => undefinedSchema.parse(Math.random())).toThrow();
expect(() => undefinedSchema.parse(true)).toThrow();
expect(() => undefinedSchema.parse(null)).toThrow();
});
test("null schema", () => {
nullSchema.parse(null);
expect(() => nullSchema.parse("foo")).toThrow();
expect(() => nullSchema.parse(Math.random())).toThrow();
expect(() => nullSchema.parse(true)).toThrow();
expect(() => nullSchema.parse(undefined)).toThrow();
});
test("primitive inference", () => {
expectTypeOf<z.TypeOf<typeof literalStringSchema>>().toEqualTypeOf<"asdf">();
expectTypeOf<z.TypeOf<typeof literalNumberSchema>>().toEqualTypeOf<12>();
expectTypeOf<z.TypeOf<typeof literalBooleanSchema>>().toEqualTypeOf<true>();
expectTypeOf<z.TypeOf<typeof literalBigIntSchema>>().toEqualTypeOf<bigint>();
expectTypeOf<z.TypeOf<typeof stringSchema>>().toEqualTypeOf<string>();
expectTypeOf<z.TypeOf<typeof numberSchema>>().toEqualTypeOf<number>();
expectTypeOf<z.TypeOf<typeof bigintSchema>>().toEqualTypeOf<bigint>();
expectTypeOf<z.TypeOf<typeof booleanSchema>>().toEqualTypeOf<boolean>();
expectTypeOf<z.TypeOf<typeof dateSchema>>().toEqualTypeOf<Date>();
expectTypeOf<z.TypeOf<typeof symbolSchema>>().toEqualTypeOf<symbol>();
expectTypeOf<z.TypeOf<typeof nullSchema>>().toEqualTypeOf<null>();
expectTypeOf<z.TypeOf<typeof undefinedSchema>>().toEqualTypeOf<undefined>();
expectTypeOf<z.TypeOf<typeof stringSchemaOptional>>().toEqualTypeOf<string | undefined>();
expectTypeOf<z.TypeOf<typeof stringSchemaNullable>>().toEqualTypeOf<string | null>();
expectTypeOf<z.TypeOf<typeof numberSchemaOptional>>().toEqualTypeOf<number | undefined>();
expectTypeOf<z.TypeOf<typeof numberSchemaNullable>>().toEqualTypeOf<number | null>();
expectTypeOf<z.TypeOf<typeof bigintSchemaOptional>>().toEqualTypeOf<bigint | undefined>();
expectTypeOf<z.TypeOf<typeof bigintSchemaNullable>>().toEqualTypeOf<bigint | null>();
expectTypeOf<z.TypeOf<typeof booleanSchemaOptional>>().toEqualTypeOf<boolean | undefined>();
expectTypeOf<z.TypeOf<typeof booleanSchemaNullable>>().toEqualTypeOf<boolean | null>();
expectTypeOf<z.TypeOf<typeof dateSchemaOptional>>().toEqualTypeOf<Date | undefined>();
expectTypeOf<z.TypeOf<typeof dateSchemaNullable>>().toEqualTypeOf<Date | null>();
expectTypeOf<z.TypeOf<typeof symbolSchemaOptional>>().toEqualTypeOf<symbol | undefined>();
expectTypeOf<z.TypeOf<typeof symbolSchemaNullable>>().toEqualTypeOf<symbol | null>();
});
test("get literal values", () => {
expect(literalStringSchema.values).toEqual(new Set(["asdf"]));
expect(literalStringSchema._zod.def.values).toEqual(["asdf"]);
});

View File

@@ -0,0 +1,5 @@
import * as z from "./external.js";
export { z };
export * from "./external.js";
export default z;

View File

@@ -0,0 +1,67 @@
var asyncHooks = require('async_hooks')
var stackback = require('stackback')
var path = require('path')
var fs = require('fs')
var sep = path.sep
var active = new Map()
var hook = asyncHooks.createHook({
init (asyncId, type, triggerAsyncId, resource) {
if (type === 'TIMERWRAP' || type === 'PROMISE') return
if (type === 'PerformanceObserver' || type === 'RANDOMBYTESREQUEST') return
var err = new Error('whatevs')
var stacks = stackback(err)
active.set(asyncId, {type, stacks, resource})
},
destroy (asyncId) {
active.delete(asyncId)
}
})
hook.enable()
module.exports = whyIsNodeRunning
function whyIsNodeRunning (logger) {
if (!logger) logger = console
hook.disable()
var activeResources = [...active.values()].filter(function(r) {
if (
typeof r.resource.hasRef === 'function'
&& !r.resource.hasRef()
) return false
return true
})
logger.error('There are %d handle(s) keeping the process running', activeResources.length)
for (const o of activeResources) printStacks(o)
function printStacks (o) {
var stacks = o.stacks.slice(1).filter(function (s) {
var filename = s.getFileName()
return filename && filename.indexOf(sep) > -1 && filename.indexOf('internal' + sep) !== 0 && filename.indexOf('node:internal' + sep) !== 0
})
logger.error('')
logger.error('# %s', o.type)
if (!stacks[0]) {
logger.error('(unknown stack trace)')
} else {
var padding = ''
stacks.forEach(function (s) {
var pad = (s.getFileName() + ':' + s.getLineNumber()).replace(/./g, ' ')
if (pad.length > padding.length) padding = pad
})
stacks.forEach(function (s) {
var prefix = s.getFileName() + ':' + s.getLineNumber()
try {
var src = fs.readFileSync(s.getFileName(), 'utf-8').split(/\n|\r\n/)
logger.error(prefix + padding.slice(prefix.length) + ' - ' + src[s.getLineNumber() - 1].trim())
} catch (e) {
logger.error(prefix + padding.slice(prefix.length))
}
})
}
}
}

View File

@@ -0,0 +1,178 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClassVisitor = void 0;
const types_1 = require("@typescript-eslint/types");
const definition_1 = require("../definition");
const TypeVisitor_1 = require("./TypeVisitor");
const Visitor_1 = require("./Visitor");
class ClassVisitor extends Visitor_1.Visitor {
#referencer;
constructor(referencer) {
super(referencer);
this.#referencer = referencer;
}
static visit(referencer, node) {
const classVisitor = new ClassVisitor(referencer);
classVisitor.visitClass(node);
}
visit(node) {
// make sure we only handle the nodes we are designed to handle
if (node && node.type in this) {
super.visit(node);
}
else {
this.#referencer.visit(node);
}
}
///////////////////
// Visit helpers //
///////////////////
visitClass(node) {
if (node.type === types_1.AST_NODE_TYPES.ClassDeclaration && node.id) {
this.#referencer
.currentScope()
.defineIdentifier(node.id, new definition_1.ClassNameDefinition(node.id, node));
}
node.decorators.forEach(d => this.#referencer.visit(d));
this.#referencer.scopeManager.nestClassScope(node);
if (node.id) {
// define the class name again inside the new scope
// references to the class should not resolve directly to the parent class
this.#referencer
.currentScope()
.defineIdentifier(node.id, new definition_1.ClassNameDefinition(node.id, node));
}
this.#referencer.visit(node.superClass);
// visit the type param declarations
this.visitType(node.typeParameters);
// then the usages
this.visitType(node.superTypeArguments);
node.implements.forEach(imp => this.visitType(imp));
this.visit(node.body);
this.#referencer.close(node);
}
visitFunctionParameterTypeAnnotation(node) {
switch (node.type) {
case types_1.AST_NODE_TYPES.AssignmentPattern:
this.visitType(node.left.typeAnnotation);
break;
case types_1.AST_NODE_TYPES.TSParameterProperty:
this.visitFunctionParameterTypeAnnotation(node.parameter);
break;
default:
this.visitType(node.typeAnnotation);
}
}
visitMethod(node) {
if (node.computed) {
this.#referencer.visit(node.key);
}
if (node.value.type === types_1.AST_NODE_TYPES.FunctionExpression) {
this.visitMethodFunction(node.value);
}
else {
this.#referencer.visit(node.value);
}
node.decorators.forEach(d => this.#referencer.visit(d));
}
visitMethodFunction(node) {
if (node.id) {
// FunctionExpression with name creates its special scope;
// FunctionExpressionNameScope.
this.#referencer.scopeManager.nestFunctionExpressionNameScope(node);
}
node.params.forEach(param => {
param.decorators.forEach(d => this.visit(d));
});
// Consider this function is in the MethodDefinition.
this.#referencer.scopeManager.nestFunctionScope(node, true);
// Process parameter declarations.
for (const param of node.params) {
this.visitPattern(param, (pattern, info) => {
this.#referencer
.currentScope()
.defineIdentifier(pattern, new definition_1.ParameterDefinition(pattern, node, info.rest));
this.#referencer.referencingDefaultValue(pattern, info.assignments, null, true);
}, { processRightHandNodes: true });
this.visitFunctionParameterTypeAnnotation(param);
}
this.visitType(node.returnType);
this.visitType(node.typeParameters);
this.#referencer.visitChildren(node.body);
this.#referencer.close(node);
}
visitPropertyBase(node) {
if (node.computed) {
this.#referencer.visit(node.key);
}
if (node.value) {
if (node.type === types_1.AST_NODE_TYPES.PropertyDefinition ||
node.type === types_1.AST_NODE_TYPES.AccessorProperty) {
this.#referencer.scopeManager.nestClassFieldInitializerScope(node.value);
}
this.#referencer.visit(node.value);
if (node.type === types_1.AST_NODE_TYPES.PropertyDefinition ||
node.type === types_1.AST_NODE_TYPES.AccessorProperty) {
this.#referencer.close(node.value);
}
}
node.decorators.forEach(d => this.#referencer.visit(d));
}
visitPropertyDefinition(node) {
this.visitPropertyBase(node);
/**
* class A {
* @meta // <--- check this
* foo: Type;
* }
*/
this.visitType(node.typeAnnotation);
}
visitType(node) {
if (!node) {
return;
}
TypeVisitor_1.TypeVisitor.visit(this.#referencer, node);
}
/////////////////////
// Visit selectors //
/////////////////////
AccessorProperty(node) {
this.visitPropertyDefinition(node);
}
ClassBody(node) {
// this is here on purpose so that this visitor explicitly declares visitors
// for all nodes it cares about (see the instance visit method above)
this.visitChildren(node);
}
Identifier(node) {
this.#referencer.visit(node);
}
MethodDefinition(node) {
this.visitMethod(node);
}
PrivateIdentifier() {
// intentionally skip
}
PropertyDefinition(node) {
this.visitPropertyDefinition(node);
}
StaticBlock(node) {
this.#referencer.scopeManager.nestClassStaticBlockScope(node);
node.body.forEach(b => this.visit(b));
this.#referencer.close(node);
}
TSAbstractAccessorProperty(node) {
this.visitPropertyDefinition(node);
}
TSAbstractMethodDefinition(node) {
this.visitPropertyBase(node);
}
TSAbstractPropertyDefinition(node) {
this.visitPropertyDefinition(node);
}
TSIndexSignature(node) {
this.visitType(node);
}
}
exports.ClassVisitor = ClassVisitor;

View File

@@ -0,0 +1,92 @@
export { M as ModuleMocker, c as createCompilerHints } from './chunk-mocker.js';
import { M as MockerRegistry } from './chunk-registry.js';
import { c as createManualModuleSource, a as cleanUrl } from './chunk-utils.js';
export { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js';
import './chunk-helpers.js';
import './index.js';
import './chunk-pathe.M-eThtNZ.js';
class ModuleMockerMSWInterceptor {
mocks = new MockerRegistry();
startPromise;
worker;
constructor(options = {}) {
this.options = options;
if (!options.globalThisAccessor) {
options.globalThisAccessor = "\"__vitest_mocker__\"";
}
}
async register(module) {
await this.init();
this.mocks.add(module);
}
async delete(url) {
await this.init();
this.mocks.delete(url);
}
async invalidate() {
this.mocks.clear();
}
async resolveManualMock(mock) {
const exports$1 = Object.keys(await mock.resolve());
const text = createManualModuleSource(mock.url, exports$1, this.options.globalThisAccessor);
return new Response(text, { headers: { "Content-Type": "application/javascript" } });
}
async init() {
if (this.worker) {
return this.worker;
}
if (this.startPromise) {
return this.startPromise;
}
const worker = this.options.mswWorker;
this.startPromise = Promise.all([worker ? { setupWorker(handler) {
worker.use(handler);
return worker;
} } : import('msw/browser'), import('msw/core/http')]).then(([{ setupWorker }, { http }]) => {
const worker = setupWorker(http.get(/.+/, async ({ request }) => {
const path = cleanQuery(request.url.slice(location.origin.length));
if (!this.mocks.has(path)) {
return passthrough();
}
const mock = this.mocks.get(path);
switch (mock.type) {
case "manual": return this.resolveManualMock(mock);
case "automock":
case "autospy": return Response.redirect(injectQuery(path, `mock=${mock.type}`));
case "redirect": return Response.redirect(mock.redirect);
default: throw new Error(`Unknown mock type: ${mock.type}`);
}
}));
return worker.start(this.options.mswOptions).then(() => worker);
}).finally(() => {
this.worker = worker;
this.startPromise = undefined;
});
return await this.startPromise;
}
}
const trailingSeparatorRE = /[?&]$/;
const timestampRE = /\bt=\d{13}&?\b/;
const versionRE = /\bv=\w{8}&?\b/;
function cleanQuery(url) {
return url.replace(timestampRE, "").replace(versionRE, "").replace(trailingSeparatorRE, "");
}
function passthrough() {
return new Response(null, {
status: 302,
statusText: "Passthrough",
headers: { "x-msw-intention": "passthrough" }
});
}
const replacePercentageRE = /%/g;
function injectQuery(url, queryToInject) {
// encode percents for consistent behavior with pathToFileURL
// see #2614 for details
const resolvedUrl = new URL(url.replace(replacePercentageRE, "%25"), location.href);
const { search, hash } = resolvedUrl;
const pathname = cleanUrl(url);
return `${pathname}?${queryToInject}${search ? `&${search.slice(1)}` : ""}${hash ?? ""}`;
}
export { ModuleMockerMSWInterceptor };

View File

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

View File

@@ -0,0 +1,12 @@
import { _ as _set_prototype_of } from "./_set_prototype_of.js";
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
if (superClass) _set_prototype_of(subClass, superClass);
}
export { _inherits as _ };