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,205 @@
/**
* @fileoverview Comma spacing - validates spacing before and after comma
* @author Vignesh Anand aka vegetableman.
* @deprecated in ESLint v8.53.0
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "comma-spacing",
url: "https://eslint.style/rules/comma-spacing",
},
},
],
},
type: "layout",
docs: {
description: "Enforce consistent spacing before and after commas",
recommended: false,
url: "https://eslint.org/docs/latest/rules/comma-spacing",
},
fixable: "whitespace",
schema: [
{
type: "object",
properties: {
before: {
type: "boolean",
default: false,
},
after: {
type: "boolean",
default: true,
},
},
additionalProperties: false,
},
],
messages: {
missing: "A space is required {{loc}} ','.",
unexpected: "There should be no space {{loc}} ','.",
},
},
create(context) {
const sourceCode = context.sourceCode;
const tokensAndComments = sourceCode.tokensAndComments;
const options = {
before: context.options[0] ? context.options[0].before : false,
after: context.options[0] ? context.options[0].after : true,
};
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
// list of comma tokens to ignore for the check of leading whitespace
const commaTokensToIgnore = [];
/**
* Reports a spacing error with an appropriate message.
* @param {ASTNode} node The binary expression node to report.
* @param {string} loc Is the error "before" or "after" the comma?
* @param {ASTNode} otherNode The node at the left or right of `node`
* @returns {void}
* @private
*/
function report(node, loc, otherNode) {
context.report({
node,
fix(fixer) {
if (options[loc]) {
if (loc === "before") {
return fixer.insertTextBefore(node, " ");
}
return fixer.insertTextAfter(node, " ");
}
let start, end;
const newText = "";
if (loc === "before") {
start = otherNode.range[1];
end = node.range[0];
} else {
start = node.range[1];
end = otherNode.range[0];
}
return fixer.replaceTextRange([start, end], newText);
},
messageId: options[loc] ? "missing" : "unexpected",
data: {
loc,
},
});
}
/**
* Adds null elements of the given ArrayExpression or ArrayPattern node to the ignore list.
* @param {ASTNode} node An ArrayExpression or ArrayPattern node.
* @returns {void}
*/
function addNullElementsToIgnoreList(node) {
let previousToken = sourceCode.getFirstToken(node);
node.elements.forEach(element => {
let token;
if (element === null) {
token = sourceCode.getTokenAfter(previousToken);
if (astUtils.isCommaToken(token)) {
commaTokensToIgnore.push(token);
}
} else {
token = sourceCode.getTokenAfter(element);
}
previousToken = token;
});
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
"Program:exit"() {
tokensAndComments.forEach((token, i) => {
if (!astUtils.isCommaToken(token)) {
return;
}
const previousToken = tokensAndComments[i - 1];
const nextToken = tokensAndComments[i + 1];
if (
previousToken &&
!astUtils.isCommaToken(previousToken) && // ignore spacing between two commas
/*
* `commaTokensToIgnore` are ending commas of `null` elements (array holes/elisions).
* In addition to spacing between two commas, this can also ignore:
*
* - Spacing after `[` (controlled by array-bracket-spacing)
* Example: [ , ]
* ^
* - Spacing after a comment (for backwards compatibility, this was possibly unintentional)
* Example: [a, /* * / ,]
* ^
*/
!commaTokensToIgnore.includes(token) &&
astUtils.isTokenOnSameLine(previousToken, token) &&
options.before !==
sourceCode.isSpaceBetween(previousToken, token)
) {
report(token, "before", previousToken);
}
if (
nextToken &&
!astUtils.isCommaToken(nextToken) && // ignore spacing between two commas
!astUtils.isClosingParenToken(nextToken) && // controlled by space-in-parens
!astUtils.isClosingBracketToken(nextToken) && // controlled by array-bracket-spacing
!astUtils.isClosingBraceToken(nextToken) && // controlled by object-curly-spacing
!(!options.after && nextToken.type === "Line") && // special case, allow space before line comment
astUtils.isTokenOnSameLine(token, nextToken) &&
options.after !==
sourceCode.isSpaceBetween(token, nextToken)
) {
report(token, "after", nextToken);
}
});
},
ArrayExpression: addNullElementsToIgnoreList,
ArrayPattern: addNullElementsToIgnoreList,
};
},
};

View File

@@ -0,0 +1,486 @@
declare module "node:ffi" {
import { NonSharedBuffer } from "node:buffer";
interface FunctionSignature {
return?: ReturnType | undefined;
arguments?: readonly ArgumentType[] | undefined;
}
interface FunctionDefinitions {
[symbol: string]: FunctionSignature;
}
type CallbackFunction<R extends ReturnType = any, P extends readonly ArgumentType[] = any[]> = (
...args: { [K in keyof P]: ArgumentTypeMap[DataTypeMap[P[K]]] }
) => ReturnTypeMap[DataTypeMap[R]];
interface WrappedFunction<R extends ReturnType = any, P extends readonly ArgumentType[] = any[]>
extends CallbackFunction<R, P>
{
readonly pointer: bigint;
}
type CallbackFunctionFromSignature<T extends FunctionSignature> = CallbackFunction<
ReturnTypeFromFunctionSignature<T>,
ArgumentTypesFromFunctionSignature<T>
>;
type WrappedFunctionFromSignature<T extends FunctionSignature> = WrappedFunction<
ReturnTypeFromFunctionSignature<T>,
ArgumentTypesFromFunctionSignature<T>
>;
type WrappedFunctionsFromDefinitions<T extends FunctionDefinitions> = {
[K in keyof T]: WrappedFunctionFromSignature<T[K]>;
};
type ReturnTypeFromFunctionSignature<T extends FunctionSignature> = "return" extends keyof T
? T extends { return: infer R extends ReturnType } ? R : any
: "void";
type ArgumentTypesFromFunctionSignature<T extends FunctionSignature> = "arguments" extends keyof T
? T extends { arguments: infer P extends readonly ArgumentType[] } ? P : any[]
: [];
interface DynamicLibraryResult<T extends FunctionDefinitions> extends Disposable {
lib: DynamicLibrary;
functions: WrappedFunctionsFromDefinitions<T>;
}
/**
* The native shared library suffix for the current platform:
*
* * `'dylib'` on macOS
* * `'so'` on Unix-like platforms
* * `'dll'` on Windows
*
* This can be used to build portable library paths:
*
* ```js
* const { suffix } = require('node:ffi');
*
* const path = `libsqlite3.${suffix}`;
* ```
* @since v26.1.0
*/
const suffix: string;
/**
* Loads a dynamic library and resolves the requested function definitions.
*
* On Windows passing `null` is not supported.
*
* When `definitions` is omitted, `functions` is returned as an empty object until
* symbols are resolved explicitly.
*
* The returned object also implements the explicit resource management protocol,
* so it can be used with the `using` declaration. Disposing the returned
* object closes the library handle.
*
* ```js
* import { dlopen } from 'node:ffi';
*
* {
* using handle = dlopen('./mylib.so', {
* add_i32: { arguments: ['i32', 'i32'], return: 'i32' },
* });
* console.log(handle.functions.add_i32(20, 22));
* } // handle.lib.close() is invoked automatically here.
* ```
*
* ```js
* import { dlopen } from 'node:ffi';
*
* const { lib, functions } = dlopen('./mylib.so', {
* add_i32: { arguments: ['i32', 'i32'], return: 'i32' },
* string_length: { arguments: ['pointer'], return: 'u64' },
* });
*
* console.log(functions.add_i32(20, 22));
* ```
* @since v26.1.0
* @param path Path to a dynamic library, or `null` to resolve symbols
* from the current process image.
* @param definitions Symbol definitions to resolve immediately.
*/
function dlopen<const T extends FunctionDefinitions = {}>(
path: string | null,
definitions?: T,
): DynamicLibraryResult<T>;
/**
* Closes a dynamic library.
*
* This is equivalent to calling `handle.close()`.
* @since v26.1.0
*/
function dlclose(handle: DynamicLibrary): void;
/**
* Resolves a symbol address from a loaded library.
*
* This is equivalent to calling `handle.getSymbol(symbol)`.
* @since v26.1.0
*/
function dlsym(handle: DynamicLibrary, symbol: string): bigint;
/**
* @since v26.1.0
*/
class DynamicLibrary {
/**
* Loads the dynamic library without resolving any functions eagerly.
*
* On Windows passing `null` is not supported.
*
* ```js
* const { DynamicLibrary } = require('node:ffi');
*
* const lib = new DynamicLibrary('./mylib.so');
* ```
* @param path Path to a dynamic library, or `null` to resolve symbols
* from the current process image.
*/
constructor(path: string | null);
/**
* The path used to load the library.
*/
readonly path: string;
/**
* An object containing previously resolved symbol addresses as `bigint` values.
*/
readonly symbols: { [symbol: string]: bigint };
/**
* Closes the library handle.
*
* `DynamicLibrary` implements the explicit resource management protocol, so a
* library instance can be managed with the `using` declaration. Leaving the
* enclosing scope invokes `library.close()` automatically.
*
* ```js
* import { DynamicLibrary } from 'node:ffi';
*
* {
* using lib = new DynamicLibrary('./mylib.so');
* // Use `lib` here; `lib.close()` is called when the block exits.
* }
* ```
*
* Calling `library.close()` (or disposing the library) more than once is a no-op.
*
* After a library has been closed:
*
* * Resolved function wrappers become invalid.
* * Further symbol and function resolution throws.
* * Registered callbacks are invalidated.
*
* Closing a library does not make previously exported callback pointers safe to
* reuse. Node.js does not track or revoke callback pointers that have already
* been handed to native code.
*
* If native code still holds a callback pointer after `library.close()` or after
* `library.unregisterCallback(pointer)`, invoking that pointer has undefined
* behavior, is not allowed, and is dangerous: it can crash the process, produce
* incorrect output, or corrupt memory. Native code must stop using callback
* addresses before the library is closed or before the callback is unregistered.
*
* Calling `library.close()` from one of the library's active callbacks is
* unsupported and dangerous. The callback must return before the library is
* closed.
*/
close(): void;
/**
* Calls `library.close()`. This allows `DynamicLibrary` instances to be used with
* the `using` declaration for automatic cleanup when the enclosing scope
* exits. It is a no-op on a library that has already been closed.
* @since v26.1.0
*/
[Symbol.dispose](): void;
/**
* Resolves a symbol and returns a callable JavaScript wrapper.
*
* The returned function has a `.pointer` property containing the native function
* address as a `bigint`.
*
* If the same symbol has already been resolved, requesting it again with a
* different signature throws.
*
* ```js
* const { DynamicLibrary } = require('node:ffi');
*
* const lib = new DynamicLibrary('./mylib.so');
* const add = lib.getFunction('add_i32', {
* arguments: ['i32', 'i32'],
* return: 'i32',
* });
*
* console.log(add(20, 22));
* console.log(add.pointer);
* ```
*/
getFunction<const T extends FunctionSignature>(name: string, signature: T): WrappedFunctionFromSignature<T>;
/**
* When `definitions` is provided, resolves each named symbol and returns an
* object containing callable wrappers.
*
* When `definitions` is omitted, returns wrappers for all functions that have
* already been resolved on the library.
*/
getFunctions(): { [symbol: string]: WrappedFunction };
getFunctions<const T extends FunctionDefinitions>(definitions: T): WrappedFunctionsFromDefinitions<T>;
/**
* Resolves a symbol and returns its native address as a `bigint`.
*/
getSymbol(name: string): bigint;
/**
* Returns an object containing all previously resolved symbol addresses.
*/
getSymbols(): Record<string, bigint>;
/**
* Creates a native callback pointer backed by a JavaScript function.
*
* When `signature` is omitted, the callback uses a default `void ()` signature.
*
* The return value is the callback pointer address as a `bigint`. It can be
* passed to native functions expecting a callback pointer.
*
* ```js
* const { DynamicLibrary } = require('node:ffi');
*
* const lib = new DynamicLibrary('./mylib.so');
*
* const callback = lib.registerCallback(
* { arguments: ['i32'], return: 'i32' },
* (value) => value * 2,
* );
* ```
*
* Callbacks are subject to the following restrictions:
*
* * They must be invoked on the same system thread where they were created.
* * They must not throw exceptions.
* * They must not return promises.
* * They must return a value compatible with the declared return type.
* * They must not call `library.close()` on their owning library while running.
* * They must not unregister themselves while running.
*
* Closing the owning library or unregistering the currently executing callback
* from inside the callback is unsupported and dangerous. Doing so may crash the
* process, produce incorrect output, or corrupt memory.
*/
registerCallback(callback: () => void): bigint;
registerCallback<const T extends FunctionSignature>(
signature: T,
callback: CallbackFunctionFromSignature<T>,
): bigint;
/**
* Releases a callback previously created with `library.registerCallback()`.
*
* Calling `library.unregisterCallback(pointer)` for a callback that is currently
* executing is unsupported and dangerous. The callback must return before it is
* unregistered.
*
* After `library.unregisterCallback(pointer)` returns, invoking that callback
* pointer from native code has undefined behavior, is not allowed, and is
* dangerous: it can crash the process, produce incorrect output, or corrupt
* memory.
*/
unregisterCallback(pointer: bigint): void;
/**
* Keeps the callback strongly referenced by JavaScript.
*/
refCallback(pointer: bigint): void;
/**
* Allows the callback to become weakly referenced by JavaScript.
*
* If the callback function is later garbage collected, subsequent native
* invocations become a no-op. Non-void return values are zero-initialized before
* returning to native code.
*/
unrefCallback(pointer: bigint): void;
}
function getInt8(pointer: bigint, offset?: number): number;
function getUint8(pointer: bigint, offset?: number): number;
function getInt16(pointer: bigint, offset?: number): number;
function getUint16(pointer: bigint, offset?: number): number;
function getInt32(pointer: bigint, offset?: number): number;
function getUint32(pointer: bigint, offset?: number): number;
function getInt64(pointer: bigint, offset?: number): bigint;
function getUint64(pointer: bigint, offset?: number): bigint;
function getFloat32(pointer: bigint, offset?: number): number;
function getFloat64(pointer: bigint, offset?: number): number;
function setInt8(pointer: bigint, offset: number, value: number): void;
function setUint8(pointer: bigint, offset: number, value: number): void;
function setInt16(pointer: bigint, offset: number, value: number): void;
function setUint16(pointer: bigint, offset: number, value: number): void;
function setInt32(pointer: bigint, offset: number, value: number): void;
function setUint32(pointer: bigint, offset: number, value: number): void;
function setInt64(pointer: bigint, offset: number, value: number | bigint): void;
function setUint64(pointer: bigint, offset: number, value: number | bigint): void;
function setFloat32(pointer: bigint, offset: number, value: number): void;
function setFloat64(pointer: bigint, offset: number, value: number): void;
/**
* Reads a NUL-terminated UTF-8 string from native memory.
*
* If `pointer` is `0n`, `null` is returned.
*
* This function does not validate that `pointer` refers to readable memory or
* that the pointed-to data is terminated with `\0`. Passing an invalid pointer,
* a pointer to freed memory, or a pointer to bytes without a terminating NUL can
* read unrelated memory, crash the process, or produce truncated or garbled
* output.
* @since v26.1.0
*/
function toString(pointer: bigint): string | null;
/**
* Creates a `Buffer` from native memory.
*
* When `copy` is `true`, the returned `Buffer` owns its own copied memory.
* When `copy` is `false`, the returned `Buffer` references the original native
* memory directly.
*
* Using `copy: false` is a zero-copy escape hatch. The returned `Buffer` is a
* writable view onto foreign memory, so writes in JavaScript update the original
* native memory directly. The caller must guarantee that:
*
* * `pointer` remains valid for the entire lifetime of the returned `Buffer`.
* * `length` stays within the allocated native region.
* * no native code frees or repurposes that memory while JavaScript still uses
* the `Buffer`.
* * Memory protection is observed. For example, read-only memory pages must not
* be written to.
*
* If these guarantees are not met, reading or writing the `Buffer` can corrupt
* memory or crash the process.
* @since v26.1.0
* @param copy When `false`, creates a zero-copy view. **Default:** `true`.
*/
function toBuffer(pointer: bigint, length: number, copy?: boolean): NonSharedBuffer;
/**
* Creates an `ArrayBuffer` from native memory.
*
* When `copy` is `true`, the returned `ArrayBuffer` contains copied bytes.
* When `copy` is `false`, the returned `ArrayBuffer` references the original
* native memory directly.
*
* The same lifetime and bounds requirements described for
* `ffi.toBuffer(pointer, length, copy)` apply
* here. With `copy: false`, the
* returned `ArrayBuffer` is a zero-copy view of foreign memory and is only safe
* while that memory remains allocated, unchanged in layout, and valid for the
* entire exposed range.
* @since v26.1.0
* @param copy When `false`, creates a zero-copy view. **Default:** `true`.
*/
function toArrayBuffer(pointer: bigint, length: number, copy?: boolean): ArrayBuffer;
/**
* Copies a JavaScript string into native memory and appends a trailing NUL
* terminator.
*
* `length` must be large enough to hold the full encoded string plus the trailing
* NUL terminator. For UTF-16 and UCS-2 encodings, the trailing terminator uses
* two zero bytes.
*
* `pointer` must refer to writable native memory with at least `length` bytes of
* available storage. This function does not allocate memory on its own.
*
* `string` must be a JavaScript string. `encoding` must be a string.
* @since v26.1.0
* @param encoding **Default:** `'utf8'`.
*/
function exportString(string: string, pointer: bigint, length: number, encoding?: BufferEncoding): void;
/**
* Copies bytes from a `Buffer` into native memory.
*
* `length` must be at least `buffer.length`.
*
* `pointer` must refer to writable native memory with at least `length` bytes of
* available storage. This function does not allocate memory on its own.
*
* `buffer` must be a Node.js `Buffer`.
* @since v26.1.0
*/
function exportBuffer(buffer: Buffer, pointer: bigint, length: number): void;
/**
* Copies bytes from an `ArrayBuffer` into native memory.
*
* `length` must be at least `arrayBuffer.byteLength`.
*
* `pointer` must refer to writable native memory with at least `length` bytes of
* available storage. This function does not allocate memory on its own.
* @since v26.1.0
*/
function exportArrayBuffer(arrayBuffer: ArrayBuffer, pointer: bigint, length: number): void;
/**
* Copies bytes from an `ArrayBufferView` into native memory.
*
* `length` must be at least `arrayBufferView.byteLength`.
*
* `pointer` must refer to writable native memory with at least `length` bytes of
* available storage. This function does not allocate memory on its own.
* @since v26.1.0
*/
function exportArrayBufferView(arrayBufferView: NodeJS.ArrayBufferView, pointer: bigint, length: number): void;
/**
* Returns the raw memory address of JavaScript-managed byte storage.
*
* This is unsafe and dangerous. The returned pointer can become invalid if the
* underlying memory is detached, resized, transferred, or otherwise invalidated.
* Using stale pointers can cause memory corruption or process crashes.
* @since v26.1.0
*/
function getRawPointer(source: ArrayBuffer | NodeJS.ArrayBufferView): bigint;
type ReturnType = { [K in keyof DataTypeMap]: K }[keyof DataTypeMap];
type ArgumentType = Exclude<ReturnType, "void">;
interface DataTypeMap {
void: "void";
char: "number";
bool: "number";
i8: "number";
int8: "number";
u8: "number";
uint8: "number";
i16: "number";
int16: "number";
u16: "number";
uint16: "number";
i32: "number";
int32: "number";
u32: "number";
uint32: "number";
i64: "bigint";
int64: "bigint";
u64: "bigint";
uint64: "bigint";
float: "number";
f32: "number";
double: "number";
f64: "number";
pointer: "pointer";
ptr: "pointer";
function: "pointer";
buffer: "pointer";
arraybuffer: "pointer";
string: "pointer";
str: "pointer";
}
interface ArgumentTypeMap {
"number": number;
"bigint": bigint;
"pointer": bigint | string | ArrayBuffer | NodeJS.ArrayBufferView | null;
}
interface ReturnTypeMap {
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
"void": void;
"number": number;
"bigint": bigint;
"pointer": bigint | null;
}
enum types {
VOID = "void",
POINTER = "pointer",
BUFFER = "buffer",
ARRAY_BUFFER = "arraybuffer",
FUNCTION = "function",
BOOL = "bool",
CHAR = "char",
STRING = "string",
FLOAT = "float",
DOUBLE = "double",
INT_8 = "int8",
UINT_8 = "uint8",
INT_16 = "int16",
UINT_16 = "uint16",
INT_32 = "int32",
UINT_32 = "uint32",
INT_64 = "int64",
UINT_64 = "uint64",
FLOAT_32 = "float32",
FLOAT_64 = "float64",
}
}

View File

@@ -0,0 +1,377 @@
import { n as __toESM, t as require_binding } from "./binding-Zhafd14U.mjs";
import { s as logMultipleWatcherOption } from "./logs-DmYCAKcW.mjs";
import { C as LOG_LEVEL_WARN } from "./bindingify-input-options-C-Zsy1EG.mjs";
import { t as arraify } from "./misc-DOSKtd97.mjs";
import { l as PluginDriver, t as createBundlerOptions } from "./create-bundler-option-wRiQzEJ3.mjs";
import { t as aggregateBindingErrorsIntoJsError } from "./error-CVc7IgvG.mjs";
//#region ../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/signals.js
/**
* This is not the set of all possible signals.
*
* It IS, however, the set of all signals that trigger
* an exit on either Linux or BSD systems. Linux is a
* superset of the signal names supported on BSD, and
* the unknown signals just fail to register, so we can
* catch that easily enough.
*
* Windows signals are a different set, since there are
* signals that terminate Windows processes, but don't
* terminate (or don't even exist) on Posix systems.
*
* Don't bother with SIGKILL. It's uncatchable, which
* means that we can't fire any callbacks anyway.
*
* If a user does happen to register a handler on a non-
* fatal signal like SIGWINCH or something, and then
* exit, it'll end up firing `process.emit('exit')`, so
* the handler will be fired anyway.
*
* SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
* artificially, inherently leave the process in a
* state from which it is not safe to try and enter JS
* listeners.
*/
const signals = [];
signals.push("SIGHUP", "SIGINT", "SIGTERM");
if (process.platform !== "win32") signals.push("SIGALRM", "SIGABRT", "SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT");
if (process.platform === "linux") signals.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT");
//#endregion
//#region ../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/index.js
const processOk = (process) => !!process && typeof process === "object" && typeof process.removeListener === "function" && typeof process.emit === "function" && typeof process.reallyExit === "function" && typeof process.listeners === "function" && typeof process.kill === "function" && typeof process.pid === "number" && typeof process.on === "function";
const kExitEmitter = Symbol.for("signal-exit emitter");
const global = globalThis;
const ObjectDefineProperty = Object.defineProperty.bind(Object);
var Emitter = class {
emitted = {
afterExit: false,
exit: false
};
listeners = {
afterExit: [],
exit: []
};
count = 0;
id = Math.random();
constructor() {
if (global[kExitEmitter]) return global[kExitEmitter];
ObjectDefineProperty(global, kExitEmitter, {
value: this,
writable: false,
enumerable: false,
configurable: false
});
}
on(ev, fn) {
this.listeners[ev].push(fn);
}
removeListener(ev, fn) {
const list = this.listeners[ev];
const i = list.indexOf(fn);
/* c8 ignore start */
if (i === -1) return;
/* c8 ignore stop */
if (i === 0 && list.length === 1) list.length = 0;
else list.splice(i, 1);
}
emit(ev, code, signal) {
if (this.emitted[ev]) return false;
this.emitted[ev] = true;
let ret = false;
for (const fn of this.listeners[ev]) ret = fn(code, signal) === true || ret;
if (ev === "exit") ret = this.emit("afterExit", code, signal) || ret;
return ret;
}
};
var SignalExitBase = class {};
const signalExitWrap = (handler) => {
return {
onExit(cb, opts) {
return handler.onExit(cb, opts);
},
load() {
return handler.load();
},
unload() {
return handler.unload();
}
};
};
var SignalExitFallback = class extends SignalExitBase {
onExit() {
return () => {};
}
load() {}
unload() {}
};
var SignalExit = class extends SignalExitBase {
/* c8 ignore start */
#hupSig = process$1.platform === "win32" ? "SIGINT" : "SIGHUP";
/* c8 ignore stop */
#emitter = new Emitter();
#process;
#originalProcessEmit;
#originalProcessReallyExit;
#sigListeners = {};
#loaded = false;
constructor(process) {
super();
this.#process = process;
this.#sigListeners = {};
for (const sig of signals) this.#sigListeners[sig] = () => {
const listeners = this.#process.listeners(sig);
let { count } = this.#emitter;
/* c8 ignore start */
const p = process;
if (typeof p.__signal_exit_emitter__ === "object" && typeof p.__signal_exit_emitter__.count === "number") count += p.__signal_exit_emitter__.count;
/* c8 ignore stop */
if (listeners.length === count) {
this.unload();
const ret = this.#emitter.emit("exit", null, sig);
/* c8 ignore start */
const s = sig === "SIGHUP" ? this.#hupSig : sig;
if (!ret) process.kill(process.pid, s);
}
};
this.#originalProcessReallyExit = process.reallyExit;
this.#originalProcessEmit = process.emit;
}
onExit(cb, opts) {
/* c8 ignore start */
if (!processOk(this.#process)) return () => {};
/* c8 ignore stop */
if (this.#loaded === false) this.load();
const ev = opts?.alwaysLast ? "afterExit" : "exit";
this.#emitter.on(ev, cb);
return () => {
this.#emitter.removeListener(ev, cb);
if (this.#emitter.listeners["exit"].length === 0 && this.#emitter.listeners["afterExit"].length === 0) this.unload();
};
}
load() {
if (this.#loaded) return;
this.#loaded = true;
this.#emitter.count += 1;
for (const sig of signals) try {
const fn = this.#sigListeners[sig];
if (fn) this.#process.on(sig, fn);
} catch (_) {}
this.#process.emit = (ev, ...a) => {
return this.#processEmit(ev, ...a);
};
this.#process.reallyExit = (code) => {
return this.#processReallyExit(code);
};
}
unload() {
if (!this.#loaded) return;
this.#loaded = false;
signals.forEach((sig) => {
const listener = this.#sigListeners[sig];
/* c8 ignore start */
if (!listener) throw new Error("Listener not defined for signal: " + sig);
/* c8 ignore stop */
try {
this.#process.removeListener(sig, listener);
} catch (_) {}
/* c8 ignore stop */
});
this.#process.emit = this.#originalProcessEmit;
this.#process.reallyExit = this.#originalProcessReallyExit;
this.#emitter.count -= 1;
}
#processReallyExit(code) {
/* c8 ignore start */
if (!processOk(this.#process)) return 0;
this.#process.exitCode = code || 0;
/* c8 ignore stop */
this.#emitter.emit("exit", this.#process.exitCode, null);
return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
}
#processEmit(ev, ...args) {
const og = this.#originalProcessEmit;
if (ev === "exit" && processOk(this.#process)) {
if (typeof args[0] === "number") this.#process.exitCode = args[0];
/* c8 ignore start */
const ret = og.call(this.#process, ev, ...args);
/* c8 ignore start */
this.#emitter.emit("exit", this.#process.exitCode, null);
/* c8 ignore stop */
return ret;
} else return og.call(this.#process, ev, ...args);
}
};
const process$1 = globalThis.process;
const { onExit: onExit$1, load, unload } = signalExitWrap(processOk(process$1) ? new SignalExit(process$1) : new SignalExitFallback());
//#endregion
//#region src/utils/signal-exit.ts
function onExit(...args) {
if (typeof process === "object" && process.versions.webcontainer) {
process.on("exit", (code) => {
args[0](code, null);
});
return;
}
onExit$1(...args);
}
//#endregion
//#region src/api/watch/watch-emitter.ts
var WatcherEmitter = class {
listeners = /* @__PURE__ */ new Map();
on(event, listener) {
const listeners = this.listeners.get(event);
if (listeners) listeners.push(listener);
else this.listeners.set(event, [listener]);
return this;
}
off(event, listener) {
const listeners = this.listeners.get(event);
if (listeners) {
const index = listeners.indexOf(listener);
if (index !== -1) listeners.splice(index, 1);
}
return this;
}
clear(event) {
this.listeners.delete(event);
}
/** Async emit — sequential dispatch so side effects from earlier handlers
* (e.g. `event.result.close()` triggering `closeBundle`) are visible to later handlers. */
async emit(event, ...args) {
const handlers = this.listeners.get(event);
if (handlers?.length) for (const h of handlers) await h(...args);
}
async close() {}
};
//#endregion
//#region src/api/watch/watcher.ts
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
function createEventCallback(emitter) {
return async (event) => {
switch (event.eventKind()) {
case "event": {
const code = event.bundleEventKind();
if (code === "BUNDLE_END") {
const { duration, output, result } = event.bundleEndData();
await emitter.emit("event", {
code: "BUNDLE_END",
duration,
output: [output],
result
});
} else if (code === "ERROR") {
const data = event.bundleErrorData();
await emitter.emit("event", {
code: "ERROR",
error: aggregateBindingErrorsIntoJsError(data.error),
result: data.result
});
} else await emitter.emit("event", { code });
break;
}
case "change": {
const { path, kind } = event.watchChangeData();
await emitter.emit("change", path, { event: kind });
break;
}
case "restart":
await emitter.emit("restart");
break;
case "close": await emitter.emit("close");
}
};
}
var Watcher = class {
closed;
inner;
emitter;
stopWorkers;
constructor(emitter, inner, stopWorkers) {
this.closed = false;
this.inner = inner;
this.emitter = emitter;
(0, import_binding.startAsyncRuntime)();
const originClose = emitter.close.bind(emitter);
emitter.close = async () => {
await this.close();
originClose();
};
this.stopWorkers = stopWorkers;
process.nextTick(() => this.run());
}
async close() {
if (this.closed) return;
this.closed = true;
try {
for (const stop of this.stopWorkers) await stop?.();
await this.inner.close();
} finally {
(0, import_binding.shutdownAsyncRuntime)();
}
}
async run() {
await this.inner.run();
this.inner.waitForClose();
}
};
async function createWatcher(emitter, input) {
const options = arraify(input);
const bundlerOptions = await Promise.all(options.map((option) => arraify(option.output || {}).map(async (output) => {
const inputOptions = await PluginDriver.callOptionsHook(option, true);
return createBundlerOptions(inputOptions, output, true);
})).flat());
warnMultiplePollingOptions(bundlerOptions);
const callback = createEventCallback(emitter);
new Watcher(emitter, new import_binding.BindingWatcher(bundlerOptions.map((option) => option.bundlerOptions), callback), bundlerOptions.map((option) => option.stopWorkers));
}
function warnMultiplePollingOptions(bundlerOptions) {
let found = false;
for (const option of bundlerOptions) {
const watch = option.inputOptions.watch;
const watcher = watch && typeof watch === "object" ? watch.watcher : void 0;
if (watcher && (watcher.usePolling != null || watcher.pollInterval != null)) {
if (found) {
option.onLog(LOG_LEVEL_WARN, logMultipleWatcherOption());
return;
}
found = true;
}
}
}
//#endregion
//#region src/api/watch/index.ts
/**
* The API compatible with Rollup's `watch` function.
*
* This function will rebuild the bundle when it detects that the individual modules have changed on disk.
*
* Note that when using this function, it is your responsibility to call `event.result.close()` in response to the `BUNDLE_END` event to avoid resource leaks.
*
* @param input The watch options object or the list of them.
* @returns A watcher object.
*
* @example
* ```js
* import { watch } from 'rolldown';
*
* const watcher = watch({ /* ... *\/ });
* watcher.on('event', (event) => {
* if (event.code === 'BUNDLE_END') {
* console.log(event.duration);
* event.result.close();
* }
* });
*
* // Stop watching
* watcher.close();
* ```
*
* @experimental
* @category Programmatic APIs
*/
function watch(input) {
const emitter = new WatcherEmitter();
createWatcher(emitter, input);
return emitter;
}
//#endregion
export { onExit as n, watch as t };

View File

@@ -0,0 +1 @@
{"version":3,"file":"sha1.d.ts","sourceRoot":"","sources":["../src/sha1.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,EAAE,MAAM,aAAa,CAAC;AAC3D,+DAA+D;AAC/D,eAAO,MAAM,IAAI,EAAE,OAAO,KAAa,CAAC;AACxC,+DAA+D;AAC/D,eAAO,MAAM,IAAI,EAAE,OAAO,KAAa,CAAC"}

View File

@@ -0,0 +1 @@
{"version":3,"file":"fix-codec-size.d.ts","sourceRoot":"","sources":["../../src/fix-codec-size.ts"],"names":[],"mappings":"AAEA,OAAO,EACH,KAAK,EAGL,OAAO,EACP,OAAO,EACP,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAGnB,MAAM,SAAS,CAAC;AAGjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,KAAK,SAAS,MAAM,EACtD,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,EACvB,UAAU,EAAE,KAAK,GAClB,gBAAgB,CAAC,KAAK,EAAE,KAAK,CAAC,CAchC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,KAAK,SAAS,MAAM,EACpD,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,EACrB,UAAU,EAAE,KAAK,GAClB,gBAAgB,CAAC,GAAG,EAAE,KAAK,CAAC,CAkB9B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,GAAG,SAAS,KAAK,EAAE,KAAK,SAAS,MAAM,EACvE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,EACxB,UAAU,EAAE,KAAK,GAClB,cAAc,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,CAAC,CAEnC"}

View File

@@ -0,0 +1,19 @@
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util';
declare const baseRule: TSESLint.RuleModule<"preferDestructuring", [import("eslint/lib/rules/prefer-destructuring").DestructuringTypeConfig | {
AssignmentExpression?: import("eslint/lib/rules/prefer-destructuring").DestructuringTypeConfig;
VariableDeclarator?: import("eslint/lib/rules/prefer-destructuring").DestructuringTypeConfig;
}, (import("eslint/lib/rules/prefer-destructuring").Option1 | undefined)?], unknown, {
AssignmentExpression(node: TSESTree.AssignmentExpression): void;
VariableDeclarator(node: TSESTree.VariableDeclarator): void;
}>;
type BaseOptions = InferOptionsTypeFromRule<typeof baseRule>;
type EnforcementOptions = {
enforceForDeclarationWithTypeAnnotation?: boolean;
} & BaseOptions[1];
export type Options = [BaseOptions[0], EnforcementOptions];
export type MessageIds = InferMessageIdsTypeFromRule<typeof baseRule>;
declare const _default: TSESLint.RuleModule<"preferDestructuring", Options, import("../../rules").ESLintPluginDocs, TSESLint.RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,83 @@
/*! *****************************************************************************
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"/>
declare namespace Intl {
// http://cldr.unicode.org/index/cldr-spec/plural-rules#TOC-Determining-Plural-Categories
type LDMLPluralRule = "zero" | "one" | "two" | "few" | "many" | "other";
type PluralRuleType = "cardinal" | "ordinal";
interface PluralRulesOptions {
localeMatcher?: "lookup" | "best fit" | undefined;
type?: PluralRuleType | undefined;
minimumIntegerDigits?: number | undefined;
minimumFractionDigits?: number | undefined;
maximumFractionDigits?: number | undefined;
minimumSignificantDigits?: number | undefined;
maximumSignificantDigits?: number | undefined;
}
interface ResolvedPluralRulesOptions {
locale: string;
pluralCategories: LDMLPluralRule[];
type: PluralRuleType;
minimumIntegerDigits: number;
minimumFractionDigits: number;
maximumFractionDigits: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface PluralRules {
resolvedOptions(): ResolvedPluralRulesOptions;
select(n: number): LDMLPluralRule;
}
interface PluralRulesConstructor {
new (locales?: string | readonly string[], options?: PluralRulesOptions): PluralRules;
(locales?: string | readonly string[], options?: PluralRulesOptions): PluralRules;
supportedLocalesOf(locales: string | readonly string[], options?: { localeMatcher?: "lookup" | "best fit"; }): string[];
}
const PluralRules: PluralRulesConstructor;
interface NumberFormatPartTypeRegistry {
literal: never;
nan: never;
infinity: never;
percent: never;
integer: never;
group: never;
decimal: never;
fraction: never;
plusSign: never;
minusSign: never;
percentSign: never;
currency: never;
}
type NumberFormatPartTypes = keyof NumberFormatPartTypeRegistry;
interface NumberFormatPart {
type: NumberFormatPartTypes;
value: string;
}
interface NumberFormat {
formatToParts(number?: number | bigint): NumberFormatPart[];
}
}

View File

@@ -0,0 +1,91 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hmac = exports.HMAC = void 0;
/**
* HMAC: RFC2104 message authentication code.
* @module
*/
const utils_ts_1 = require("./utils.js");
class HMAC extends utils_ts_1.Hash {
constructor(hash, _key) {
super();
this.finished = false;
this.destroyed = false;
(0, utils_ts_1.ahash)(hash);
const key = (0, utils_ts_1.toBytes)(_key);
this.iHash = hash.create();
if (typeof this.iHash.update !== 'function')
throw new Error('Expected instance of class which extends utils.Hash');
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad = new Uint8Array(blockLen);
// blockLen can be bigger than outputLen
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 0x36;
this.iHash.update(pad);
// By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
this.oHash = hash.create();
// Undo internal XOR && apply outer XOR
for (let i = 0; i < pad.length; i++)
pad[i] ^= 0x36 ^ 0x5c;
this.oHash.update(pad);
(0, utils_ts_1.clean)(pad);
}
update(buf) {
(0, utils_ts_1.aexists)(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
(0, utils_ts_1.aexists)(this);
(0, utils_ts_1.abytes)(out, this.outputLen);
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
// Create new instance without calling constructor since key already in state and we don't know it.
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
clone() {
return this._cloneInto();
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
}
exports.HMAC = HMAC;
/**
* HMAC: RFC2104 message authentication code.
* @param hash - function that would be used e.g. sha256
* @param key - message key
* @param message - message data
* @example
* import { hmac } from '@noble/hashes/hmac';
* import { sha256 } from '@noble/hashes/sha2';
* const mac1 = hmac(sha256, 'key', 'message');
*/
const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
exports.hmac = hmac;
exports.hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map

View File

@@ -0,0 +1,154 @@
{
"$schema": "http://json-schema.org/draft-06/schema#",
"$id": "http://json-schema.org/draft-06/schema#",
"title": "Core schema meta-schema",
"definitions": {
"schemaArray": {
"type": "array",
"minItems": 1,
"items": { "$ref": "#" }
},
"nonNegativeInteger": {
"type": "integer",
"minimum": 0
},
"nonNegativeIntegerDefault0": {
"allOf": [
{ "$ref": "#/definitions/nonNegativeInteger" },
{ "default": 0 }
]
},
"simpleTypes": {
"enum": [
"array",
"boolean",
"integer",
"null",
"number",
"object",
"string"
]
},
"stringArray": {
"type": "array",
"items": { "type": "string" },
"uniqueItems": true,
"default": []
}
},
"type": ["object", "boolean"],
"properties": {
"$id": {
"type": "string",
"format": "uri-reference"
},
"$schema": {
"type": "string",
"format": "uri"
},
"$ref": {
"type": "string",
"format": "uri-reference"
},
"title": {
"type": "string"
},
"description": {
"type": "string"
},
"default": {},
"examples": {
"type": "array",
"items": {}
},
"multipleOf": {
"type": "number",
"exclusiveMinimum": 0
},
"maximum": {
"type": "number"
},
"exclusiveMaximum": {
"type": "number"
},
"minimum": {
"type": "number"
},
"exclusiveMinimum": {
"type": "number"
},
"maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
"minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
"pattern": {
"type": "string",
"format": "regex"
},
"additionalItems": { "$ref": "#" },
"items": {
"anyOf": [
{ "$ref": "#" },
{ "$ref": "#/definitions/schemaArray" }
],
"default": {}
},
"maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
"minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
"uniqueItems": {
"type": "boolean",
"default": false
},
"contains": { "$ref": "#" },
"maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
"minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
"required": { "$ref": "#/definitions/stringArray" },
"additionalProperties": { "$ref": "#" },
"definitions": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"properties": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"patternProperties": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"dependencies": {
"type": "object",
"additionalProperties": {
"anyOf": [
{ "$ref": "#" },
{ "$ref": "#/definitions/stringArray" }
]
}
},
"propertyNames": { "$ref": "#" },
"const": {},
"enum": {
"type": "array",
"minItems": 1,
"uniqueItems": true
},
"type": {
"anyOf": [
{ "$ref": "#/definitions/simpleTypes" },
{
"type": "array",
"items": { "$ref": "#/definitions/simpleTypes" },
"minItems": 1,
"uniqueItems": true
}
]
},
"format": { "type": "string" },
"allOf": { "$ref": "#/definitions/schemaArray" },
"anyOf": { "$ref": "#/definitions/schemaArray" },
"oneOf": { "$ref": "#/definitions/schemaArray" },
"not": { "$ref": "#" }
},
"default": {}
}

View File

@@ -0,0 +1,104 @@
# why-is-node-running
Node is running but you don't know why? `why-is-node-running` is here to help you.
## Installation
Node 8 and above:
```bash
npm i why-is-node-running -g
```
Earlier Node versions (no longer supported):
```bash
npm i why-is-node-running@v1.x -g
```
## Usage
```js
const log = require('why-is-node-running') // should be your first require
const net = require('net')
function createServer () {
const server = net.createServer()
setInterval(function () {}, 1000)
server.listen(0)
}
createServer()
createServer()
setTimeout(function () {
log() // logs out active handles that are keeping node running
}, 100)
```
Save the file as `example.js`, then execute:
```bash
node ./example.js
```
Here's the output:
```
There are 5 handle(s) keeping the process running
# Timeout
/home/maf/dev/node_modules/why-is-node-running/example.js:6 - setInterval(function () {}, 1000)
/home/maf/dev/node_modules/why-is-node-running/example.js:10 - createServer()
# TCPSERVERWRAP
/home/maf/dev/node_modules/why-is-node-running/example.js:7 - server.listen(0)
/home/maf/dev/node_modules/why-is-node-running/example.js:10 - createServer()
# Timeout
/home/maf/dev/node_modules/why-is-node-running/example.js:6 - setInterval(function () {}, 1000)
/home/maf/dev/node_modules/why-is-node-running/example.js:11 - createServer()
# TCPSERVERWRAP
/home/maf/dev/node_modules/why-is-node-running/example.js:7 - server.listen(0)
/home/maf/dev/node_modules/why-is-node-running/example.js:11 - createServer()
# Timeout
/home/maf/dev/node_modules/why-is-node-running/example.js:13 - setTimeout(function () {
```
**Important Note!**
`unref`ed timers do not prevent the Node process from exiting. If you are running with Node v11.0.0 and above, `unref`ed timers will not be listed in the above list. Unfortunately, this is not supported in node versions below v11.0.0.
## CLI
You can also run `why-is-node-running` as a standalone if you don't want to include it inside your code. Sending `SIGUSR1`/`SIGINFO` signal to the process will produce the log. (`Ctrl + T` on macOS and BSD systems)
```bash
why-is-node-running /path/to/some/file.js
```
```
probing module /path/to/some/file.js
kill -SIGUSR1 31115 for logging
```
To trigger the log:
```
kill -SIGUSR1 31115
```
## Require CLI Option
You can also use the node `-r` option to include `why-is-node-running`:
```bash
node -r why-is-node-running/include /path/to/some/file.js
```
The steps are otherwise the same as the above CLI section
## License
MIT

View File

@@ -0,0 +1,22 @@
import type { ScopeManager } from '@typescript-eslint/scope-manager';
import type { ParserOptions, TSESTree } from '@typescript-eslint/types';
import type { AST, ParserServices } from '@typescript-eslint/typescript-estree';
import type { VisitorKeys } from '@typescript-eslint/visitor-keys';
import type * as ts from 'typescript';
interface ESLintProgram extends AST<{
comment: true;
tokens: true;
}> {
comments: TSESTree.Comment[];
range: [number, number];
tokens: TSESTree.Token[];
}
interface ParseForESLintResult {
ast: ESLintProgram;
scopeManager: ScopeManager;
services: ParserServices;
visitorKeys: VisitorKeys;
}
export declare function parse(code: string | ts.SourceFile, options?: ParserOptions): ParseForESLintResult['ast'];
export declare function parseForESLint(code: string | ts.SourceFile, parserOptions?: ParserOptions | null): ParseForESLintResult;
export type { ParserOptions } from '@typescript-eslint/types';

View File

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

View File

@@ -0,0 +1,26 @@
{
"name": "@types/esrecurse",
"version": "4.3.1",
"description": "TypeScript definitions for esrecurse",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/esrecurse",
"license": "MIT",
"contributors": [
{
"name": "Jimmy Leung",
"githubUsername": "hkleungai",
"url": "https://github.com/hkleungai"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/esrecurse"
},
"scripts": {},
"dependencies": {},
"peerDependencies": {},
"typesPublisherContentHash": "0e4ed7e0fe84b6879532ce29fdfe397c1fc205d0c9dbc17172b64f3016ae0065",
"typeScriptVersion": "5.1"
}

View File

@@ -0,0 +1,81 @@
type Pathname = string
interface IgnoreRule {
pattern: string
mark?: string
negative: boolean
}
interface TestResult {
ignored: boolean
unignored: boolean
rule?: IgnoreRule
}
interface PatternParams {
pattern: string
mark?: string
}
/**
* Creates new ignore manager.
*/
declare function ignore(options?: ignore.Options): ignore.Ignore
declare namespace ignore {
interface Ignore {
/**
* Adds one or several rules to the current manager.
* @param {string[]} patterns
* @returns IgnoreBase
*/
add(
patterns: string | Ignore | readonly (string | Ignore)[] | PatternParams
): this
/**
* Filters the given array of pathnames, and returns the filtered array.
* NOTICE that each path here should be a relative path to the root of your repository.
* @param paths the array of paths to be filtered.
* @returns The filtered array of paths
*/
filter(pathnames: readonly Pathname[]): Pathname[]
/**
* Creates a filter function which could filter
* an array of paths with Array.prototype.filter.
*/
createFilter(): (pathname: Pathname) => boolean
/**
* Returns Boolean whether pathname should be ignored.
* @param {string} pathname a path to check
* @returns boolean
*/
ignores(pathname: Pathname): boolean
/**
* Returns whether pathname should be ignored or unignored
* @param {string} pathname a path to check
* @returns TestResult
*/
test(pathname: Pathname): TestResult
/**
* Debugs ignore rules and returns the checking result, which is
* equivalent to `git check-ignore -v`.
* @returns TestResult
*/
checkIgnore(pathname: Pathname): TestResult
}
interface Options {
ignorecase?: boolean
// For compatibility
ignoreCase?: boolean
allowRelativePaths?: boolean
}
function isPathValid(pathname: string): boolean
}
export = ignore

View File

@@ -0,0 +1,23 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.es2020_bigint = void 0;
const base_config_1 = require("./base-config");
const es2020_intl_1 = require("./es2020.intl");
exports.es2020_bigint = {
libs: [es2020_intl_1.es2020_intl],
variables: [
['BigIntToLocaleStringOptions', base_config_1.TYPE],
['BigInt', base_config_1.TYPE_VALUE],
['BigIntConstructor', base_config_1.TYPE],
['BigInt64Array', base_config_1.TYPE_VALUE],
['BigInt64ArrayConstructor', base_config_1.TYPE],
['BigUint64Array', base_config_1.TYPE_VALUE],
['BigUint64ArrayConstructor', base_config_1.TYPE],
['DataView', base_config_1.TYPE],
['Intl', base_config_1.TYPE_VALUE],
],
};

View File

@@ -0,0 +1,8 @@
"use strict";
function _overload_yield(value, /** 0: await 1: delegate */ kind) {
this.v = value;
this.k = kind;
}
exports._ = _overload_yield;

View File

@@ -0,0 +1,25 @@
{
"name": "picocolors",
"version": "1.1.1",
"main": "./picocolors.js",
"types": "./picocolors.d.ts",
"browser": {
"./picocolors.js": "./picocolors.browser.js"
},
"sideEffects": false,
"description": "The tiniest and the fastest library for terminal output formatting with ANSI colors",
"files": [
"picocolors.*",
"types.d.ts"
],
"keywords": [
"terminal",
"colors",
"formatting",
"cli",
"console"
],
"author": "Alexey Raspopov",
"repository": "alexeyraspopov/picocolors",
"license": "ISC"
}

View File

@@ -0,0 +1,113 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{## def.setExclusiveLimit:
$exclusive = true;
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
#}}
{{
var $isMax = $keyword == 'maximum'
, $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum'
, $schemaExcl = it.schema[$exclusiveKeyword]
, $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data
, $op = $isMax ? '<' : '>'
, $notOp = $isMax ? '>' : '<'
, $errorKeyword = undefined;
if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
throw new Error($keyword + ' must be number');
}
if (!($isDataExcl || $schemaExcl === undefined
|| typeof $schemaExcl == 'number'
|| typeof $schemaExcl == 'boolean')) {
throw new Error($exclusiveKeyword + ' must be number or boolean');
}
}}
{{? $isDataExcl }}
{{
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr)
, $exclusive = 'exclusive' + $lvl
, $exclType = 'exclType' + $lvl
, $exclIsNumber = 'exclIsNumber' + $lvl
, $opExpr = 'op' + $lvl
, $opStr = '\' + ' + $opExpr + ' + \'';
}}
var schemaExcl{{=$lvl}} = {{=$schemaValueExcl}};
{{ $schemaValueExcl = 'schemaExcl' + $lvl; }}
var {{=$exclusive}};
var {{=$exclType}} = typeof {{=$schemaValueExcl}};
if ({{=$exclType}} != 'boolean' && {{=$exclType}} != 'undefined' && {{=$exclType}} != 'number') {
{{ var $errorKeyword = $exclusiveKeyword; }}
{{# def.error:'_exclusiveLimit' }}
} else if ({{# def.$dataNotType:'number' }}
{{=$exclType}} == 'number'
? (
({{=$exclusive}} = {{=$schemaValue}} === undefined || {{=$schemaValueExcl}} {{=$op}}= {{=$schemaValue}})
? {{=$data}} {{=$notOp}}= {{=$schemaValueExcl}}
: {{=$data}} {{=$notOp}} {{=$schemaValue}}
)
: (
({{=$exclusive}} = {{=$schemaValueExcl}} === true)
? {{=$data}} {{=$notOp}}= {{=$schemaValue}}
: {{=$data}} {{=$notOp}} {{=$schemaValue}}
)
|| {{=$data}} !== {{=$data}}) {
var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}=';
{{
if ($schema === undefined) {
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
$schemaValue = $schemaValueExcl;
$isData = $isDataExcl;
}
}}
{{??}}
{{
var $exclIsNumber = typeof $schemaExcl == 'number'
, $opStr = $op; /*used in error*/
}}
{{? $exclIsNumber && $isData }}
{{ var $opExpr = '\'' + $opStr + '\''; /*used in error*/ }}
if ({{# def.$dataNotType:'number' }}
( {{=$schemaValue}} === undefined
|| {{=$schemaExcl}} {{=$op}}= {{=$schemaValue}}
? {{=$data}} {{=$notOp}}= {{=$schemaExcl}}
: {{=$data}} {{=$notOp}} {{=$schemaValue}} )
|| {{=$data}} !== {{=$data}}) {
{{??}}
{{
if ($exclIsNumber && $schema === undefined) {
{{# def.setExclusiveLimit }}
$schemaValue = $schemaExcl;
$notOp += '=';
} else {
if ($exclIsNumber)
$schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
{{# def.setExclusiveLimit }}
$notOp += '=';
} else {
$exclusive = false;
$opStr += '=';
}
}
var $opExpr = '\'' + $opStr + '\''; /*used in error*/
}}
if ({{# def.$dataNotType:'number' }}
{{=$data}} {{=$notOp}} {{=$schemaValue}}
|| {{=$data}} !== {{=$data}}) {
{{?}}
{{?}}
{{ $errorKeyword = $errorKeyword || $keyword; }}
{{# def.error:'_limit' }}
} {{? $breakOnError }} else { {{?}}

View File

@@ -0,0 +1,150 @@
declare var global: typeof globalThis;
declare var process: NodeJS.Process;
interface ErrorConstructor {
/**
* Creates a `.stack` property on `targetObject`, which when accessed returns
* a string representing the location in the code at which
* `Error.captureStackTrace()` was called.
*
* ```js
* const myObject = {};
* Error.captureStackTrace(myObject);
* myObject.stack; // Similar to `new Error().stack`
* ```
*
* The first line of the trace will be prefixed with
* `${myObject.name}: ${myObject.message}`.
*
* The optional `constructorOpt` argument accepts a function. If given, all frames
* above `constructorOpt`, including `constructorOpt`, will be omitted from the
* generated stack trace.
*
* The `constructorOpt` argument is useful for hiding implementation
* details of error generation from the user. For instance:
*
* ```js
* function a() {
* b();
* }
*
* function b() {
* c();
* }
*
* function c() {
* // Create an error without stack trace to avoid calculating the stack trace twice.
* const { stackTraceLimit } = Error;
* Error.stackTraceLimit = 0;
* const error = new Error();
* Error.stackTraceLimit = stackTraceLimit;
*
* // Capture the stack trace above function b
* Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
* throw error;
* }
*
* a();
* ```
*/
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
/**
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
*/
prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
/**
* The `Error.stackTraceLimit` property specifies the number of stack frames
* collected by a stack trace (whether generated by `new Error().stack` or
* `Error.captureStackTrace(obj)`).
*
* The default value is `10` but may be set to any valid JavaScript number. Changes
* will affect any stack trace captured _after_ the value has been changed.
*
* If set to a non-number value, or set to a negative number, stack traces will
* not capture any frames.
*/
stackTraceLimit: number;
}
/**
* Enable this API with the `--expose-gc` CLI flag.
*/
declare var gc: NodeJS.GCFunction | undefined;
declare namespace NodeJS {
interface CallSite {
getColumnNumber(): number | null;
getEnclosingColumnNumber(): number | null;
getEnclosingLineNumber(): number | null;
getEvalOrigin(): string | undefined;
getFileName(): string | null;
getFunction(): Function | undefined;
getFunctionName(): string | null;
getLineNumber(): number | null;
getMethodName(): string | null;
getPosition(): number;
getPromiseIndex(): number | null;
getScriptHash(): string;
getScriptNameOrSourceURL(): string | null;
getThis(): unknown;
getTypeName(): string | null;
isAsync(): boolean;
isConstructor(): boolean;
isEval(): boolean;
isNative(): boolean;
isPromiseAll(): boolean;
isToplevel(): boolean;
}
interface ErrnoException extends Error {
errno?: number;
code?: string;
path?: string;
syscall?: string;
}
interface RefCounted {
ref(): this;
unref(): this;
}
interface Dict<T> {
[key: string]: T | undefined;
}
interface ReadOnlyDict<T> {
readonly [key: string]: T | undefined;
}
type PartialOptions<T> = { [K in keyof T]?: T[K] | undefined };
interface GCFunction {
(minor?: boolean): void;
(options: NodeJS.GCOptions & { execution: "async" }): Promise<void>;
(options: NodeJS.GCOptions): void;
}
interface GCOptions {
execution?: "sync" | "async" | undefined;
flavor?: "regular" | "last-resort" | undefined;
type?: "major-snapshot" | "major" | "minor" | undefined;
filename?: string | undefined;
}
/** An iterable iterator returned by the Node.js API. */
interface Iterator<T, TReturn = undefined, TNext = any> extends IteratorObject<T, TReturn, TNext> {
[Symbol.iterator](): NodeJS.Iterator<T, TReturn, TNext>;
}
/** An async iterable iterator returned by the Node.js API. */
interface AsyncIterator<T, TReturn = undefined, TNext = any> extends AsyncIteratorObject<T, TReturn, TNext> {
[Symbol.asyncIterator](): NodeJS.AsyncIterator<T, TReturn, TNext>;
}
/** The [`BufferSource`](https://webidl.spec.whatwg.org/#BufferSource) type from the Web IDL specification. */
type BufferSource = NonSharedArrayBufferView | ArrayBuffer;
/** The [`AllowSharedBufferSource`](https://webidl.spec.whatwg.org/#AllowSharedBufferSource) type from the Web IDL specification. */
type AllowSharedBufferSource = ArrayBufferView | ArrayBufferLike;
}

View File

@@ -0,0 +1,28 @@
function dispose_SuppressedError(r, e) {
return "undefined" != typeof SuppressedError ? dispose_SuppressedError = SuppressedError : (dispose_SuppressedError = function dispose_SuppressedError(r, e) {
this.suppressed = e, this.error = r, this.stack = Error().stack;
}, dispose_SuppressedError.prototype = Object.create(Error.prototype, {
constructor: {
value: dispose_SuppressedError,
writable: !0,
configurable: !0
}
})), new dispose_SuppressedError(r, e);
}
function _dispose(r, e, s) {
function next() {
for (; r.length > 0;) try {
var o = r.pop(),
p = o.d.call(o.v);
if (o.a) return Promise.resolve(p).then(next, err);
} catch (r) {
return err(r);
}
if (s) throw e;
}
function err(r) {
return e = s ? new dispose_SuppressedError(e, r) : r, s = !0, next();
}
return next();
}
export { _dispose as default };

View File

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

View File

@@ -0,0 +1,88 @@
import { FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';
import { NumberCodecConfig } from './common';
/**
* Returns an encoder for 64-bit unsigned integers (`u64`).
*
* This encoder serializes `u64` values using 8 bytes.
* Values can be provided as either `number` or `bigint`.
*
* For more details, see {@link getU64Codec}.
*
* @param config - Optional configuration to specify endianness (little by default).
* @returns A `FixedSizeEncoder<number | bigint, 8>` for encoding `u64` values.
*
* @example
* Encoding a `u64` value.
* ```ts
* const encoder = getU64Encoder();
* const bytes = encoder.encode(42); // 0x2a00000000000000
* ```
*
* @see {@link getU64Codec}
*/
export declare const getU64Encoder: (config?: NumberCodecConfig) => FixedSizeEncoder<bigint | number, 8>;
/**
* Returns a decoder for 64-bit unsigned integers (`u64`).
*
* This decoder deserializes `u64` values from 8 bytes.
* The decoded value is always a `bigint`.
*
* For more details, see {@link getU64Codec}.
*
* @param config - Optional configuration to specify endianness (little by default).
* @returns A `FixedSizeDecoder<bigint, 8>` for decoding `u64` values.
*
* @example
* Decoding a `u64` value.
* ```ts
* const decoder = getU64Decoder();
* const value = decoder.decode(new Uint8Array([0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])); // 42n
* ```
*
* @see {@link getU64Codec}
*/
export declare const getU64Decoder: (config?: NumberCodecConfig) => FixedSizeDecoder<bigint, 8>;
/**
* Returns a codec for encoding and decoding 64-bit unsigned integers (`u64`).
*
* This codec serializes `u64` values using 8 bytes.
* Values can be provided as either `number` or `bigint`, but the decoded value is always a `bigint`.
*
* @param config - Optional configuration to specify endianness (little by default).
* @returns A `FixedSizeCodec<number | bigint, bigint, 8>` for encoding and decoding `u64` values.
*
* @example
* Encoding and decoding a `u64` value.
* ```ts
* const codec = getU64Codec();
* const bytes = codec.encode(42); // 0x2a00000000000000
* const value = codec.decode(bytes); // 42n
* ```
*
* @example
* Using big-endian encoding.
* ```ts
* const codec = getU64Codec({ endian: Endian.Big });
* const bytes = codec.encode(42); // 0x000000000000002a
* ```
*
* @remarks
* This codec supports values between `0` and `2^64 - 1`.
* Since JavaScript `number` cannot safely represent values beyond `2^53 - 1`, the decoded value is always a `bigint`.
*
* - If you need a smaller unsigned integer, consider using {@link getU32Codec} or {@link getU16Codec}.
* - If you need a larger unsigned integer, consider using {@link getU128Codec}.
* - If you need signed integers, consider using {@link getI64Codec}.
*
* Separate {@link getU64Encoder} and {@link getU64Decoder} functions are available.
*
* ```ts
* const bytes = getU64Encoder().encode(42);
* const value = getU64Decoder().decode(bytes);
* ```
*
* @see {@link getU64Encoder}
* @see {@link getU64Decoder}
*/
export declare const getU64Codec: (config?: NumberCodecConfig) => FixedSizeCodec<bigint | number, bigint, 8>;
//# sourceMappingURL=u64.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"blake2.d.ts","sourceRoot":"","sources":["../src/blake2.ts"],"names":[],"mappings":"AASA,OAAO,EAEmB,IAAI,EAC5B,KAAK,MAAM,EAAE,KAAK,KAAK,EACxB,MAAM,YAAY,CAAC;AAEpB,qGAAqG;AACrG,MAAM,MAAM,UAAU,GAAG;IACvB,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,CAAC;IAE1C,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;gBAEf,IAAI,GAAE,UAAe;IA+BjC,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;IAKjF,SAAS,CAAC,GAAG,CACX,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAC7F,IAAI;IAUP,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI;IAkB3E,OAAO,IAAI,IAAI;CAKhB;AAED;;;;GAIG;AACH,eAAO,MAAM,OAAO,EAAE,MAErB,CAAC"}

View File

@@ -0,0 +1,146 @@
import { RangePosition } from './css-syntax-error.js'
import Node from './node.js'
declare namespace Warning {
export interface WarningOptions {
/**
* End position, exclusive, in CSS node string that caused the warning.
*/
end?: RangePosition
/**
* End index, exclusive, in CSS node string that caused the warning.
*/
endIndex?: number
/**
* Start index, inclusive, in CSS node string that caused the warning.
*/
index?: number
/**
* CSS node that caused the warning.
*/
node?: Node
/**
* Name of the plugin that created this warning. `Result#warn` fills
* this property automatically.
*/
plugin?: string
/**
* Start position, inclusive, in CSS node string that caused the warning.
*/
start?: RangePosition
/**
* Word in CSS source that caused the warning.
*/
word?: string
}
export { Warning_ as default }
}
/**
* Represents a plugins warning. It can be created using `Node#warn`.
*
* ```js
* if (decl.important) {
* decl.warn(result, 'Avoid !important', { word: '!important' })
* }
* ```
*/
declare class Warning_ {
/**
* Column for inclusive start position in the input file with this warnings source.
*
* ```js
* warning.column //=> 6
* ```
*/
column: number
/**
* Column for exclusive end position in the input file with this warnings source.
*
* ```js
* warning.endColumn //=> 4
* ```
*/
endColumn?: number
/**
* Line for exclusive end position in the input file with this warnings source.
*
* ```js
* warning.endLine //=> 6
* ```
*/
endLine?: number
/**
* Line for inclusive start position in the input file with this warnings source.
*
* ```js
* warning.line //=> 5
* ```
*/
line: number
/**
* Contains the CSS node that caused the warning.
*
* ```js
* warning.node.toString() //=> 'color: white !important'
* ```
*/
node: Node
/**
* The name of the plugin that created this warning.
* When you call `Node#warn` it will fill this property automatically.
*
* ```js
* warning.plugin //=> 'postcss-important'
* ```
*/
plugin: string
/**
* The warning message.
*
* ```js
* warning.text //=> 'Try to avoid !important'
* ```
*/
text: string
/**
* Type to filter warnings from `Result#messages`.
* Always equal to `"warning"`.
*/
type: 'warning'
/**
* @param text Warning message.
* @param opts Warning options.
*/
constructor(text: string, opts?: Warning.WarningOptions)
/**
* Returns a warning position and message.
*
* ```js
* warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
* ```
*
* @return Warning position and message.
*/
toString(): string
}
declare class Warning extends Warning_ {}
export = Warning

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/abstract/utils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,CAAC,MAAM,aAAa,CAAC;AAEjC,oDAAoD;AACpD,MAAM,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC;AACxB,oDAAoD;AACpD,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,OAAO,CAAC;AAChC,oDAAoD;AACpD,MAAM,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC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pD,eAAO,MAAM,MAAM,EAAE,OAAO,CAAC,CAAC,MAAiB,CAAC"}

View File

@@ -0,0 +1,126 @@
import Container, {
ContainerProps,
ContainerWithChildren
} from './container.js'
declare namespace Rule {
export interface RuleRaws extends Record<string, unknown> {
/**
* The space symbols after the last child of the node to the end of the node.
*/
after?: string
/**
* The space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
*/
before?: string
/**
* The symbols between the selector and `{` for rules.
*/
between?: string
/**
* Contains the text of the semicolon after this rule.
*/
ownSemicolon?: string
/**
* The rules selector with comments.
*/
selector?: {
raw: string
value: string
}
/**
* Contains `true` if the last child has an (optional) semicolon.
*/
semicolon?: boolean
}
export type RuleProps = {
/** Information used to generate byte-to-byte equal node string as it was in the origin input. */
raws?: RuleRaws
} & (
| {
/** Selector or selectors of the rule. */
selector: string
selectors?: never
}
| {
selector?: never
/** Selectors of the rule represented as an array of strings. */
selectors: readonly string[]
}
) &
ContainerProps
export { Rule_ as default }
}
/**
* Represents a CSS rule: a selector followed by a declaration block.
*
* ```js
* Once (root, { Rule }) {
* let a = new Rule({ selector: 'a' })
* a.append(…)
* root.append(a)
* }
* ```
*
* ```js
* const root = postcss.parse('a{}')
* const rule = root.first
* rule.type //=> 'rule'
* rule.toString() //=> 'a{}'
* ```
*/
declare class Rule_ extends Container {
nodes: NonNullable<Container['nodes']>
parent: ContainerWithChildren | undefined
raws: Rule.RuleRaws
type: 'rule'
/**
* The rules full selector represented as a string.
*
* ```js
* const root = postcss.parse('a, b { }')
* const rule = root.first
* rule.selector //=> 'a, b'
* ```
*/
get selector(): string
set selector(value: string)
/**
* An array containing the rules individual selectors.
* Groups of selectors are split at commas.
*
* ```js
* const root = postcss.parse('a, b { }')
* const rule = root.first
*
* rule.selector //=> 'a, b'
* rule.selectors //=> ['a', 'b']
*
* rule.selectors = ['a', 'strong']
* rule.selector //=> 'a, strong'
* ```
*/
get selectors(): string[]
set selectors(values: string[])
constructor(defaults?: Rule.RuleProps)
assign(overrides: object | Rule.RuleProps): this
clone(overrides?: Partial<Rule.RuleProps>): this
cloneAfter(overrides?: Partial<Rule.RuleProps>): this
cloneBefore(overrides?: Partial<Rule.RuleProps>): this
}
declare class Rule extends Rule_ {}
export = Rule

View File

@@ -0,0 +1,404 @@
const test = require('tap').test
const fss = require('./').stable
const clone = require('clone')
const s = JSON.stringify
const stream = require('stream')
test('circular reference to root', function (assert) {
const fixture = { name: 'Tywin Lannister' }
fixture.circle = fixture
const expected = s({ circle: '[Circular]', name: 'Tywin Lannister' })
const actual = fss(fixture)
assert.equal(actual, expected)
assert.end()
})
test('circular getter reference to root', function (assert) {
const fixture = {
name: 'Tywin Lannister',
get circle () {
return fixture
}
}
const expected = s({ circle: '[Circular]', name: 'Tywin Lannister' })
const actual = fss(fixture)
assert.equal(actual, expected)
assert.end()
})
test('nested circular reference to root', function (assert) {
const fixture = { name: 'Tywin Lannister' }
fixture.id = { circle: fixture }
const expected = s({ id: { circle: '[Circular]' }, name: 'Tywin Lannister' })
const actual = fss(fixture)
assert.equal(actual, expected)
assert.end()
})
test('child circular reference', function (assert) {
const fixture = {
name: 'Tywin Lannister',
child: { name: 'Tyrion Lannister' }
}
fixture.child.dinklage = fixture.child
const expected = s({
child: {
dinklage: '[Circular]',
name: 'Tyrion Lannister'
},
name: 'Tywin Lannister'
})
const actual = fss(fixture)
assert.equal(actual, expected)
assert.end()
})
test('nested child circular reference', function (assert) {
const fixture = {
name: 'Tywin Lannister',
child: { name: 'Tyrion Lannister' }
}
fixture.child.actor = { dinklage: fixture.child }
const expected = s({
child: {
actor: { dinklage: '[Circular]' },
name: 'Tyrion Lannister'
},
name: 'Tywin Lannister'
})
const actual = fss(fixture)
assert.equal(actual, expected)
assert.end()
})
test('circular objects in an array', function (assert) {
const fixture = { name: 'Tywin Lannister' }
fixture.hand = [fixture, fixture]
const expected = s({
hand: ['[Circular]', '[Circular]'],
name: 'Tywin Lannister'
})
const actual = fss(fixture)
assert.equal(actual, expected)
assert.end()
})
test('nested circular references in an array', function (assert) {
const fixture = {
name: 'Tywin Lannister',
offspring: [{ name: 'Tyrion Lannister' }, { name: 'Cersei Lannister' }]
}
fixture.offspring[0].dinklage = fixture.offspring[0]
fixture.offspring[1].headey = fixture.offspring[1]
const expected = s({
name: 'Tywin Lannister',
offspring: [
{ dinklage: '[Circular]', name: 'Tyrion Lannister' },
{ headey: '[Circular]', name: 'Cersei Lannister' }
]
})
const actual = fss(fixture)
assert.equal(actual, expected)
assert.end()
})
test('circular arrays', function (assert) {
const fixture = []
fixture.push(fixture, fixture)
const expected = s(['[Circular]', '[Circular]'])
const actual = fss(fixture)
assert.equal(actual, expected)
assert.end()
})
test('nested circular arrays', function (assert) {
const fixture = []
fixture.push(
{ name: 'Jon Snow', bastards: fixture },
{ name: 'Ramsay Bolton', bastards: fixture }
)
const expected = s([
{ bastards: '[Circular]', name: 'Jon Snow' },
{ bastards: '[Circular]', name: 'Ramsay Bolton' }
])
const actual = fss(fixture)
assert.equal(actual, expected)
assert.end()
})
test('repeated non-circular references in objects', function (assert) {
const daenerys = { name: 'Daenerys Targaryen' }
const fixture = {
motherOfDragons: daenerys,
queenOfMeereen: daenerys
}
const expected = s(fixture)
const actual = fss(fixture)
assert.equal(actual, expected)
assert.end()
})
test('repeated non-circular references in arrays', function (assert) {
const daenerys = { name: 'Daenerys Targaryen' }
const fixture = [daenerys, daenerys]
const expected = s(fixture)
const actual = fss(fixture)
assert.equal(actual, expected)
assert.end()
})
test('double child circular reference', function (assert) {
// create circular reference
const child = { name: 'Tyrion Lannister' }
child.dinklage = child
// include it twice in the fixture
const fixture = { name: 'Tywin Lannister', childA: child, childB: child }
const cloned = clone(fixture)
const expected = s({
childA: {
dinklage: '[Circular]',
name: 'Tyrion Lannister'
},
childB: {
dinklage: '[Circular]',
name: 'Tyrion Lannister'
},
name: 'Tywin Lannister'
})
const actual = fss(fixture)
assert.equal(actual, expected)
// check if the fixture has not been modified
assert.same(fixture, cloned)
assert.end()
})
test('child circular reference with toJSON', function (assert) {
// Create a test object that has an overridden `toJSON` property
TestObject.prototype.toJSON = function () {
return { special: 'case' }
}
function TestObject (content) {}
// Creating a simple circular object structure
const parentObject = {}
parentObject.childObject = new TestObject()
parentObject.childObject.parentObject = parentObject
// Creating a simple circular object structure
const otherParentObject = new TestObject()
otherParentObject.otherChildObject = {}
otherParentObject.otherChildObject.otherParentObject = otherParentObject
// Making sure our original tests work
assert.same(parentObject.childObject.parentObject, parentObject)
assert.same(
otherParentObject.otherChildObject.otherParentObject,
otherParentObject
)
// Should both be idempotent
assert.equal(fss(parentObject), '{"childObject":{"special":"case"}}')
assert.equal(fss(otherParentObject), '{"special":"case"}')
// Therefore the following assertion should be `true`
assert.same(parentObject.childObject.parentObject, parentObject)
assert.same(
otherParentObject.otherChildObject.otherParentObject,
otherParentObject
)
assert.end()
})
test('null object', function (assert) {
const expected = s(null)
const actual = fss(null)
assert.equal(actual, expected)
assert.end()
})
test('null property', function (assert) {
const expected = s({ f: null })
const actual = fss({ f: null })
assert.equal(actual, expected)
assert.end()
})
test('nested child circular reference in toJSON', function (assert) {
var circle = { some: 'data' }
circle.circle = circle
var a = {
b: {
toJSON: function () {
a.b = 2
return '[Redacted]'
}
},
baz: {
circle,
toJSON: function () {
a.baz = circle
return '[Redacted]'
}
}
}
var o = {
a,
bar: a
}
const expected = s({
a: {
b: '[Redacted]',
baz: '[Redacted]'
},
bar: {
// TODO: This is a known limitation of the current implementation.
// The ideal result would be:
//
// b: 2,
// baz: {
// circle: '[Circular]',
// some: 'data'
// }
//
b: '[Redacted]',
baz: '[Redacted]'
}
})
const actual = fss(o)
assert.equal(actual, expected)
assert.end()
})
test('circular getters are restored when stringified', function (assert) {
const fixture = {
name: 'Tywin Lannister',
get circle () {
return fixture
}
}
fss(fixture)
assert.equal(fixture.circle, fixture)
assert.end()
})
test('non-configurable circular getters use a replacer instead of markers', function (assert) {
const fixture = { name: 'Tywin Lannister' }
Object.defineProperty(fixture, 'circle', {
configurable: false,
get: function () {
return fixture
},
enumerable: true
})
fss(fixture)
assert.equal(fixture.circle, fixture)
assert.end()
})
test('getter child circular reference', function (assert) {
const fixture = {
name: 'Tywin Lannister',
child: {
name: 'Tyrion Lannister',
get dinklage () {
return fixture.child
}
},
get self () {
return fixture
}
}
const expected = s({
child: {
dinklage: '[Circular]',
name: 'Tyrion Lannister'
},
name: 'Tywin Lannister',
self: '[Circular]'
})
const actual = fss(fixture)
assert.equal(actual, expected)
assert.end()
})
test('Proxy throwing', function (assert) {
assert.plan(1)
const s = new stream.PassThrough()
s.resume()
s.write('', () => {
assert.end()
})
const actual = fss({ s, p: new Proxy({}, { get () { throw new Error('kaboom') } }) })
assert.equal(actual, '"[unable to serialize, circular reference is too complex to analyze]"')
})
test('depthLimit option - will replace deep objects', function (assert) {
const fixture = {
name: 'Tywin Lannister',
child: {
name: 'Tyrion Lannister'
},
get self () {
return fixture
}
}
const expected = s({
child: '[...]',
name: 'Tywin Lannister',
self: '[Circular]'
})
const actual = fss(fixture, undefined, undefined, {
depthLimit: 1,
edgesLimit: 1
})
assert.equal(actual, expected)
assert.end()
})
test('edgesLimit option - will replace deep objects', function (assert) {
const fixture = {
object: {
1: { test: 'test' },
2: { test: 'test' },
3: { test: 'test' },
4: { test: 'test' }
},
array: [
{ test: 'test' },
{ test: 'test' },
{ test: 'test' },
{ test: 'test' }
],
get self () {
return fixture
}
}
const expected = s({
array: [{ test: 'test' }, { test: 'test' }, { test: 'test' }, '[...]'],
object: {
1: { test: 'test' },
2: { test: 'test' },
3: { test: 'test' },
4: '[...]'
},
self: '[Circular]'
})
const actual = fss(fixture, undefined, undefined, {
depthLimit: 3,
edgesLimit: 3
})
assert.equal(actual, expected)
assert.end()
})

View File

@@ -0,0 +1,40 @@
{
"name": "@types/json-schema",
"version": "7.0.15",
"description": "TypeScript definitions for json-schema",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/json-schema",
"license": "MIT",
"contributors": [
{
"name": "Boris Cherny",
"githubUsername": "bcherny",
"url": "https://github.com/bcherny"
},
{
"name": "Lucian Buzzo",
"githubUsername": "lucianbuzzo",
"url": "https://github.com/lucianbuzzo"
},
{
"name": "Roland Groza",
"githubUsername": "rolandjitsu",
"url": "https://github.com/rolandjitsu"
},
{
"name": "Jason Kwok",
"githubUsername": "JasonHK",
"url": "https://github.com/JasonHK"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/json-schema"
},
"scripts": {},
"dependencies": {},
"typesPublisherContentHash": "79984fd70cd25c3f7d72b84368778c763c89728ea0073832d745d4691b705257",
"typeScriptVersion": "4.5"
}

View File

@@ -0,0 +1,719 @@
/**
* @fileoverview A rule to control the use of single variable declarations.
* @author Ian Christian Myers
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Determines whether the given node is in a statement list.
* @param {ASTNode} node node to check
* @returns {boolean} `true` if the given node is in a statement list
*/
function isInStatementList(node) {
return astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type);
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description:
"Enforce variables to be declared either together or separately in functions",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/one-var",
},
fixable: "code",
schema: [
{
oneOf: [
{
enum: ["always", "never", "consecutive"],
},
{
type: "object",
properties: {
separateRequires: {
type: "boolean",
},
var: {
enum: ["always", "never", "consecutive"],
},
let: {
enum: ["always", "never", "consecutive"],
},
const: {
enum: ["always", "never", "consecutive"],
},
using: {
enum: ["always", "never", "consecutive"],
},
awaitUsing: {
enum: ["always", "never", "consecutive"],
},
},
additionalProperties: false,
},
{
type: "object",
properties: {
initialized: {
enum: ["always", "never", "consecutive"],
},
uninitialized: {
enum: ["always", "never", "consecutive"],
},
},
additionalProperties: false,
},
],
},
],
defaultOptions: ["always"],
messages: {
combineUninitialized:
"Combine this with the previous '{{type}}' statement with uninitialized variables.",
combineInitialized:
"Combine this with the previous '{{type}}' statement with initialized variables.",
splitUninitialized:
"Split uninitialized '{{type}}' declarations into multiple statements.",
splitInitialized:
"Split initialized '{{type}}' declarations into multiple statements.",
splitRequires:
"Split requires to be separated into a single block.",
combine: "Combine this with the previous '{{type}}' statement.",
split: "Split '{{type}}' declarations into multiple statements.",
},
},
create(context) {
const MODE_ALWAYS = "always";
const MODE_NEVER = "never";
const MODE_CONSECUTIVE = "consecutive";
const mode = context.options[0];
const options = {};
if (typeof mode === "string") {
// simple options configuration with just a string
options.var = { uninitialized: mode, initialized: mode };
options.let = { uninitialized: mode, initialized: mode };
options.const = { uninitialized: mode, initialized: mode };
options.using = { uninitialized: mode, initialized: mode };
options.awaitUsing = { uninitialized: mode, initialized: mode };
} else if (typeof mode === "object") {
// options configuration is an object
options.separateRequires = !!mode.separateRequires;
options.var = { uninitialized: mode.var, initialized: mode.var };
options.let = { uninitialized: mode.let, initialized: mode.let };
options.const = {
uninitialized: mode.const,
initialized: mode.const,
};
options.using = {
uninitialized: mode.using,
initialized: mode.using,
};
options.awaitUsing = {
uninitialized: mode.awaitUsing,
initialized: mode.awaitUsing,
};
if (Object.hasOwn(mode, "uninitialized")) {
options.var.uninitialized = mode.uninitialized;
options.let.uninitialized = mode.uninitialized;
options.const.uninitialized = mode.uninitialized;
options.using.uninitialized = mode.uninitialized;
options.awaitUsing.uninitialized = mode.uninitialized;
}
if (Object.hasOwn(mode, "initialized")) {
options.var.initialized = mode.initialized;
options.let.initialized = mode.initialized;
options.const.initialized = mode.initialized;
options.using.initialized = mode.initialized;
options.awaitUsing.initialized = mode.initialized;
}
}
const sourceCode = context.sourceCode;
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
const functionStack = [];
const blockStack = [];
/**
* Increments the blockStack counter.
* @returns {void}
* @private
*/
function startBlock() {
blockStack.push({
let: { initialized: false, uninitialized: false },
const: { initialized: false, uninitialized: false },
using: { initialized: false, uninitialized: false },
awaitUsing: { initialized: false, uninitialized: false },
});
}
/**
* Increments the functionStack counter.
* @returns {void}
* @private
*/
function startFunction() {
functionStack.push({ initialized: false, uninitialized: false });
startBlock();
}
/**
* Decrements the blockStack counter.
* @returns {void}
* @private
*/
function endBlock() {
blockStack.pop();
}
/**
* Decrements the functionStack counter.
* @returns {void}
* @private
*/
function endFunction() {
functionStack.pop();
endBlock();
}
/**
* Check if a variable declaration is a require.
* @param {ASTNode} decl variable declaration Node
* @returns {bool} if decl is a require, return true; else return false.
* @private
*/
function isRequire(decl) {
return (
decl.init &&
decl.init.type === "CallExpression" &&
decl.init.callee.name === "require"
);
}
/**
* Records whether initialized/uninitialized/required variables are defined in current scope.
* @param {string} statementType one of: "var", "let", "const", "using", or "awaitUsing"
* @param {ASTNode[]} declarations List of declarations
* @param {Object} currentScope The scope being investigated
* @returns {void}
* @private
*/
function recordTypes(statementType, declarations, currentScope) {
for (let i = 0; i < declarations.length; i++) {
if (declarations[i].init === null) {
if (
options[statementType] &&
options[statementType].uninitialized === MODE_ALWAYS
) {
currentScope.uninitialized = true;
}
} else {
if (
options[statementType] &&
options[statementType].initialized === MODE_ALWAYS
) {
if (
options.separateRequires &&
isRequire(declarations[i])
) {
currentScope.required = true;
} else {
currentScope.initialized = true;
}
}
}
}
}
/**
* Determines the current scope (function or block)
* @param {string} statementType one of: "var", "let", "const", "using", or "awaitUsing"
* @returns {Object} The scope associated with statementType
*/
function getCurrentScope(statementType) {
let currentScope;
if (statementType === "var") {
currentScope = functionStack.at(-1);
} else if (statementType === "let") {
currentScope = blockStack.at(-1).let;
} else if (statementType === "const") {
currentScope = blockStack.at(-1).const;
} else if (statementType === "using") {
currentScope = blockStack.at(-1).using;
} else if (statementType === "awaitUsing") {
currentScope = blockStack.at(-1).awaitUsing;
}
return currentScope;
}
/**
* Counts the number of initialized and uninitialized declarations in a list of declarations
* @param {ASTNode[]} declarations List of declarations
* @returns {Object} Counts of 'uninitialized' and 'initialized' declarations
* @private
*/
function countDeclarations(declarations) {
const counts = { uninitialized: 0, initialized: 0 };
for (let i = 0; i < declarations.length; i++) {
if (declarations[i].init === null) {
counts.uninitialized++;
} else {
counts.initialized++;
}
}
return counts;
}
/**
* Determines if there is more than one var statement in the current scope.
* @param {string} statementType one of: "var", "let", "const", "using", or "awaitUsing"
* @param {ASTNode[]} declarations List of declarations
* @returns {boolean} Returns true if it is the first var declaration, false if not.
* @private
*/
function hasOnlyOneStatement(statementType, declarations) {
const declarationCounts = countDeclarations(declarations);
const currentOptions = options[statementType] || {};
const currentScope = getCurrentScope(statementType);
const hasRequires = declarations.some(isRequire);
if (
currentOptions.uninitialized === MODE_ALWAYS &&
currentOptions.initialized === MODE_ALWAYS
) {
if (currentScope.uninitialized || currentScope.initialized) {
if (!hasRequires) {
return false;
}
}
}
if (declarationCounts.uninitialized > 0) {
if (
currentOptions.uninitialized === MODE_ALWAYS &&
currentScope.uninitialized
) {
return false;
}
}
if (declarationCounts.initialized > 0) {
if (
currentOptions.initialized === MODE_ALWAYS &&
currentScope.initialized
) {
if (!hasRequires) {
return false;
}
}
}
if (currentScope.required && hasRequires) {
return false;
}
recordTypes(statementType, declarations, currentScope);
return true;
}
/**
* Fixer to join VariableDeclaration's into a single declaration
* @param {VariableDeclarator[]} declarations The `VariableDeclaration` to join
* @returns {Function} The fixer function
*/
function joinDeclarations(declarations) {
const declaration = declarations[0];
const body = Array.isArray(declaration.parent.parent.body)
? declaration.parent.parent.body
: [];
const currentIndex = body.findIndex(
node => node.range[0] === declaration.parent.range[0],
);
const previousNode = body[currentIndex - 1];
return function* joinDeclarationsFixer(fixer) {
const type = sourceCode.getFirstToken(declaration.parent);
const beforeType = sourceCode.getTokenBefore(type);
if (
previousNode &&
previousNode.kind === declaration.parent.kind
) {
if (beforeType.value === ";") {
yield fixer.replaceText(beforeType, ",");
} else {
yield fixer.insertTextAfter(beforeType, ",");
}
if (declaration.parent.kind === "await using") {
const usingToken = sourceCode.getTokenAfter(type);
yield fixer.remove(usingToken);
}
yield fixer.replaceText(type, "");
}
};
}
/**
* Fixer to split a VariableDeclaration into individual declarations
* @param {VariableDeclaration} declaration The `VariableDeclaration` to split
* @returns {Function|null} The fixer function
*/
function splitDeclarations(declaration) {
const { parent } = declaration;
// don't autofix code such as: if (foo) var x, y;
if (
!isInStatementList(
parent.type === "ExportNamedDeclaration"
? parent
: declaration,
)
) {
return null;
}
return fixer =>
declaration.declarations
.map(declarator => {
const tokenAfterDeclarator =
sourceCode.getTokenAfter(declarator);
if (tokenAfterDeclarator === null) {
return null;
}
const afterComma = sourceCode.getTokenAfter(
tokenAfterDeclarator,
{ includeComments: true },
);
if (tokenAfterDeclarator.value !== ",") {
return null;
}
const exportPlacement =
declaration.parent.type === "ExportNamedDeclaration"
? "export "
: "";
/*
* `var x,y`
* tokenAfterDeclarator ^^ afterComma
*/
if (
afterComma.range[0] ===
tokenAfterDeclarator.range[1]
) {
return fixer.replaceText(
tokenAfterDeclarator,
`; ${exportPlacement}${declaration.kind} `,
);
}
/*
* `var x,
* tokenAfterDeclarator ^
* y`
* ^ afterComma
*/
if (
afterComma.loc.start.line >
tokenAfterDeclarator.loc.end.line ||
afterComma.type === "Line" ||
afterComma.type === "Block"
) {
let lastComment = afterComma;
while (
lastComment.type === "Line" ||
lastComment.type === "Block"
) {
lastComment = sourceCode.getTokenAfter(
lastComment,
{ includeComments: true },
);
}
return fixer.replaceTextRange(
[
tokenAfterDeclarator.range[0],
lastComment.range[0],
],
`;${sourceCode.text.slice(
tokenAfterDeclarator.range[1],
lastComment.range[0],
)}${exportPlacement}${declaration.kind} `,
);
}
return fixer.replaceText(
tokenAfterDeclarator,
`; ${exportPlacement}${declaration.kind}`,
);
})
.filter(x => x);
}
/**
* Checks a given VariableDeclaration node for errors.
* @param {ASTNode} node The VariableDeclaration node to check
* @returns {void}
* @private
*/
function checkVariableDeclaration(node) {
const parent = node.parent;
const type = node.kind;
const key = type === "await using" ? "awaitUsing" : type;
if (!options[key]) {
return;
}
const declarations = node.declarations;
const declarationCounts = countDeclarations(declarations);
const mixedRequires =
declarations.some(isRequire) && !declarations.every(isRequire);
if (options[key].initialized === MODE_ALWAYS) {
if (options.separateRequires && mixedRequires) {
context.report({
node,
messageId: "splitRequires",
});
}
}
// consecutive
const nodeIndex =
(parent.body &&
parent.body.length > 0 &&
parent.body.indexOf(node)) ||
0;
if (nodeIndex > 0) {
const previousNode = parent.body[nodeIndex - 1];
const isPreviousNodeDeclaration =
previousNode.type === "VariableDeclaration";
const declarationsWithPrevious = declarations.concat(
previousNode.declarations || [],
);
if (
isPreviousNodeDeclaration &&
previousNode.kind === type &&
!(
declarationsWithPrevious.some(isRequire) &&
!declarationsWithPrevious.every(isRequire)
)
) {
const previousDeclCounts = countDeclarations(
previousNode.declarations,
);
if (
options[key].initialized === MODE_CONSECUTIVE &&
options[key].uninitialized === MODE_CONSECUTIVE
) {
context.report({
node,
messageId: "combine",
data: {
type,
},
fix: joinDeclarations(declarations),
});
} else if (
options[key].initialized === MODE_CONSECUTIVE &&
declarationCounts.initialized > 0 &&
previousDeclCounts.initialized > 0
) {
context.report({
node,
messageId: "combineInitialized",
data: {
type,
},
fix: joinDeclarations(declarations),
});
} else if (
options[key].uninitialized === MODE_CONSECUTIVE &&
declarationCounts.uninitialized > 0 &&
previousDeclCounts.uninitialized > 0
) {
context.report({
node,
messageId: "combineUninitialized",
data: {
type,
},
fix: joinDeclarations(declarations),
});
}
}
}
// always
if (!hasOnlyOneStatement(key, declarations)) {
if (
options[key].initialized === MODE_ALWAYS &&
options[key].uninitialized === MODE_ALWAYS
) {
context.report({
node,
messageId: "combine",
data: {
type,
},
fix: joinDeclarations(declarations),
});
} else {
if (
options[key].initialized === MODE_ALWAYS &&
declarationCounts.initialized > 0
) {
context.report({
node,
messageId: "combineInitialized",
data: {
type,
},
fix: joinDeclarations(declarations),
});
}
if (
options[key].uninitialized === MODE_ALWAYS &&
declarationCounts.uninitialized > 0
) {
if (
node.parent.left === node &&
(node.parent.type === "ForInStatement" ||
node.parent.type === "ForOfStatement")
) {
return;
}
context.report({
node,
messageId: "combineUninitialized",
data: {
type,
},
fix: joinDeclarations(declarations),
});
}
}
}
// never
if (parent.type !== "ForStatement" || parent.init !== node) {
const totalDeclarations =
declarationCounts.uninitialized +
declarationCounts.initialized;
if (totalDeclarations > 1) {
if (
options[key].initialized === MODE_NEVER &&
options[key].uninitialized === MODE_NEVER
) {
// both initialized and uninitialized
context.report({
node,
messageId: "split",
data: {
type,
},
fix: splitDeclarations(node),
});
} else if (
options[key].initialized === MODE_NEVER &&
declarationCounts.initialized > 0
) {
// initialized
context.report({
node,
messageId: "splitInitialized",
data: {
type,
},
fix: splitDeclarations(node),
});
} else if (
options[key].uninitialized === MODE_NEVER &&
declarationCounts.uninitialized > 0
) {
// uninitialized
context.report({
node,
messageId: "splitUninitialized",
data: {
type,
},
fix: splitDeclarations(node),
});
}
}
}
}
//--------------------------------------------------------------------------
// Public API
//--------------------------------------------------------------------------
return {
Program: startFunction,
FunctionDeclaration: startFunction,
FunctionExpression: startFunction,
ArrowFunctionExpression: startFunction,
StaticBlock: startFunction, // StaticBlock creates a new scope for `var` variables
BlockStatement: startBlock,
ForStatement: startBlock,
ForInStatement: startBlock,
ForOfStatement: startBlock,
SwitchStatement: startBlock,
VariableDeclaration: checkVariableDeclaration,
"ForStatement:exit": endBlock,
"ForOfStatement:exit": endBlock,
"ForInStatement:exit": endBlock,
"SwitchStatement:exit": endBlock,
"BlockStatement:exit": endBlock,
"Program:exit": endFunction,
"FunctionDeclaration:exit": endFunction,
"FunctionExpression:exit": endFunction,
"ArrowFunctionExpression:exit": endFunction,
"StaticBlock:exit": endFunction,
};
},
};