WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABILITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
interface PromiseWithResolvers<T> {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T | PromiseLike<T>) => void;
|
||||
reject: (reason?: any) => void;
|
||||
}
|
||||
|
||||
interface PromiseConstructor {
|
||||
/**
|
||||
* Creates a new Promise and returns it in an object, along with its resolve and reject functions.
|
||||
* @returns An object with the properties `promise`, `resolve`, and `reject`.
|
||||
*
|
||||
* ```ts
|
||||
* const { promise, resolve, reject } = Promise.withResolvers<T>();
|
||||
* ```
|
||||
*/
|
||||
withResolvers<T>(): PromiseWithResolvers<T>;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import * as util from "../core/util.js";
|
||||
const error = () => {
|
||||
const Sizable = {
|
||||
string: { unit: "حرف", verb: "أن يحوي" },
|
||||
file: { unit: "بايت", verb: "أن يحوي" },
|
||||
array: { unit: "عنصر", verb: "أن يحوي" },
|
||||
set: { unit: "عنصر", verb: "أن يحوي" },
|
||||
};
|
||||
function getSizing(origin) {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
const FormatDictionary = {
|
||||
regex: "مدخل",
|
||||
email: "بريد إلكتروني",
|
||||
url: "رابط",
|
||||
emoji: "إيموجي",
|
||||
uuid: "UUID",
|
||||
uuidv4: "UUIDv4",
|
||||
uuidv6: "UUIDv6",
|
||||
nanoid: "nanoid",
|
||||
guid: "GUID",
|
||||
cuid: "cuid",
|
||||
cuid2: "cuid2",
|
||||
ulid: "ULID",
|
||||
xid: "XID",
|
||||
ksuid: "KSUID",
|
||||
datetime: "تاريخ ووقت بمعيار ISO",
|
||||
date: "تاريخ بمعيار ISO",
|
||||
time: "وقت بمعيار ISO",
|
||||
duration: "مدة بمعيار ISO",
|
||||
ipv4: "عنوان IPv4",
|
||||
ipv6: "عنوان IPv6",
|
||||
cidrv4: "مدى عناوين بصيغة IPv4",
|
||||
cidrv6: "مدى عناوين بصيغة IPv6",
|
||||
base64: "نَص بترميز base64-encoded",
|
||||
base64url: "نَص بترميز base64url-encoded",
|
||||
json_string: "نَص على هيئة JSON",
|
||||
e164: "رقم هاتف بمعيار E.164",
|
||||
jwt: "JWT",
|
||||
template_literal: "مدخل",
|
||||
};
|
||||
const TypeDictionary = {
|
||||
nan: "NaN",
|
||||
};
|
||||
return (issue) => {
|
||||
switch (issue.code) {
|
||||
case "invalid_type": {
|
||||
const expected = TypeDictionary[issue.expected] ?? issue.expected;
|
||||
const receivedType = util.parsedType(issue.input);
|
||||
const received = TypeDictionary[receivedType] ?? receivedType;
|
||||
if (/^[A-Z]/.test(issue.expected)) {
|
||||
return `مدخلات غير مقبولة: يفترض إدخال instanceof ${issue.expected}، ولكن تم إدخال ${received}`;
|
||||
}
|
||||
return `مدخلات غير مقبولة: يفترض إدخال ${expected}، ولكن تم إدخال ${received}`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1)
|
||||
return `مدخلات غير مقبولة: يفترض إدخال ${util.stringifyPrimitive(issue.values[0])}`;
|
||||
return `اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${util.joinValues(issue.values, "|")}`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing)
|
||||
return ` أكبر من اللازم: يفترض أن تكون ${issue.origin ?? "القيمة"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "عنصر"}`;
|
||||
return `أكبر من اللازم: يفترض أن تكون ${issue.origin ?? "القيمة"} ${adj} ${issue.maximum.toString()}`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()} ${sizing.unit}`;
|
||||
}
|
||||
return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()}`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue;
|
||||
if (_issue.format === "starts_with")
|
||||
return `نَص غير مقبول: يجب أن يبدأ بـ "${issue.prefix}"`;
|
||||
if (_issue.format === "ends_with")
|
||||
return `نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`;
|
||||
if (_issue.format === "includes")
|
||||
return `نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`;
|
||||
if (_issue.format === "regex")
|
||||
return `نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`;
|
||||
return `${FormatDictionary[_issue.format] ?? issue.format} غير مقبول`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `رقم غير مقبول: يجب أن يكون من مضاعفات ${issue.divisor}`;
|
||||
case "unrecognized_keys":
|
||||
return `معرف${issue.keys.length > 1 ? "ات" : ""} غريب${issue.keys.length > 1 ? "ة" : ""}: ${util.joinValues(issue.keys, "، ")}`;
|
||||
case "invalid_key":
|
||||
return `معرف غير مقبول في ${issue.origin}`;
|
||||
case "invalid_union":
|
||||
return "مدخل غير مقبول";
|
||||
case "invalid_element":
|
||||
return `مدخل غير مقبول في ${issue.origin}`;
|
||||
default:
|
||||
return "مدخل غير مقبول";
|
||||
}
|
||||
};
|
||||
};
|
||||
export default function () {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
import{r}from"./get-pipe-path-_tAJyU_v.mjs";import{globalPreload as A,initialize as B,load as C,resolve as D}from"./esm/index.mjs";import"module";import"node:path";import"./temporary-directory-BDDVQOvU.mjs";import"node:os";import"node:worker_threads";import"./node-features-JeyyvQz6.mjs";import"./register-C4vWVmug.mjs";import"node:crypto";import"node:module";import"./register-C9AniqUt.mjs";import"node:url";import"node:fs";import"fs";import"os";import"path";import"./index-DQtFPMc2.mjs";import"esbuild";import"./client-D_mPDF5S.mjs";import"node:net";import"node:util";import"./index-gbaejti9.mjs";import"node:fs/promises";import"./require-CywAB2e6.mjs";r("./cjs/index.cjs");export{A as globalPreload,B as initialize,C as load,D as resolve};
|
||||
@@ -0,0 +1,529 @@
|
||||
/// <reference path="../node/node.d.ts" preserve="true" />
|
||||
import { CompletionItemKind } from "#enums/completionItemKind";
|
||||
import { DiagnosticCategory } from "#enums/diagnosticCategory";
|
||||
import { ElementFlags } from "#enums/elementFlags";
|
||||
import { ModuleKind } from "#enums/moduleKind";
|
||||
import { NodeBuilderFlags } from "#enums/nodeBuilderFlags";
|
||||
import { ObjectFlags } from "#enums/objectFlags";
|
||||
import { SignatureFlags } from "#enums/signatureFlags";
|
||||
import { SignatureKind } from "#enums/signatureKind";
|
||||
import { SymbolFlags } from "#enums/symbolFlags";
|
||||
import { TypeFlags } from "#enums/typeFlags";
|
||||
import { TypePredicateKind } from "#enums/typePredicateKind";
|
||||
import { type __String, type Expression, type Identifier, ModifierFlags, type Node, type Path, type SourceFile, type SyntaxKind, type TypeNode } from "../../ast/index.ts";
|
||||
import type { APIOptions, LSPConnectionOptions } from "../options.ts";
|
||||
import type { CompilerOptions, ConfigResponse, DocumentIdentifier, DocumentPosition, LSPUpdateSnapshotParams, ProjectResponse, SignatureResponse, SourceFileMetadata, SymbolResponse, TypeResponse, UpdateSnapshotParams, UpdateSnapshotResponse } from "../proto.ts";
|
||||
import { SourceFileCache } from "../sourceFileCache.ts";
|
||||
import type { RequestTiming, TimingAccumulators, TimingInfo } from "../timing.ts";
|
||||
import { Client, type ClientSocketOptions, type ClientSpawnOptions } from "./client.ts";
|
||||
import type { AssertsIdentifierTypePredicate, AssertsThisTypePredicate, BigIntLiteralType, BooleanLiteralType, CompletionEntry, CompletionInfo, CompletionOptions, ConditionalType, Diagnostic, FreshableType, IdentifierTypePredicate, IndexedAccessType, IndexInfo, IndexType, InterfaceType, IntersectionType, IntrinsicType, JSDocTagInfo, LiteralType, NumberLiteralType, ObjectType, StringLiteralType, StringMappingType, SubstitutionType, TemplateLiteralType, ThisTypePredicate, TupleType, Type, TypeParameter, TypePredicate, TypePredicateBase, TypeReference, UnionOrIntersectionType, UnionType } from "./types.ts";
|
||||
export { documentURIToFileName, fileNameToDocumentURI } from "../path.ts";
|
||||
export { CompletionItemKind, DiagnosticCategory, ElementFlags, ModifierFlags, ModuleKind, NodeBuilderFlags, ObjectFlags, SignatureFlags, SignatureKind, SymbolFlags, TypeFlags, TypePredicateKind };
|
||||
export type { APIOptions, AssertsIdentifierTypePredicate, AssertsThisTypePredicate, BigIntLiteralType, BooleanLiteralType, ClientSocketOptions, ClientSpawnOptions, CompilerOptions, CompletionEntry, CompletionInfo, CompletionOptions, ConditionalType, Diagnostic, DocumentIdentifier, DocumentPosition, FreshableType, IdentifierTypePredicate, IndexedAccessType, IndexInfo, IndexType, InterfaceType, IntersectionType, IntrinsicType, JSDocTagInfo, LiteralType, LSPConnectionOptions, NumberLiteralType, ObjectType, RequestTiming, SourceFileMetadata, StringLiteralType, StringMappingType, SubstitutionType, TemplateLiteralType, ThisTypePredicate, TimingAccumulators, TimingInfo, TupleType, Type, TypeParameter, TypePredicate, TypePredicateBase, TypeReference, UnionOrIntersectionType, UnionType };
|
||||
export declare class API<FromLSP extends boolean = false> {
|
||||
private client;
|
||||
private sourceFileCache;
|
||||
private toPath;
|
||||
private initialized;
|
||||
private activeSnapshots;
|
||||
private latestSnapshot;
|
||||
readonly internal: InternalAPI;
|
||||
constructor(options?: APIOptions | LSPConnectionOptions);
|
||||
/**
|
||||
* Create an API instance from an existing LSP connection's API session.
|
||||
* Use this when connecting to an API pipe provided by an LSP server via custom/initializeAPISession.
|
||||
*/
|
||||
static fromLSPConnection(options: LSPConnectionOptions): API<true>;
|
||||
private ensureInitialized;
|
||||
parseConfigFile(file: DocumentIdentifier): ConfigResponse;
|
||||
updateSnapshot(params?: FromLSP extends true ? LSPUpdateSnapshotParams : UpdateSnapshotParams): Snapshot;
|
||||
close(): void;
|
||||
clearSourceFileCache(): void;
|
||||
/**
|
||||
* Returns a snapshot of collected timing information for requests made
|
||||
* through this API instance: client-measured round-trip latency and bytes
|
||||
* transferred, folded together with the server's own per-request processing
|
||||
* time and an estimated transport overhead (round-trip minus server time).
|
||||
*
|
||||
* Fetching the snapshot issues a lightweight request to the server to
|
||||
* retrieve its timing collection. Collection must be enabled via the
|
||||
* `collectTiming` option; when it is not, the returned snapshot has
|
||||
* `enabled: false` and zeroed totals.
|
||||
*/
|
||||
getTimingInfo(): TimingInfo;
|
||||
/** Clears all accumulated timing totals and recent-request history, on both the client and the server. */
|
||||
resetTimingInfo(): void;
|
||||
}
|
||||
export declare class InternalAPI {
|
||||
private client;
|
||||
private ensureInitialized;
|
||||
/** @internal */
|
||||
constructor(client: Client, ensureInitialized: () => void);
|
||||
startCPUProfile(dir: string): void;
|
||||
stopCPUProfile(): string;
|
||||
saveHeapProfile(dir: string): string;
|
||||
}
|
||||
export declare class Snapshot {
|
||||
readonly id: number;
|
||||
private projectMap;
|
||||
private toPath;
|
||||
private client;
|
||||
private disposed;
|
||||
private onDispose;
|
||||
private snapshotRegistry;
|
||||
constructor(data: UpdateSnapshotResponse, client: Client, sourceFileCache: SourceFileCache, toPath: (fileName: string) => Path, onDispose: () => void);
|
||||
getProjects(): readonly Project[];
|
||||
getProject(configFileName: string): Project | undefined;
|
||||
getDefaultProjectForFile(file: DocumentIdentifier): Project | undefined;
|
||||
[globalThis.Symbol.dispose](): void;
|
||||
dispose(): void;
|
||||
isDisposed(): boolean;
|
||||
private ensureNotDisposed;
|
||||
}
|
||||
declare class SnapshotObjectRegistry {
|
||||
private readonly symbols;
|
||||
private readonly client;
|
||||
private readonly snapshotId;
|
||||
private readonly resolveProject;
|
||||
constructor(client: Client, snapshotId: number, resolveProject: (projectId: Path) => Project | undefined);
|
||||
/** Resolve a project id (a config file path) to its Project within this snapshot. */
|
||||
getProject(projectId: Path): Project | undefined;
|
||||
getOrCreateSymbol(data: SymbolResponse): Symbol;
|
||||
getSymbol(id: number): Symbol | undefined;
|
||||
clear(): void;
|
||||
fetchSymbol(source: Symbol | Signature | Type, method: string, handle: number | undefined, projectId?: Path): Symbol;
|
||||
fetchSymbols(source: Symbol | Signature | Type, method: string, handles?: readonly number[], projectId?: Path): readonly Symbol[];
|
||||
}
|
||||
declare class ProjectObjectRegistry {
|
||||
private client;
|
||||
private snapshotId;
|
||||
private project;
|
||||
private snapshotRegistry;
|
||||
private types;
|
||||
private signatures;
|
||||
constructor(client: Client, snapshotId: number, project: Project, snapshotRegistry: SnapshotObjectRegistry);
|
||||
getOrCreateSymbol(data: SymbolResponse): Symbol;
|
||||
getSymbol(id: number): Symbol | undefined;
|
||||
getOrCreateType(data: TypeResponse): TypeObject;
|
||||
getType(id: number): TypeObject | undefined;
|
||||
getOrCreateSignature(data: SignatureResponse): Signature;
|
||||
getSignature(id: number): Signature | undefined;
|
||||
clear(): void;
|
||||
fetchType<T extends Type>(source: Symbol | Signature | Type, method: string, handle: number | false | undefined): T;
|
||||
fetchSymbol(source: Symbol | Signature | Type, method: string, handle: number | undefined): Symbol;
|
||||
fetchSignature(source: Symbol | Signature | Type, method: string, handle: number | undefined): Signature;
|
||||
fetchTypes(source: Symbol | Signature | Type, method: string, handles?: readonly number[]): readonly Type[];
|
||||
fetchSymbols(source: Symbol | Signature | Type, method: string, handles?: readonly number[]): readonly Symbol[];
|
||||
fetchBaseTypes(source: Type): readonly Type[];
|
||||
}
|
||||
export declare class Project {
|
||||
readonly id: Path;
|
||||
readonly configFileName: string;
|
||||
readonly compilerOptions: CompilerOptions;
|
||||
readonly rootFiles: readonly string[];
|
||||
readonly program: Program;
|
||||
readonly checker: Checker;
|
||||
readonly emitter: Emitter;
|
||||
private client;
|
||||
constructor(data: ProjectResponse, snapshotId: number, client: Client, sourceFileCache: SourceFileCache, toPath: (fileName: string) => Path, snapshotRegistry: SnapshotObjectRegistry);
|
||||
dispose(): void;
|
||||
}
|
||||
export declare class Program {
|
||||
private snapshotId;
|
||||
private project;
|
||||
private client;
|
||||
private sourceFileCache;
|
||||
private toPath;
|
||||
private decoder;
|
||||
private sourceFileMetadataCache;
|
||||
constructor(snapshotId: number, project: Project, client: Client, sourceFileCache: SourceFileCache, toPath: (fileName: string) => Path);
|
||||
getCompilerOptions(): CompilerOptions;
|
||||
getSourceFile(file: DocumentIdentifier): SourceFile | undefined;
|
||||
getSourceFileNames(): readonly string[];
|
||||
/**
|
||||
* Returns program-stored metadata for the given source file, or `undefined` if the file
|
||||
* is not part of the program. Metadata is fetched lazily per file and cached on this
|
||||
* `Program` instance.
|
||||
*/
|
||||
getSourceFileMetadata(fileName: string): SourceFileMetadata | undefined;
|
||||
/**
|
||||
* Returns program-stored metadata for the source file at the given path, or `undefined`
|
||||
* if the file is not part of the program. Like {@link getSourceFileMetadata}, but skips
|
||||
* the file name to path conversion. Metadata is fetched lazily per file and cached on
|
||||
* this `Program` instance.
|
||||
*/
|
||||
getSourceFileMetadataByPath(path: Path): SourceFileMetadata | undefined;
|
||||
private fetchSourceFileMetadata;
|
||||
/**
|
||||
* Returns whether the given source file was loaded as part of an external library
|
||||
* (e.g. a dependency resolved from `node_modules`). The underlying program metadata is
|
||||
* fetched lazily per file and cached on this `Program` instance.
|
||||
*/
|
||||
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
|
||||
/**
|
||||
* Returns whether the given source file is a default library file (e.g. `lib.d.ts`).
|
||||
* The underlying program metadata is fetched lazily per file and cached on this
|
||||
* `Program` instance.
|
||||
*/
|
||||
isSourceFileDefaultLibrary(file: SourceFile): boolean;
|
||||
/**
|
||||
* Get syntactic (parse) diagnostics for a specific file or all files.
|
||||
* @param file - Optional file to get diagnostics for. If omitted, returns diagnostics for all files.
|
||||
*/
|
||||
getSyntacticDiagnostics(file?: DocumentIdentifier): readonly Diagnostic[];
|
||||
/**
|
||||
* Get binder diagnostics for a specific file or all files.
|
||||
* @param file - Optional file to get diagnostics for. If omitted, returns diagnostics for all files.
|
||||
*/
|
||||
getBindDiagnostics(file?: DocumentIdentifier): readonly Diagnostic[];
|
||||
/**
|
||||
* Get semantic (type-check) diagnostics for a specific file or all files.
|
||||
* @param file - Optional file to get diagnostics for. If omitted, returns diagnostics for all files.
|
||||
*/
|
||||
getSemanticDiagnostics(file?: DocumentIdentifier): readonly Diagnostic[];
|
||||
/**
|
||||
* Get suggestion diagnostics for a specific file or all files.
|
||||
* @param file - Optional file to get diagnostics for. If omitted, returns diagnostics for all files.
|
||||
*/
|
||||
getSuggestionDiagnostics(file?: DocumentIdentifier): readonly Diagnostic[];
|
||||
/**
|
||||
* Get declaration emit diagnostics for a specific file or all files.
|
||||
* @param file - Optional file to get diagnostics for. If omitted, returns diagnostics for all files.
|
||||
*/
|
||||
getDeclarationDiagnostics(file?: DocumentIdentifier): readonly Diagnostic[];
|
||||
/**
|
||||
* Get program-wide diagnostics for the project, including compiler options diagnostics.
|
||||
*/
|
||||
getProgramDiagnostics(): readonly Diagnostic[];
|
||||
/**
|
||||
* Get global (non-file-specific) semantic diagnostics for the project.
|
||||
*/
|
||||
getGlobalDiagnostics(): readonly Diagnostic[];
|
||||
/**
|
||||
* Get config file parsing diagnostics for the project.
|
||||
*/
|
||||
getConfigFileParsingDiagnostics(): readonly Diagnostic[];
|
||||
}
|
||||
export declare class Checker {
|
||||
private snapshotId;
|
||||
private project;
|
||||
private client;
|
||||
private objectRegistry;
|
||||
private wellKnownSymbols;
|
||||
constructor(snapshotId: number, project: Project, client: Client, objectRegistry: ProjectObjectRegistry);
|
||||
dispose(): void;
|
||||
getSymbolAtLocation(node: Node): Symbol | undefined;
|
||||
getSymbolAtLocation(nodes: readonly Node[]): (Symbol | undefined)[];
|
||||
getSymbolAtPosition(file: DocumentIdentifier, position: number): Symbol | undefined;
|
||||
getSymbolAtPosition(file: DocumentIdentifier, positions: readonly number[]): (Symbol | undefined)[];
|
||||
getTypeOfSymbol(symbol: Symbol): Type | undefined;
|
||||
getTypeOfSymbol(symbols: readonly Symbol[]): (Type | undefined)[];
|
||||
/**
|
||||
* Get the declared type of a symbol. Always returns a type; for symbols whose
|
||||
* declared type cannot be determined the checker yields the error type (use
|
||||
* {@link Type.isErrorType} to detect it).
|
||||
*/
|
||||
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
|
||||
getReferencesToSymbolInFile(file: DocumentIdentifier, symbol: Symbol): NodeHandle[];
|
||||
getReferencedSymbolsForNode(node: Node, position: number): ReferencedSymbolEntry[];
|
||||
getSignatureUsage(signatureDecl: Node): SignatureUsage[];
|
||||
getCompletionsAtPosition(document: string, position: number, options?: CompletionOptions): CompletionInfo | undefined;
|
||||
getTypeAtLocation(node: Node): Type | undefined;
|
||||
getTypeAtLocation(nodes: readonly Node[]): (Type | undefined)[];
|
||||
getSignaturesOfType(type: Type, kind: SignatureKind): readonly Signature[];
|
||||
getResolvedSignature(node: Node): Signature | undefined;
|
||||
getTypeAtPosition(file: DocumentIdentifier, position: number): Type | undefined;
|
||||
getTypeAtPosition(file: DocumentIdentifier, positions: readonly number[]): (Type | undefined)[];
|
||||
resolveName(name: string, meaning: SymbolFlags, location?: Node | DocumentPosition, excludeGlobals?: boolean): Symbol | undefined;
|
||||
getResolvedSymbol(node: Identifier): Symbol | undefined;
|
||||
getContextualType(node: Expression): Type | undefined;
|
||||
getBaseTypeOfLiteralType(type: Type): Type | undefined;
|
||||
getNonNullableType(type: Type): Type | undefined;
|
||||
getTypeFromTypeNode(node: TypeNode): Type | undefined;
|
||||
getWidenedType(type: Type): Type | undefined;
|
||||
getParameterType(signature: Signature, index: number): Type | undefined;
|
||||
isArrayLikeType(type: Type): boolean;
|
||||
isTypeAssignableTo(source: Type, target: Type): boolean;
|
||||
getShorthandAssignmentValueSymbol(node: Node): Symbol | undefined;
|
||||
/**
|
||||
* Get the type of a symbol as narrowed at a specific location. Always returns
|
||||
* a type; for symbols whose type cannot be determined the checker yields the
|
||||
* error type (use {@link Type.isErrorType} to detect it).
|
||||
*/
|
||||
getTypeOfSymbolAtLocation(symbol: Symbol, location: Node): Type;
|
||||
private getIntrinsicType;
|
||||
getAnyType(): Type;
|
||||
getStringType(): Type;
|
||||
getNumberType(): Type;
|
||||
getBooleanType(): Type;
|
||||
getVoidType(): Type;
|
||||
getUndefinedType(): Type;
|
||||
getNullType(): Type;
|
||||
getNeverType(): Type;
|
||||
getUnknownType(): Type;
|
||||
getBigIntType(): Type;
|
||||
getESSymbolType(): Type;
|
||||
typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: number): TypeNode | undefined;
|
||||
signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Node | undefined;
|
||||
typeToString(type: Type, enclosingDeclaration?: Node, flags?: number): string;
|
||||
isContextSensitive(node: Node): boolean;
|
||||
isArrayType(type: Type): boolean;
|
||||
isTupleType(type: Type): boolean;
|
||||
getReturnTypeOfSignature(signature: Signature): Type | undefined;
|
||||
getRestTypeOfSignature(signature: Signature): Type | undefined;
|
||||
getTypePredicateOfSignature(signature: Signature): TypePredicate | undefined;
|
||||
/**
|
||||
* Get the base types of a class or interface type. A type with no base types
|
||||
* yields an empty array.
|
||||
*/
|
||||
getBaseTypes(type: InterfaceType): readonly Type[];
|
||||
getApparentType(type: Type): Type | undefined;
|
||||
getPropertiesOfType(type: Type): readonly Symbol[];
|
||||
getIndexInfosOfType(type: Type): readonly IndexInfo[];
|
||||
/**
|
||||
* Get the constraint of a type parameter (the `T` in `<U extends T>`), or
|
||||
* undefined if it has none.
|
||||
*/
|
||||
getConstraintOfTypeParameter(type: TypeParameter): Type | undefined;
|
||||
getBaseConstraintOfType(type: Type): Type | undefined;
|
||||
getPropertyOfType(type: Type, name: string): Symbol | undefined;
|
||||
getConstantValue(node: Node): string | number | undefined;
|
||||
getSignatureFromDeclaration(node: Node): Signature | undefined;
|
||||
getExportSpecifierLocalTargetSymbol(node: Node): Symbol | undefined;
|
||||
/**
|
||||
* Follow all aliases to get the original symbol. Always returns a symbol; for
|
||||
* an unresolved alias the checker yields the unknown symbol (use
|
||||
* {@link Checker.isUnknownSymbol} to detect it).
|
||||
*/
|
||||
getAliasedSymbol(symbol: Symbol): Symbol;
|
||||
getImmediateAliasedSymbol(symbol: Symbol): Symbol | undefined;
|
||||
/**
|
||||
* Fetch (once, then cache) the handle ids of the per-checker singleton
|
||||
* symbols (unknown, undefined, arguments). These ids are stable for the life
|
||||
* of the project's checker, so identity checks against them are local after
|
||||
* the first call.
|
||||
*/
|
||||
private getWellKnownSymbols;
|
||||
/**
|
||||
* Returns `true` if the symbol is the checker's "unknown" symbol (e.g. the
|
||||
* result of {@link Checker.getAliasedSymbol} on an unresolved alias).
|
||||
*/
|
||||
isUnknownSymbol(symbol: Symbol): boolean;
|
||||
/**
|
||||
* Returns `true` if the symbol is the checker's "undefined" symbol.
|
||||
*/
|
||||
isUndefinedSymbol(symbol: Symbol): boolean;
|
||||
/**
|
||||
* Returns `true` if the symbol is the checker's "arguments" symbol.
|
||||
*/
|
||||
isArgumentsSymbol(symbol: Symbol): boolean;
|
||||
getExportsOfModule(symbol: Symbol): readonly Symbol[];
|
||||
getMemberInModuleExports(symbol: Symbol, name: string): Symbol | undefined;
|
||||
getJsDocTagsOfSymbol(symbol: Symbol): readonly JSDocTagInfo[];
|
||||
getDocumentationCommentOfSymbol(symbol: Symbol): string;
|
||||
/**
|
||||
* Get the type arguments of a type reference (e.g. the `string` in `Array<string>`).
|
||||
*/
|
||||
getTypeArguments(type: TypeReference): readonly Type[];
|
||||
}
|
||||
export interface PrintNodeOptions {
|
||||
preserveSourceNewlines?: boolean | undefined;
|
||||
neverAsciiEscape?: boolean | undefined;
|
||||
terminateUnterminatedLiterals?: boolean | undefined;
|
||||
}
|
||||
export declare class Emitter {
|
||||
private client;
|
||||
constructor(client: Client);
|
||||
printNode(node: Node, options?: PrintNodeOptions): string;
|
||||
}
|
||||
export declare class NodeHandle {
|
||||
/**
|
||||
* The project this handle was produced in, used as the default for {@link resolve}.
|
||||
* Node handles are only meaningful within a project's program, so the producing project
|
||||
* is remembered so callers don't have to pass it explicitly.
|
||||
*/
|
||||
private readonly canonicalProject;
|
||||
readonly index: number;
|
||||
readonly kind: SyntaxKind;
|
||||
readonly path: Path;
|
||||
constructor(handle: string, canonicalProject: Project);
|
||||
/**
|
||||
* Resolve this handle to the actual AST node by fetching the source file from a project
|
||||
* and looking up the node by index. If no project is passed, the project that produced
|
||||
* the handle is used.
|
||||
*/
|
||||
resolve(project?: Project): Node | undefined;
|
||||
}
|
||||
/** A symbol definition paired with all of its reference nodes. */
|
||||
export interface ReferencedSymbolEntry {
|
||||
/** The node handle for the symbol's definition. */
|
||||
definition: NodeHandle;
|
||||
/** The resolved symbol for the definition, if available. */
|
||||
symbol?: Symbol | undefined;
|
||||
/** The node handles for each reference to the symbol. */
|
||||
references: NodeHandle[];
|
||||
}
|
||||
/** A single usage of a signature, pairing the reference name with its call expression (if any). */
|
||||
export interface SignatureUsage {
|
||||
/** The node handle for the name reference. */
|
||||
name: NodeHandle;
|
||||
/** The node handle for the call expression, if the reference is invoked. */
|
||||
call?: NodeHandle | undefined;
|
||||
}
|
||||
export declare class Symbol {
|
||||
private objectRegistry;
|
||||
/**
|
||||
* The project this symbol was first observed in, used as the default project for
|
||||
* lookups that need a project context (members/exports/parent). Symbols are shared
|
||||
* snapshot-wide, so these lookups can otherwise be ambiguous about which project to use.
|
||||
*/
|
||||
private readonly canonicalProject;
|
||||
readonly id: number;
|
||||
/** The escaped (`__String`) name, used as the key in member/export tables. */
|
||||
readonly escapedName: __String;
|
||||
/** The display name (escaped underscores removed). */
|
||||
readonly name: string;
|
||||
readonly flags: SymbolFlags;
|
||||
readonly checkFlags: number;
|
||||
readonly declarations: readonly NodeHandle[];
|
||||
readonly valueDeclaration: NodeHandle | undefined;
|
||||
private readonly parent;
|
||||
private readonly exportSymbol;
|
||||
private membersCache;
|
||||
private exportsCache;
|
||||
constructor(data: SymbolResponse, objectRegistry: SnapshotObjectRegistry);
|
||||
getParent(): Symbol | undefined;
|
||||
/**
|
||||
* Get this symbol's members keyed by escaped name. The result is cached on
|
||||
* the symbol, so repeated calls do not round-trip to the server.
|
||||
*/
|
||||
getMembers(): ReadonlyMap<__String, Symbol>;
|
||||
/**
|
||||
* Get this symbol's exports keyed by escaped name. The result is cached on
|
||||
* the symbol, so repeated calls do not round-trip to the server.
|
||||
*/
|
||||
getExports(): ReadonlyMap<__String, Symbol>;
|
||||
private fetchSymbolTable;
|
||||
getExportSymbol(): Symbol;
|
||||
getJsDocTags(checker: Checker): readonly JSDocTagInfo[];
|
||||
getDocumentationComment(checker: Checker): string;
|
||||
}
|
||||
declare class TypeObject implements Type {
|
||||
private objectRegistry;
|
||||
readonly id: number;
|
||||
readonly flags: TypeFlags;
|
||||
readonly objectFlags: ObjectFlags;
|
||||
readonly symbol: number;
|
||||
readonly value: string | number | boolean | bigint;
|
||||
readonly intrinsicName: string;
|
||||
readonly isThisType: boolean;
|
||||
readonly freshType: number;
|
||||
readonly regularType: number;
|
||||
readonly target: number;
|
||||
readonly typeParameters: readonly number[];
|
||||
readonly outerTypeParameters: readonly number[];
|
||||
readonly localTypeParameters: readonly number[];
|
||||
readonly aliasTypeArguments: readonly number[];
|
||||
readonly aliasSymbol: number;
|
||||
readonly elementFlags: readonly ElementFlags[];
|
||||
readonly fixedLength: number;
|
||||
readonly readonly: boolean;
|
||||
readonly texts: readonly string[];
|
||||
readonly objectType: number;
|
||||
readonly indexType: number;
|
||||
readonly checkType: number;
|
||||
readonly extendsType: number;
|
||||
readonly baseType: number;
|
||||
readonly substConstraint: number;
|
||||
private trueType;
|
||||
private falseType;
|
||||
constructor(data: TypeResponse, objectRegistry: ProjectObjectRegistry);
|
||||
getSymbol(): Symbol | undefined;
|
||||
getAliasSymbol(): Symbol | undefined;
|
||||
getTarget(): Type;
|
||||
getFreshType(): FreshableType | undefined;
|
||||
getRegularType(): FreshableType | undefined;
|
||||
getTypes(): readonly Type[] | undefined;
|
||||
getTypeParameters(): readonly TypeParameter[];
|
||||
getOuterTypeParameters(): readonly TypeParameter[];
|
||||
getLocalTypeParameters(): readonly TypeParameter[];
|
||||
getAliasTypeArguments(): readonly Type[];
|
||||
getObjectType(): Type;
|
||||
getIndexType(): Type;
|
||||
getCheckType(): Type;
|
||||
getExtendsType(): Type;
|
||||
getBaseType(): Type;
|
||||
getConstraint(): Type;
|
||||
getTrueType(): Type;
|
||||
getFalseType(): Type;
|
||||
/**
|
||||
* Get the base types of this type. Returns `undefined` for any type that is
|
||||
* not a class or interface.
|
||||
*/
|
||||
getBaseTypes(): readonly Type[] | undefined;
|
||||
isClassOrInterface(): this is InterfaceType;
|
||||
isUnionType(): this is UnionType;
|
||||
isIntersectionType(): this is IntersectionType;
|
||||
isObjectType(): this is ObjectType;
|
||||
isIntrinsicType(): this is IntrinsicType;
|
||||
isErrorType(): boolean;
|
||||
isLiteralType(): this is LiteralType;
|
||||
isStringLiteralType(): this is StringLiteralType;
|
||||
isNumberLiteralType(): this is NumberLiteralType;
|
||||
isBigIntLiteralType(): this is BigIntLiteralType;
|
||||
isBooleanLiteralType(): this is BooleanLiteralType;
|
||||
isTypeReference(): this is TypeReference;
|
||||
isTupleType(): this is TupleType;
|
||||
isIndexType(): this is IndexType;
|
||||
isIndexedAccessType(): this is IndexedAccessType;
|
||||
isConditionalType(): this is ConditionalType;
|
||||
isSubstitutionType(): this is SubstitutionType;
|
||||
isTemplateLiteralType(): this is TemplateLiteralType;
|
||||
isStringMappingType(): this is StringMappingType;
|
||||
isTypeParameter(): this is TypeParameter;
|
||||
}
|
||||
export declare function isUnionType(type: Type): type is UnionType;
|
||||
export declare function isIntersectionType(type: Type): type is IntersectionType;
|
||||
export declare function isObjectType(type: Type): type is ObjectType;
|
||||
export declare function isClassOrInterfaceType(type: Type): type is InterfaceType;
|
||||
export declare function isIntrinsicType(type: Type): type is IntrinsicType;
|
||||
/**
|
||||
* Whether this is the error type — the placeholder the checker produces when a
|
||||
* type cannot be determined (e.g. an unresolved reference). It is an intrinsic
|
||||
* type named `"error"` (this covers both the singleton error type and the
|
||||
* per-alias error types manufactured for unresolved type alias references).
|
||||
*/
|
||||
export declare function isErrorType(type: Type): boolean;
|
||||
export declare function isLiteralType(type: Type): type is LiteralType;
|
||||
export declare function isStringLiteralType(type: Type): type is StringLiteralType;
|
||||
export declare function isNumberLiteralType(type: Type): type is NumberLiteralType;
|
||||
export declare function isBigIntLiteralType(type: Type): type is BigIntLiteralType;
|
||||
export declare function isBooleanLiteralType(type: Type): type is BooleanLiteralType;
|
||||
export declare function isTypeReference(type: Type): type is TypeReference;
|
||||
export declare function isTupleType(type: Type): type is TupleType;
|
||||
export declare function isIndexType(type: Type): type is IndexType;
|
||||
export declare function isIndexedAccessType(type: Type): type is IndexedAccessType;
|
||||
export declare function isConditionalType(type: Type): type is ConditionalType;
|
||||
export declare function isSubstitutionType(type: Type): type is SubstitutionType;
|
||||
export declare function isTemplateLiteralType(type: Type): type is TemplateLiteralType;
|
||||
export declare function isStringMappingType(type: Type): type is StringMappingType;
|
||||
export declare function isTypeParameter(type: Type): type is TypeParameter;
|
||||
export declare class Signature {
|
||||
private flags;
|
||||
private objectRegistry;
|
||||
readonly id: number;
|
||||
readonly declaration?: NodeHandle | undefined;
|
||||
readonly typeParameters?: readonly number[] | undefined;
|
||||
readonly parameters: readonly number[];
|
||||
readonly thisParameter?: number | undefined;
|
||||
readonly target?: number | undefined;
|
||||
constructor(data: SignatureResponse, project: Project, objectRegistry: ProjectObjectRegistry);
|
||||
getTypeParameters(): readonly TypeParameter[];
|
||||
getParameters(): readonly Symbol[];
|
||||
getThisParameter(): Symbol | undefined;
|
||||
getTarget(): Signature | undefined;
|
||||
get hasRestParameter(): boolean;
|
||||
get isConstruct(): boolean;
|
||||
get isAbstract(): boolean;
|
||||
}
|
||||
//# sourceMappingURL=api.d.ts.map
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* @fileoverview Rule for disallowing require() outside of the top-level module context
|
||||
* @author Jamund Ferguson
|
||||
* @deprecated in ESLint v7.0.0
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
const ACCEPTABLE_PARENTS = new Set([
|
||||
"AssignmentExpression",
|
||||
"VariableDeclarator",
|
||||
"MemberExpression",
|
||||
"ExpressionStatement",
|
||||
"CallExpression",
|
||||
"ConditionalExpression",
|
||||
"Program",
|
||||
"VariableDeclaration",
|
||||
"ChainExpression",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Finds the eslint-scope reference in the given scope.
|
||||
* @param {Object} scope The scope to search.
|
||||
* @param {ASTNode} node The identifier node.
|
||||
* @returns {Reference|null} Returns the found reference or null if none were found.
|
||||
*/
|
||||
function findReference(scope, node) {
|
||||
const references = scope.references.filter(
|
||||
reference =>
|
||||
reference.identifier.range[0] === node.range[0] &&
|
||||
reference.identifier.range[1] === node.range[1],
|
||||
);
|
||||
|
||||
if (references.length === 1) {
|
||||
return references[0];
|
||||
}
|
||||
|
||||
/* c8 ignore next */
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given identifier node is shadowed in the given scope.
|
||||
* @param {Object} scope The current scope.
|
||||
* @param {ASTNode} node The identifier node to check.
|
||||
* @returns {boolean} Whether or not the name is shadowed.
|
||||
*/
|
||||
function isShadowed(scope, node) {
|
||||
const reference = findReference(scope, node);
|
||||
|
||||
return (
|
||||
reference && reference.resolved && reference.resolved.defs.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
deprecated: {
|
||||
message: "Node.js rules were moved out of ESLint core.",
|
||||
url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules",
|
||||
deprecatedSince: "7.0.0",
|
||||
availableUntil: "11.0.0",
|
||||
replacedBy: [
|
||||
{
|
||||
message:
|
||||
"eslint-plugin-n now maintains deprecated Node.js-related rules.",
|
||||
plugin: {
|
||||
name: "eslint-plugin-n",
|
||||
url: "https://github.com/eslint-community/eslint-plugin-n",
|
||||
},
|
||||
rule: {
|
||||
name: "global-require",
|
||||
url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/global-require.md",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
type: "suggestion",
|
||||
|
||||
docs: {
|
||||
description:
|
||||
"Require `require()` calls to be placed at top-level module scope",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/global-require",
|
||||
},
|
||||
|
||||
schema: [],
|
||||
messages: {
|
||||
unexpected: "Unexpected require().",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
return {
|
||||
CallExpression(node) {
|
||||
const currentScope = sourceCode.getScope(node);
|
||||
|
||||
if (
|
||||
node.callee.name === "require" &&
|
||||
!isShadowed(currentScope, node.callee)
|
||||
) {
|
||||
const isGoodRequire = sourceCode
|
||||
.getAncestors(node)
|
||||
.every(parent => ACCEPTABLE_PARENTS.has(parent.type));
|
||||
|
||||
if (!isGoodRequire) {
|
||||
context.report({ node, messageId: "unexpected" });
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,173 @@
|
||||
'use strict'
|
||||
|
||||
module.exports = parseFactoryOptions
|
||||
|
||||
const {
|
||||
LEVEL_NAMES
|
||||
} = require('../constants')
|
||||
const colors = require('../colors')
|
||||
const handleCustomLevelsOpts = require('./handle-custom-levels-opts')
|
||||
const handleCustomLevelsNamesOpts = require('./handle-custom-levels-names-opts')
|
||||
const handleLevelLabelData = require('./get-level-label-data')
|
||||
|
||||
/**
|
||||
* A `PrettyContext` is an object to be used by the various functions that
|
||||
* process log data. It is derived from the provided {@link PinoPrettyOptions}.
|
||||
* It may be used as a `this` context.
|
||||
*
|
||||
* @typedef {object} PrettyContext
|
||||
* @property {string} EOL The escape sequence chosen as the line terminator.
|
||||
* @property {string} IDENT The string to use as the indentation sequence.
|
||||
* @property {ColorizerFunc} colorizer A configured colorizer function.
|
||||
* @property {Array[Array<number, string>]} customColors A set of custom color
|
||||
* names associated with level numbers.
|
||||
* @property {object} customLevelNames A hash of level numbers to level names,
|
||||
* e.g. `{ 30: "info" }`.
|
||||
* @property {object} customLevels A hash of level names to level numbers,
|
||||
* e.g. `{ info: 30 }`.
|
||||
* @property {CustomPrettifiers} customPrettifiers A hash of custom prettifier
|
||||
* functions.
|
||||
* @property {object} customProperties Comprised of `customLevels` and
|
||||
* `customLevelNames` if such options are provided.
|
||||
* @property {string[]} errorLikeObjectKeys The key names in the log data that
|
||||
* should be considered as holding error objects.
|
||||
* @property {string[]} errorProps A list of error object keys that should be
|
||||
* included in the output.
|
||||
* @property {function} getLevelLabelData Pass a numeric level to return [levelLabelString,levelNum]
|
||||
* @property {boolean} hideObject Indicates the prettifier should omit objects
|
||||
* in the output.
|
||||
* @property {string[]} ignoreKeys Set of log data keys to omit.
|
||||
* @property {string[]} includeKeys Opposite of `ignoreKeys`.
|
||||
* @property {boolean} levelFirst Indicates the level should be printed first.
|
||||
* @property {string} levelKey Name of the key in the log data that contains
|
||||
* the message.
|
||||
* @property {string} levelLabel Format token to represent the position of the
|
||||
* level name in the output string.
|
||||
* @property {MessageFormatString|MessageFormatFunction} messageFormat
|
||||
* @property {string} messageKey Name of the key in the log data that contains
|
||||
* the message.
|
||||
* @property {string|number} minimumLevel The minimum log level to process
|
||||
* and output.
|
||||
* @property {ColorizerFunc} objectColorizer
|
||||
* @property {boolean} singleLine Indicates objects should be printed on a
|
||||
* single output line.
|
||||
* @property {string} timestampKey The name of the key in the log data that
|
||||
* contains the log timestamp.
|
||||
* @property {boolean} translateTime Indicates if timestamps should be
|
||||
* translated to a human-readable string.
|
||||
* @property {boolean} useOnlyCustomProps
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {PinoPrettyOptions} options The user supplied object of options.
|
||||
*
|
||||
* @returns {PrettyContext}
|
||||
*/
|
||||
function parseFactoryOptions (options) {
|
||||
const EOL = options.crlf ? '\r\n' : '\n'
|
||||
const IDENT = ' '
|
||||
const {
|
||||
customPrettifiers,
|
||||
errorLikeObjectKeys,
|
||||
hideObject,
|
||||
levelFirst,
|
||||
levelKey,
|
||||
levelLabel,
|
||||
messageFormat,
|
||||
messageKey,
|
||||
minimumLevel,
|
||||
singleLine,
|
||||
timestampKey,
|
||||
translateTime
|
||||
} = options
|
||||
const errorProps = options.errorProps.split(',')
|
||||
const useOnlyCustomProps = typeof options.useOnlyCustomProps === 'boolean'
|
||||
? options.useOnlyCustomProps
|
||||
: (options.useOnlyCustomProps === 'true')
|
||||
const customLevels = handleCustomLevelsOpts(options.customLevels)
|
||||
const customLevelNames = handleCustomLevelsNamesOpts(options.customLevels)
|
||||
const getLevelLabelData = handleLevelLabelData(useOnlyCustomProps, customLevels, customLevelNames)
|
||||
|
||||
let customColors
|
||||
if (options.customColors) {
|
||||
if (typeof options.customColors === 'string') {
|
||||
customColors = options.customColors.split(',').reduce((agg, value) => {
|
||||
const [level, color] = value.split(':')
|
||||
const condition = useOnlyCustomProps
|
||||
? options.customLevels
|
||||
: customLevelNames[level] !== undefined
|
||||
const levelNum = condition
|
||||
? customLevelNames[level]
|
||||
: LEVEL_NAMES[level]
|
||||
const colorIdx = levelNum !== undefined
|
||||
? levelNum
|
||||
: level
|
||||
agg.push([colorIdx, color])
|
||||
return agg
|
||||
}, [])
|
||||
} else if (typeof options.customColors === 'object') {
|
||||
customColors = Object.keys(options.customColors).reduce((agg, value) => {
|
||||
const [level, color] = [value, options.customColors[value]]
|
||||
const condition = useOnlyCustomProps
|
||||
? options.customLevels
|
||||
: customLevelNames[level] !== undefined
|
||||
const levelNum = condition
|
||||
? customLevelNames[level]
|
||||
: LEVEL_NAMES[level]
|
||||
const colorIdx = levelNum !== undefined
|
||||
? levelNum
|
||||
: level
|
||||
agg.push([colorIdx, color])
|
||||
return agg
|
||||
}, [])
|
||||
} else {
|
||||
throw new Error('options.customColors must be of type string or object.')
|
||||
}
|
||||
}
|
||||
|
||||
const customProperties = { customLevels, customLevelNames }
|
||||
if (useOnlyCustomProps === true && !options.customLevels) {
|
||||
customProperties.customLevels = undefined
|
||||
customProperties.customLevelNames = undefined
|
||||
}
|
||||
|
||||
const includeKeys = options.include !== undefined
|
||||
? new Set(options.include.split(','))
|
||||
: undefined
|
||||
const ignoreKeys = (!includeKeys && options.ignore)
|
||||
? new Set(options.ignore.split(','))
|
||||
: undefined
|
||||
|
||||
const colorizer = colors(options.colorize, customColors, useOnlyCustomProps)
|
||||
const objectColorizer = options.colorizeObjects
|
||||
? colorizer
|
||||
: colors(false, [], false)
|
||||
|
||||
return {
|
||||
EOL,
|
||||
IDENT,
|
||||
colorizer,
|
||||
customColors,
|
||||
customLevelNames,
|
||||
customLevels,
|
||||
customPrettifiers,
|
||||
customProperties,
|
||||
errorLikeObjectKeys,
|
||||
errorProps,
|
||||
getLevelLabelData,
|
||||
hideObject,
|
||||
ignoreKeys,
|
||||
includeKeys,
|
||||
levelFirst,
|
||||
levelKey,
|
||||
levelLabel,
|
||||
messageFormat,
|
||||
messageKey,
|
||||
minimumLevel,
|
||||
objectColorizer,
|
||||
singleLine,
|
||||
timestampKey,
|
||||
translateTime,
|
||||
useOnlyCustomProps
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
|
||||
*
|
||||
* To break sha256 using birthday attack, attackers need to try 2^128 hashes.
|
||||
* BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
|
||||
*
|
||||
* Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
|
||||
* @module
|
||||
* @deprecated
|
||||
*/
|
||||
import { SHA224 as SHA224n, sha224 as sha224n, SHA256 as SHA256n, sha256 as sha256n } from './sha2.ts';
|
||||
/** @deprecated Use import from `noble/hashes/sha2` module */
|
||||
export declare const SHA256: typeof SHA256n;
|
||||
/** @deprecated Use import from `noble/hashes/sha2` module */
|
||||
export declare const sha256: typeof sha256n;
|
||||
/** @deprecated Use import from `noble/hashes/sha2` module */
|
||||
export declare const SHA224: typeof SHA224n;
|
||||
/** @deprecated Use import from `noble/hashes/sha2` module */
|
||||
export declare const sha224: typeof sha224n;
|
||||
//# sourceMappingURL=sha256.d.ts.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"outerExpressionKinds.d.ts","sourceRoot":"","sources":["../../src/enums/outerExpressionKinds.ts"],"names":[],"mappings":"AACA,eAAO,IAAI,oBAAoB,EAAE,GAAG,CAAC"}
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* @fileoverview Rule to flag labels that are the same as an identifier
|
||||
* @author Ian Christian Myers
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
docs: {
|
||||
description: "Disallow labels that share a name with a variable",
|
||||
recommended: false,
|
||||
frozen: true,
|
||||
url: "https://eslint.org/docs/latest/rules/no-label-var",
|
||||
},
|
||||
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
identifierClashWithLabel:
|
||||
"Found identifier with same name as label.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Check if the identifier is present inside current scope
|
||||
* @param {Object} scope current scope
|
||||
* @param {string} name To evaluate
|
||||
* @returns {boolean} True if its present
|
||||
* @private
|
||||
*/
|
||||
function findIdentifier(scope, name) {
|
||||
return astUtils.getVariableByName(scope, name) !== null;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public API
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
return {
|
||||
LabeledStatement(node) {
|
||||
// Fetch the innermost scope.
|
||||
const scope = sourceCode.getScope(node);
|
||||
|
||||
/*
|
||||
* Recursively find the identifier walking up the scope, starting
|
||||
* with the innermost scope.
|
||||
*/
|
||||
if (findIdentifier(scope, node.label.name)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "identifierClashWithLabel",
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { R as VERSION, r as defineConfig, t as ConfigExport } from "./shared/define-config-Dsp5YQR4.mjs";
|
||||
//#region src/utils/load-config.d.ts
|
||||
type ConfigLoader = "bundle" | "native";
|
||||
interface LoadConfigOptions {
|
||||
/**
|
||||
* How to load the config file.
|
||||
* - `'bundle'` (default): bundle the config with Rolldown, then import it.
|
||||
* - `'native'`: import the config directly, delegating TypeScript/loader
|
||||
* handling to the runtime. Faster, but requires runtime support.
|
||||
*
|
||||
* @default 'bundle'
|
||||
*/
|
||||
configLoader?: ConfigLoader;
|
||||
}
|
||||
/**
|
||||
* Load config from a file in a way that Rolldown does.
|
||||
*
|
||||
* @param configPath The path to the config file. If empty, it will look for `rolldown.config` with supported extensions in the current working directory.
|
||||
* @param options Loading options. `configLoader` selects `'bundle'` (default) or `'native'`.
|
||||
* @returns The loaded config export
|
||||
*
|
||||
* @category Config
|
||||
*/
|
||||
declare function loadConfig(configPath: string, options?: LoadConfigOptions): Promise<ConfigExport>;
|
||||
//#endregion
|
||||
export { VERSION, defineConfig, loadConfig };
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"main": "../../cjs/_ts_rewrite_relative_import_extension.cjs",
|
||||
"module": "../../esm/_ts_rewrite_relative_import_extension.js"
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
const _path = require('./shared/pathe.BSlhyZSM.cjs');
|
||||
|
||||
const delimiter = /* @__PURE__ */ (() => globalThis.process?.platform === "win32" ? ";" : ":")();
|
||||
const _platforms = { posix: void 0, win32: void 0 };
|
||||
const mix = (del = delimiter) => {
|
||||
return new Proxy(_path._path, {
|
||||
get(_, prop) {
|
||||
if (prop === "delimiter") return del;
|
||||
if (prop === "posix") return posix;
|
||||
if (prop === "win32") return win32;
|
||||
return _platforms[prop] || _path._path[prop];
|
||||
}
|
||||
});
|
||||
};
|
||||
const posix = /* @__PURE__ */ mix(":");
|
||||
const win32 = /* @__PURE__ */ mix(";");
|
||||
|
||||
exports.basename = _path.basename;
|
||||
exports.dirname = _path.dirname;
|
||||
exports.extname = _path.extname;
|
||||
exports.format = _path.format;
|
||||
exports.isAbsolute = _path.isAbsolute;
|
||||
exports.join = _path.join;
|
||||
exports.matchesGlob = _path.matchesGlob;
|
||||
exports.normalize = _path.normalize;
|
||||
exports.normalizeString = _path.normalizeString;
|
||||
exports.parse = _path.parse;
|
||||
exports.relative = _path.relative;
|
||||
exports.resolve = _path.resolve;
|
||||
exports.sep = _path.sep;
|
||||
exports.toNamespacedPath = _path.toNamespacedPath;
|
||||
exports.default = posix;
|
||||
exports.delimiter = delimiter;
|
||||
exports.posix = posix;
|
||||
exports.win32 = win32;
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"ed448.d.ts","sourceRoot":"","sources":["src/ed448.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAEvD,OAAO,EAEL,iBAAiB,EAEjB,KAAK,OAAO,EAEZ,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAIL,KAAK,SAAS,EACd,KAAK,aAAa,EAClB,KAAK,SAAS,EACd,KAAK,YAAY,EAClB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAiD,KAAK,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACnG,OAAO,EAAc,KAAK,cAAc,IAAI,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACvF,OAAO,EAA0D,KAAK,GAAG,EAAE,MAAM,YAAY,CAAC;AAyI9F;;;;;;;;GAQG;AACH,eAAO,MAAM,KAAK,EAAE,OAAmC,CAAC;AAGxD,0FAA0F;AAC1F,eAAO,MAAM,OAAO,EAAE,OAIf,CAAC;AAER;;;;GAIG;AACH,eAAO,MAAM,IAAI,EAAE,gBAAsC,CAAC;AAE1D;;;;GAIG;AACH,eAAO,MAAM,IAAI,EAAE,QAYf,CAAC;AA+EL,oEAAoE;AACpE,eAAO,MAAM,YAAY,EAAE,SAAS,CAAC,MAAM,CASpC,CAAC;AAgER;;;;;;GAMG;AACH,cAAM,WAAY,SAAQ,iBAAiB,CAAC,WAAW,CAAC;IAGtD,MAAM,CAAC,IAAI,EAAE,WAAW,CAC0D;IAElF,MAAM,CAAC,IAAI,EAAE,WAAW,CACsC;IAE9D,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CACS;IAElC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CACS;gBAEtB,EAAE,EAAE,YAAY;IAI5B,MAAM,CAAC,UAAU,CAAC,EAAE,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,WAAW;IAIvD,SAAS,CAAC,UAAU,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI;IAI9C,SAAS,CAAC,IAAI,CAAC,EAAE,EAAE,YAAY,GAAG,WAAW;IAI7C,kFAAkF;IAClF,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,WAAW;IAIzC,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,UAAU,GAAG,WAAW;IA+BhD;;;;OAIG;IACH,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,WAAW;IAIrC,qFAAqF;IACrF,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,WAAW,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,WAAW;IAIjE;;;OAGG;IACH,OAAO,IAAI,UAAU;IAerB;;;OAGG;IACH,MAAM,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO;IAQnC,GAAG,IAAI,OAAO;CAGf;AAED,eAAO,MAAM,QAAQ,EAAE;IACrB,KAAK,EAAE,OAAO,WAAW,CAAC;CACF,CAAC;AAE3B,4DAA4D;AAC5D,eAAO,MAAM,eAAe,EAAE,aAAa,CAAC,MAAM,CAajD,CAAC;AAUF;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,EAAE,MAAM,EAK1C,CAAC;AAEF,KAAK,SAAS,GAAG,CAAC,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,KAAK,WAAW,CAAC;AAEzE,uCAAuC;AACvC,eAAO,MAAM,UAAU,EAAE,OAAO,WAAyB,CAAC;AAC1D,+EAA+E;AAC/E,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,MAAM,CAAsD,CAAC;AACjG,+EAA+E;AAC/E,eAAO,MAAM,aAAa,EAAE,SAAS,CAAC,MAAM,CACb,CAAC;AAChC,kFAAkF;AAClF,eAAO,MAAM,cAAc,EAAE,SACgB,CAAC;AAC9C,kFAAkF;AAClF,eAAO,MAAM,gBAAgB,EAAE,SACc,CAAC;AAC9C,iDAAiD;AACjD,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,MAAM,GAAG,UAAU,GAAG,UAAU,CAElF;AACD,iDAAiD;AACjD,eAAO,MAAM,mBAAmB,EAAE,OAAO,sBAA+C,CAAC"}
|
||||
@@ -0,0 +1,229 @@
|
||||
module.exports = stringify
|
||||
stringify.default = stringify
|
||||
stringify.stable = deterministicStringify
|
||||
stringify.stableStringify = deterministicStringify
|
||||
|
||||
var LIMIT_REPLACE_NODE = '[...]'
|
||||
var CIRCULAR_REPLACE_NODE = '[Circular]'
|
||||
|
||||
var arr = []
|
||||
var replacerStack = []
|
||||
|
||||
function defaultOptions () {
|
||||
return {
|
||||
depthLimit: Number.MAX_SAFE_INTEGER,
|
||||
edgesLimit: Number.MAX_SAFE_INTEGER
|
||||
}
|
||||
}
|
||||
|
||||
// Regular stringify
|
||||
function stringify (obj, replacer, spacer, options) {
|
||||
if (typeof options === 'undefined') {
|
||||
options = defaultOptions()
|
||||
}
|
||||
|
||||
decirc(obj, '', 0, [], undefined, 0, options)
|
||||
var res
|
||||
try {
|
||||
if (replacerStack.length === 0) {
|
||||
res = JSON.stringify(obj, replacer, spacer)
|
||||
} else {
|
||||
res = JSON.stringify(obj, replaceGetterValues(replacer), spacer)
|
||||
}
|
||||
} catch (_) {
|
||||
return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]')
|
||||
} finally {
|
||||
while (arr.length !== 0) {
|
||||
var part = arr.pop()
|
||||
if (part.length === 4) {
|
||||
Object.defineProperty(part[0], part[1], part[3])
|
||||
} else {
|
||||
part[0][part[1]] = part[2]
|
||||
}
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
function setReplace (replace, val, k, parent) {
|
||||
var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)
|
||||
if (propertyDescriptor.get !== undefined) {
|
||||
if (propertyDescriptor.configurable) {
|
||||
Object.defineProperty(parent, k, { value: replace })
|
||||
arr.push([parent, k, val, propertyDescriptor])
|
||||
} else {
|
||||
replacerStack.push([val, k, replace])
|
||||
}
|
||||
} else {
|
||||
parent[k] = replace
|
||||
arr.push([parent, k, val])
|
||||
}
|
||||
}
|
||||
|
||||
function decirc (val, k, edgeIndex, stack, parent, depth, options) {
|
||||
depth += 1
|
||||
var i
|
||||
if (typeof val === 'object' && val !== null) {
|
||||
for (i = 0; i < stack.length; i++) {
|
||||
if (stack[i] === val) {
|
||||
setReplace(CIRCULAR_REPLACE_NODE, val, k, parent)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
typeof options.depthLimit !== 'undefined' &&
|
||||
depth > options.depthLimit
|
||||
) {
|
||||
setReplace(LIMIT_REPLACE_NODE, val, k, parent)
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
typeof options.edgesLimit !== 'undefined' &&
|
||||
edgeIndex + 1 > options.edgesLimit
|
||||
) {
|
||||
setReplace(LIMIT_REPLACE_NODE, val, k, parent)
|
||||
return
|
||||
}
|
||||
|
||||
stack.push(val)
|
||||
// Optimize for Arrays. Big arrays could kill the performance otherwise!
|
||||
if (Array.isArray(val)) {
|
||||
for (i = 0; i < val.length; i++) {
|
||||
decirc(val[i], i, i, stack, val, depth, options)
|
||||
}
|
||||
} else {
|
||||
var keys = Object.keys(val)
|
||||
for (i = 0; i < keys.length; i++) {
|
||||
var key = keys[i]
|
||||
decirc(val[key], key, i, stack, val, depth, options)
|
||||
}
|
||||
}
|
||||
stack.pop()
|
||||
}
|
||||
}
|
||||
|
||||
// Stable-stringify
|
||||
function compareFunction (a, b) {
|
||||
if (a < b) {
|
||||
return -1
|
||||
}
|
||||
if (a > b) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
function deterministicStringify (obj, replacer, spacer, options) {
|
||||
if (typeof options === 'undefined') {
|
||||
options = defaultOptions()
|
||||
}
|
||||
|
||||
var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj
|
||||
var res
|
||||
try {
|
||||
if (replacerStack.length === 0) {
|
||||
res = JSON.stringify(tmp, replacer, spacer)
|
||||
} else {
|
||||
res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer)
|
||||
}
|
||||
} catch (_) {
|
||||
return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]')
|
||||
} finally {
|
||||
// Ensure that we restore the object as it was.
|
||||
while (arr.length !== 0) {
|
||||
var part = arr.pop()
|
||||
if (part.length === 4) {
|
||||
Object.defineProperty(part[0], part[1], part[3])
|
||||
} else {
|
||||
part[0][part[1]] = part[2]
|
||||
}
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
function deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) {
|
||||
depth += 1
|
||||
var i
|
||||
if (typeof val === 'object' && val !== null) {
|
||||
for (i = 0; i < stack.length; i++) {
|
||||
if (stack[i] === val) {
|
||||
setReplace(CIRCULAR_REPLACE_NODE, val, k, parent)
|
||||
return
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (typeof val.toJSON === 'function') {
|
||||
return
|
||||
}
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
typeof options.depthLimit !== 'undefined' &&
|
||||
depth > options.depthLimit
|
||||
) {
|
||||
setReplace(LIMIT_REPLACE_NODE, val, k, parent)
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
typeof options.edgesLimit !== 'undefined' &&
|
||||
edgeIndex + 1 > options.edgesLimit
|
||||
) {
|
||||
setReplace(LIMIT_REPLACE_NODE, val, k, parent)
|
||||
return
|
||||
}
|
||||
|
||||
stack.push(val)
|
||||
// Optimize for Arrays. Big arrays could kill the performance otherwise!
|
||||
if (Array.isArray(val)) {
|
||||
for (i = 0; i < val.length; i++) {
|
||||
deterministicDecirc(val[i], i, i, stack, val, depth, options)
|
||||
}
|
||||
} else {
|
||||
// Create a temporary object in the required way
|
||||
var tmp = {}
|
||||
var keys = Object.keys(val).sort(compareFunction)
|
||||
for (i = 0; i < keys.length; i++) {
|
||||
var key = keys[i]
|
||||
deterministicDecirc(val[key], key, i, stack, val, depth, options)
|
||||
tmp[key] = val[key]
|
||||
}
|
||||
if (typeof parent !== 'undefined') {
|
||||
arr.push([parent, k, val])
|
||||
parent[k] = tmp
|
||||
} else {
|
||||
return tmp
|
||||
}
|
||||
}
|
||||
stack.pop()
|
||||
}
|
||||
}
|
||||
|
||||
// wraps replacer function to handle values we couldn't replace
|
||||
// and mark them as replaced value
|
||||
function replaceGetterValues (replacer) {
|
||||
replacer =
|
||||
typeof replacer !== 'undefined'
|
||||
? replacer
|
||||
: function (k, v) {
|
||||
return v
|
||||
}
|
||||
return function (key, val) {
|
||||
if (replacerStack.length > 0) {
|
||||
for (var i = 0; i < replacerStack.length; i++) {
|
||||
var part = replacerStack[i]
|
||||
if (part[1] === key && part[0] === val) {
|
||||
val = part[2]
|
||||
replacerStack.splice(i, 1)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return replacer.call(this, key, val)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { _ as _class_apply_descriptor_set } from "./_class_apply_descriptor_set.js";
|
||||
import { _ as _class_extract_field_descriptor } from "./_class_extract_field_descriptor.js";
|
||||
|
||||
function _class_private_field_set(receiver, privateMap, value) {
|
||||
var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
|
||||
_class_apply_descriptor_set(receiver, descriptor, value);
|
||||
return value;
|
||||
}
|
||||
export { _class_private_field_set as _ };
|
||||
@@ -0,0 +1,65 @@
|
||||
import type * as JSONSchema from "./json-schema.cjs";
|
||||
import type { $ZodRegistry } from "./registries.cjs";
|
||||
import type * as schemas from "./schemas.cjs";
|
||||
import { type JSONSchemaGeneratorParams, type ProcessParams, type Seen } from "./to-json-schema.cjs";
|
||||
/**
|
||||
* Parameters for the emit method of JSONSchemaGenerator.
|
||||
* @deprecated Use toJSONSchema function instead
|
||||
*/
|
||||
export type EmitParams = Pick<JSONSchemaGeneratorParams, "cycles" | "reused" | "external">;
|
||||
/**
|
||||
* Parameters for JSONSchemaGenerator constructor.
|
||||
* @deprecated Use toJSONSchema function instead
|
||||
*/
|
||||
type JSONSchemaGeneratorConstructorParams = Pick<JSONSchemaGeneratorParams, "metadata" | "target" | "unrepresentable" | "override" | "io">;
|
||||
/**
|
||||
* Legacy class-based interface for JSON Schema generation.
|
||||
* This class wraps the new functional implementation to provide backward compatibility.
|
||||
*
|
||||
* @deprecated Use the `toJSONSchema` function instead for new code.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Legacy usage (still supported)
|
||||
* const gen = new JSONSchemaGenerator({ target: "draft-07" });
|
||||
* gen.process(schema);
|
||||
* const result = gen.emit(schema);
|
||||
*
|
||||
* // Preferred modern usage
|
||||
* const result = toJSONSchema(schema, { target: "draft-07" });
|
||||
* ```
|
||||
*/
|
||||
export declare class JSONSchemaGenerator {
|
||||
private ctx;
|
||||
/** @deprecated Access via ctx instead */
|
||||
get metadataRegistry(): $ZodRegistry<Record<string, any>>;
|
||||
/** @deprecated Access via ctx instead */
|
||||
get target(): ({} & string) | "draft-2020-12" | "draft-07" | "openapi-3.0" | "draft-04";
|
||||
/** @deprecated Access via ctx instead */
|
||||
get unrepresentable(): "any" | "throw";
|
||||
/** @deprecated Access via ctx instead */
|
||||
get override(): (ctx: {
|
||||
zodSchema: schemas.$ZodType;
|
||||
jsonSchema: JSONSchema.BaseSchema;
|
||||
path: (string | number)[];
|
||||
}) => void;
|
||||
/** @deprecated Access via ctx instead */
|
||||
get io(): "input" | "output";
|
||||
/** @deprecated Access via ctx instead */
|
||||
get counter(): number;
|
||||
set counter(value: number);
|
||||
/** @deprecated Access via ctx instead */
|
||||
get seen(): Map<schemas.$ZodType, Seen>;
|
||||
constructor(params?: JSONSchemaGeneratorConstructorParams);
|
||||
/**
|
||||
* Process a schema to prepare it for JSON Schema generation.
|
||||
* This must be called before emit().
|
||||
*/
|
||||
process(schema: schemas.$ZodType, _params?: ProcessParams): JSONSchema.BaseSchema;
|
||||
/**
|
||||
* Emit the final JSON Schema after processing.
|
||||
* Must call process() first.
|
||||
*/
|
||||
emit(schema: schemas.$ZodType, _params?: EmitParams): JSONSchema.BaseSchema;
|
||||
}
|
||||
export {};
|
||||
@@ -0,0 +1,186 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.phrases = void 0;
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const util_1 = require("../util");
|
||||
exports.phrases = {
|
||||
[utils_1.AST_NODE_TYPES.TSInterfaceDeclaration]: 'Interface',
|
||||
[utils_1.AST_NODE_TYPES.TSTypeLiteral]: 'Type literal',
|
||||
};
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'prefer-function-type',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description: 'Enforce using function types instead of interfaces with call signatures',
|
||||
recommended: 'stylistic',
|
||||
},
|
||||
fixable: 'code',
|
||||
messages: {
|
||||
functionTypeOverCallableType: '{{ literalOrInterface }} only has a call signature, you should use a function type instead.',
|
||||
unexpectedThisOnFunctionOnlyInterface: "`this` refers to the function type '{{ interfaceName }}', did you intend to use a generic `this` parameter like `<Self>(this: Self, ...) => Self` instead?",
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
defaultOptions: [],
|
||||
create(context) {
|
||||
/**
|
||||
* Checks if there the interface has exactly one supertype that isn't named 'Function'
|
||||
* @param node The node being checked
|
||||
*/
|
||||
function hasOneSupertype(node) {
|
||||
if (node.extends.length === 0) {
|
||||
return false;
|
||||
}
|
||||
if (node.extends.length !== 1) {
|
||||
return true;
|
||||
}
|
||||
const expr = node.extends[0].expression;
|
||||
return (expr.type !== utils_1.AST_NODE_TYPES.Identifier || expr.name !== 'Function');
|
||||
}
|
||||
/**
|
||||
* @param parent The parent of the call signature causing the diagnostic
|
||||
*/
|
||||
function shouldWrapSuggestion(parent) {
|
||||
if (!parent) {
|
||||
return false;
|
||||
}
|
||||
switch (parent.type) {
|
||||
case utils_1.AST_NODE_TYPES.TSUnionType:
|
||||
case utils_1.AST_NODE_TYPES.TSIntersectionType:
|
||||
case utils_1.AST_NODE_TYPES.TSArrayType:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param member The TypeElement being checked
|
||||
* @param node The parent of member being checked
|
||||
*/
|
||||
function checkMember(member, node, tsThisTypes = null) {
|
||||
if ((member.type === utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration ||
|
||||
member.type === utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration) &&
|
||||
member.returnType != null) {
|
||||
if (tsThisTypes?.length &&
|
||||
node.type === utils_1.AST_NODE_TYPES.TSInterfaceDeclaration) {
|
||||
// the message can be confusing if we don't point directly to the `this` node instead of the whole member
|
||||
// and in favour of generating at most one error we'll only report the first occurrence of `this` if there are multiple
|
||||
context.report({
|
||||
node: tsThisTypes[0],
|
||||
messageId: 'unexpectedThisOnFunctionOnlyInterface',
|
||||
data: {
|
||||
interfaceName: node.id.name,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
const fixable = node.parent.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration;
|
||||
const fix = fixable
|
||||
? null
|
||||
: (fixer) => {
|
||||
const fixes = [];
|
||||
const start = member.range[0];
|
||||
// https://github.com/microsoft/TypeScript/pull/56908
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const colonPos = member.returnType.range[0] - start;
|
||||
const text = context.sourceCode
|
||||
.getText()
|
||||
.slice(start, member.range[1]);
|
||||
const comments = [
|
||||
...context.sourceCode.getCommentsBefore(member),
|
||||
...context.sourceCode.getCommentsAfter(member),
|
||||
];
|
||||
let suggestion = `${text.slice(0, colonPos)} =>${text.slice(colonPos + 1)}`;
|
||||
const lastChar = suggestion.endsWith(';') ? ';' : '';
|
||||
if (lastChar) {
|
||||
suggestion = suggestion.slice(0, -1);
|
||||
}
|
||||
if (shouldWrapSuggestion(node.parent)) {
|
||||
suggestion = `(${suggestion})`;
|
||||
}
|
||||
if (node.type === utils_1.AST_NODE_TYPES.TSInterfaceDeclaration) {
|
||||
if (node.typeParameters != null) {
|
||||
suggestion = `type ${context.sourceCode
|
||||
.getText()
|
||||
.slice(node.id.range[0], node.typeParameters.range[1])} = ${suggestion}${lastChar}`;
|
||||
}
|
||||
else {
|
||||
suggestion = `type ${node.id.name} = ${suggestion}${lastChar}`;
|
||||
}
|
||||
}
|
||||
const isParentExported = node.parent.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration;
|
||||
if (node.type === utils_1.AST_NODE_TYPES.TSInterfaceDeclaration &&
|
||||
isParentExported) {
|
||||
const commentsText = comments
|
||||
.map(({ type, value }) => type === utils_1.AST_TOKEN_TYPES.Line
|
||||
? `//${value}\n`
|
||||
: `/*${value}*/\n`)
|
||||
.join('');
|
||||
// comments should move before export and not between export and interface declaration
|
||||
fixes.push(fixer.insertTextBefore(node.parent, commentsText));
|
||||
}
|
||||
else {
|
||||
comments.forEach(comment => {
|
||||
let commentText = comment.type === utils_1.AST_TOKEN_TYPES.Line
|
||||
? `//${comment.value}`
|
||||
: `/*${comment.value}*/`;
|
||||
const isCommentOnTheSameLine = comment.loc.start.line === member.loc.start.line;
|
||||
if (!isCommentOnTheSameLine) {
|
||||
commentText += '\n';
|
||||
}
|
||||
else {
|
||||
commentText += ' ';
|
||||
}
|
||||
suggestion = commentText + suggestion;
|
||||
});
|
||||
}
|
||||
const fixStart = node.range[0];
|
||||
fixes.push(fixer.replaceTextRange([fixStart, node.range[1]], suggestion));
|
||||
return fixes;
|
||||
};
|
||||
context.report({
|
||||
node: member,
|
||||
messageId: 'functionTypeOverCallableType',
|
||||
data: {
|
||||
literalOrInterface: exports.phrases[node.type],
|
||||
},
|
||||
fix,
|
||||
});
|
||||
}
|
||||
}
|
||||
let tsThisTypes = null;
|
||||
let literalNesting = 0;
|
||||
return {
|
||||
TSInterfaceDeclaration() {
|
||||
// when entering an interface reset the count of `this`s to empty.
|
||||
tsThisTypes = [];
|
||||
},
|
||||
'TSInterfaceDeclaration:exit'(node) {
|
||||
if (!hasOneSupertype(node) && node.body.body.length === 1) {
|
||||
checkMember(node.body.body[0], node, tsThisTypes);
|
||||
}
|
||||
// on exit check member and reset the array to nothing.
|
||||
tsThisTypes = null;
|
||||
},
|
||||
'TSInterfaceDeclaration TSThisType'(node) {
|
||||
// inside an interface keep track of all ThisType references.
|
||||
// unless it's inside a nested type literal in which case it's invalid code anyway
|
||||
// we don't want to incorrectly say "it refers to name" while typescript says it's completely invalid.
|
||||
if (literalNesting === 0 && tsThisTypes != null) {
|
||||
tsThisTypes.push(node);
|
||||
}
|
||||
},
|
||||
// keep track of nested literals to avoid complaining about invalid `this` uses
|
||||
'TSInterfaceDeclaration TSTypeLiteral'() {
|
||||
literalNesting += 1;
|
||||
},
|
||||
'TSInterfaceDeclaration TSTypeLiteral:exit'() {
|
||||
literalNesting -= 1;
|
||||
},
|
||||
'TSTypeLiteral[members.length = 1]'(node) {
|
||||
checkMember(node.members[0], node);
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,555 @@
|
||||
import AtRule = require('./at-rule.js')
|
||||
import { AtRuleProps } from './at-rule.js'
|
||||
import Comment, { CommentProps } from './comment.js'
|
||||
import Container, { NewChild } from './container.js'
|
||||
import CssSyntaxError from './css-syntax-error.js'
|
||||
import Declaration, { DeclarationProps } from './declaration.js'
|
||||
import Document from './document.js'
|
||||
import Input from './input.js'
|
||||
import { Stringifier, Syntax } from './postcss.js'
|
||||
import Result from './result.js'
|
||||
import Root from './root.js'
|
||||
import Rule, { RuleProps } from './rule.js'
|
||||
import Warning, { WarningOptions } from './warning.js'
|
||||
|
||||
declare namespace Node {
|
||||
export type ChildNode = AtRule.default | Comment | Declaration | Rule
|
||||
|
||||
export type AnyNode =
|
||||
| AtRule.default
|
||||
| Comment
|
||||
| Declaration
|
||||
| Document
|
||||
| Root
|
||||
| Rule
|
||||
|
||||
export type ChildProps =
|
||||
| AtRuleProps
|
||||
| CommentProps
|
||||
| DeclarationProps
|
||||
| RuleProps
|
||||
|
||||
export interface Position {
|
||||
/**
|
||||
* Source column in file. It starts from 1.
|
||||
*/
|
||||
column: number
|
||||
|
||||
/**
|
||||
* Source line in file. It starts from 1.
|
||||
*/
|
||||
line: number
|
||||
|
||||
/**
|
||||
* Source offset in file. It starts from 0.
|
||||
*/
|
||||
offset: number
|
||||
}
|
||||
|
||||
export interface Range {
|
||||
/**
|
||||
* End position, exclusive.
|
||||
*/
|
||||
end: Position
|
||||
|
||||
/**
|
||||
* Start position, inclusive.
|
||||
*/
|
||||
start: Position
|
||||
}
|
||||
|
||||
/**
|
||||
* Source represents an interface for the {@link Node.source} property.
|
||||
*/
|
||||
export interface Source {
|
||||
/**
|
||||
* The inclusive ending position for the source
|
||||
* code of a node.
|
||||
*
|
||||
* However, `end.offset` of a non `Root` node is the exclusive position.
|
||||
* See https://github.com/postcss/postcss/pull/1879 for details.
|
||||
*
|
||||
* ```js
|
||||
* const root = postcss.parse('a { color: black }')
|
||||
* const a = root.first
|
||||
* const color = a.first
|
||||
*
|
||||
* // The offset of `Root` node is the inclusive position
|
||||
* css.source.end // { line: 1, column: 19, offset: 18 }
|
||||
*
|
||||
* // The offset of non `Root` node is the exclusive position
|
||||
* a.source.end // { line: 1, column: 18, offset: 18 }
|
||||
* color.source.end // { line: 1, column: 16, offset: 16 }
|
||||
* ```
|
||||
*/
|
||||
end?: Position
|
||||
|
||||
/**
|
||||
* The source file from where a node has originated.
|
||||
*/
|
||||
input: Input
|
||||
|
||||
/**
|
||||
* The inclusive starting position for the source
|
||||
* code of a node.
|
||||
*/
|
||||
start?: Position
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface represents an interface for an object received
|
||||
* as parameter by Node class constructor.
|
||||
*/
|
||||
export interface NodeProps {
|
||||
source?: Source
|
||||
}
|
||||
|
||||
export interface NodeErrorOptions {
|
||||
/**
|
||||
* An ending index inside a node's string that should be highlighted as
|
||||
* source of error.
|
||||
*/
|
||||
endIndex?: number
|
||||
/**
|
||||
* An index inside a node's string that should be highlighted as source
|
||||
* of error.
|
||||
*/
|
||||
index?: number
|
||||
/**
|
||||
* Plugin name that created this error. PostCSS will set it automatically.
|
||||
*/
|
||||
plugin?: string
|
||||
/**
|
||||
* A word inside a node's string, that should be highlighted as source
|
||||
* of error.
|
||||
*/
|
||||
word?: string
|
||||
}
|
||||
|
||||
class Node extends Node_ {}
|
||||
export { Node as default }
|
||||
}
|
||||
|
||||
/**
|
||||
* It represents an abstract class that handles common
|
||||
* methods for other CSS abstract syntax tree nodes.
|
||||
*
|
||||
* Any node that represents CSS selector or value should
|
||||
* not extend the `Node` class.
|
||||
*/
|
||||
declare abstract class Node_ {
|
||||
/**
|
||||
* It represents parent of the current node.
|
||||
*
|
||||
* ```js
|
||||
* root.nodes[0].parent === root //=> true
|
||||
* ```
|
||||
*/
|
||||
parent: Container | Document | undefined
|
||||
|
||||
/**
|
||||
* It represents unnecessary whitespace and characters present
|
||||
* in the css source code.
|
||||
*
|
||||
* Information to generate byte-to-byte equal node string as it was
|
||||
* in the origin input.
|
||||
*
|
||||
* The properties of the raws object are decided by parser,
|
||||
* the default parser uses the following properties:
|
||||
*
|
||||
* * `before`: the space symbols before the node. It also stores `*`
|
||||
* and `_` symbols before the declaration (IE hack).
|
||||
* * `after`: the space symbols after the last child of the node
|
||||
* to the end of the node.
|
||||
* * `between`: the symbols between the property and value
|
||||
* for declarations, selector and `{` for rules, or last parameter
|
||||
* and `{` for at-rules.
|
||||
* * `semicolon`: contains true if the last child has
|
||||
* an (optional) semicolon.
|
||||
* * `afterName`: the space between the at-rule name and its parameters.
|
||||
* * `left`: the space symbols between `/*` and the comment’s text.
|
||||
* * `right`: the space symbols between the comment’s text
|
||||
* and <code>*/</code>.
|
||||
* - `important`: the content of the important statement,
|
||||
* if it is not just `!important`.
|
||||
*
|
||||
* PostCSS filters out the comments inside selectors, declaration values
|
||||
* and at-rule parameters but it stores the origin content in raws.
|
||||
*
|
||||
* ```js
|
||||
* const root = postcss.parse('a {\n color:black\n}')
|
||||
* root.first.first.raws //=> { before: '\n ', between: ':' }
|
||||
* ```
|
||||
*/
|
||||
raws: any
|
||||
|
||||
/**
|
||||
* It represents information related to origin of a node and is required
|
||||
* for generating source maps.
|
||||
*
|
||||
* The nodes that are created manually using the public APIs
|
||||
* provided by PostCSS will have `source` undefined and
|
||||
* will be absent in the source map.
|
||||
*
|
||||
* For this reason, the plugin developer should consider
|
||||
* duplicating nodes as the duplicate node will have the
|
||||
* same source as the original node by default or assign
|
||||
* source to a node created manually.
|
||||
*
|
||||
* ```js
|
||||
* decl.source.input.from //=> '/home/ai/source.css'
|
||||
* decl.source.start //=> { line: 10, column: 2 }
|
||||
* decl.source.end //=> { line: 10, column: 12 }
|
||||
* ```
|
||||
*
|
||||
* ```js
|
||||
* // Incorrect method, source not specified!
|
||||
* const prefixed = postcss.decl({
|
||||
* prop: '-moz-' + decl.prop,
|
||||
* value: decl.value
|
||||
* })
|
||||
*
|
||||
* // Correct method, source is inherited when duplicating.
|
||||
* const prefixed = decl.clone({
|
||||
* prop: '-moz-' + decl.prop
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* ```js
|
||||
* if (atrule.name === 'add-link') {
|
||||
* const rule = postcss.rule({
|
||||
* selector: 'a',
|
||||
* source: atrule.source
|
||||
* })
|
||||
*
|
||||
* atrule.parent.insertBefore(atrule, rule)
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
source?: Node.Source
|
||||
|
||||
/**
|
||||
* It represents type of a node in
|
||||
* an abstract syntax tree.
|
||||
*
|
||||
* A type of node helps in identification of a node
|
||||
* and perform operation based on it's type.
|
||||
*
|
||||
* ```js
|
||||
* const declaration = new Declaration({
|
||||
* prop: 'color',
|
||||
* value: 'black'
|
||||
* })
|
||||
*
|
||||
* declaration.type //=> 'decl'
|
||||
* ```
|
||||
*/
|
||||
type: string
|
||||
|
||||
constructor(defaults?: object)
|
||||
|
||||
/**
|
||||
* Insert new node after current node to current node’s parent.
|
||||
*
|
||||
* Just alias for `node.parent.insertAfter(node, add)`.
|
||||
*
|
||||
* ```js
|
||||
* decl.after('color: black')
|
||||
* ```
|
||||
*
|
||||
* @param newNode New node.
|
||||
* @return This node for methods chain.
|
||||
*/
|
||||
after(
|
||||
newNode: Node | Node.ChildProps | readonly Node[] | string | undefined
|
||||
): this
|
||||
|
||||
/**
|
||||
* It assigns properties to an existing node instance.
|
||||
*
|
||||
* ```js
|
||||
* decl.assign({ prop: 'word-wrap', value: 'break-word' })
|
||||
* ```
|
||||
*
|
||||
* @param overrides New properties to override the node.
|
||||
*
|
||||
* @return `this` for method chaining.
|
||||
*/
|
||||
assign(overrides: object): this
|
||||
|
||||
/**
|
||||
* Insert new node before current node to current node’s parent.
|
||||
*
|
||||
* Just alias for `node.parent.insertBefore(node, add)`.
|
||||
*
|
||||
* ```js
|
||||
* decl.before('content: ""')
|
||||
* ```
|
||||
*
|
||||
* @param newNode New node.
|
||||
* @return This node for methods chain.
|
||||
*/
|
||||
before(
|
||||
newNode: Node | Node.ChildProps | readonly Node[] | string | undefined
|
||||
): this
|
||||
|
||||
/**
|
||||
* Clear the code style properties for the node and its children.
|
||||
*
|
||||
* ```js
|
||||
* node.raws.before //=> ' '
|
||||
* node.cleanRaws()
|
||||
* node.raws.before //=> undefined
|
||||
* ```
|
||||
*
|
||||
* @param keepBetween Keep the `raws.between` symbols.
|
||||
*/
|
||||
cleanRaws(keepBetween?: boolean): void
|
||||
|
||||
/**
|
||||
* It creates clone of an existing node, which includes all the properties
|
||||
* and their values, that includes `raws` but not `type`.
|
||||
*
|
||||
* ```js
|
||||
* decl.raws.before //=> "\n "
|
||||
* const cloned = decl.clone({ prop: '-moz-' + decl.prop })
|
||||
* cloned.raws.before //=> "\n "
|
||||
* cloned.toString() //=> -moz-transform: scale(0)
|
||||
* ```
|
||||
*
|
||||
* @param overrides New properties to override in the clone.
|
||||
*
|
||||
* @return Duplicate of the node instance.
|
||||
*/
|
||||
clone(overrides?: object): this
|
||||
|
||||
/**
|
||||
* Shortcut to clone the node and insert the resulting cloned node
|
||||
* after the current node.
|
||||
*
|
||||
* @param overrides New properties to override in the clone.
|
||||
* @return New node.
|
||||
*/
|
||||
cloneAfter(overrides?: object): this
|
||||
|
||||
/**
|
||||
* Shortcut to clone the node and insert the resulting cloned node
|
||||
* before the current node.
|
||||
*
|
||||
* ```js
|
||||
* decl.cloneBefore({ prop: '-moz-' + decl.prop })
|
||||
* ```
|
||||
*
|
||||
* @param overrides Mew properties to override in the clone.
|
||||
*
|
||||
* @return New node
|
||||
*/
|
||||
cloneBefore(overrides?: object): this
|
||||
|
||||
/**
|
||||
* It creates an instance of the class `CssSyntaxError` and parameters passed
|
||||
* to this method are assigned to the error instance.
|
||||
*
|
||||
* The error instance will have description for the
|
||||
* error, original position of the node in the
|
||||
* source, showing line and column number.
|
||||
*
|
||||
* If any previous map is present, it would be used
|
||||
* to get original position of the source.
|
||||
*
|
||||
* The Previous Map here is referred to the source map
|
||||
* generated by previous compilation, example: Less,
|
||||
* Stylus and Sass.
|
||||
*
|
||||
* This method returns the error instance instead of
|
||||
* throwing it.
|
||||
*
|
||||
* ```js
|
||||
* if (!variables[name]) {
|
||||
* throw decl.error(`Unknown variable ${name}`, { word: name })
|
||||
* // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
|
||||
* // color: $black
|
||||
* // a
|
||||
* // ^
|
||||
* // background: white
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param message Description for the error instance.
|
||||
* @param options Options for the error instance.
|
||||
*
|
||||
* @return Error instance is returned.
|
||||
*/
|
||||
error(message: string, options?: Node.NodeErrorOptions): CssSyntaxError
|
||||
|
||||
/**
|
||||
* Returns the next child of the node’s parent.
|
||||
* Returns `undefined` if the current node is the last child.
|
||||
*
|
||||
* ```js
|
||||
* if (comment.text === 'delete next') {
|
||||
* const next = comment.next()
|
||||
* if (next) {
|
||||
* next.remove()
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @return Next node.
|
||||
*/
|
||||
next(): Node.ChildNode | undefined
|
||||
|
||||
/**
|
||||
* Get the position for a word or an index inside the node.
|
||||
*
|
||||
* @param opts Options.
|
||||
* @return Position.
|
||||
*/
|
||||
positionBy(opts?: Pick<WarningOptions, 'index' | 'word'>): Node.Position
|
||||
|
||||
/**
|
||||
* Convert string index to line/column.
|
||||
*
|
||||
* @param index The symbol number in the node’s string.
|
||||
* @return Symbol position in file.
|
||||
*/
|
||||
positionInside(index: number): Node.Position
|
||||
|
||||
/**
|
||||
* Returns the previous child of the node’s parent.
|
||||
* Returns `undefined` if the current node is the first child.
|
||||
*
|
||||
* ```js
|
||||
* const annotation = decl.prev()
|
||||
* if (annotation.type === 'comment') {
|
||||
* readAnnotation(annotation.text)
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @return Previous node.
|
||||
*/
|
||||
prev(): Node.ChildNode | undefined
|
||||
|
||||
/**
|
||||
* Get the range for a word or start and end index inside the node.
|
||||
* The start index is inclusive; the end index is exclusive.
|
||||
*
|
||||
* @param opts Options.
|
||||
* @return Range.
|
||||
*/
|
||||
rangeBy(
|
||||
opts?: Pick<WarningOptions, 'end' | 'endIndex' | 'index' | 'start' | 'word'>
|
||||
): Node.Range
|
||||
|
||||
/**
|
||||
* Returns a `raws` value. If the node is missing
|
||||
* the code style property (because the node was manually built or cloned),
|
||||
* PostCSS will try to autodetect the code style property by looking
|
||||
* at other nodes in the tree.
|
||||
*
|
||||
* ```js
|
||||
* const root = postcss.parse('a { background: white }')
|
||||
* root.nodes[0].append({ prop: 'color', value: 'black' })
|
||||
* root.nodes[0].nodes[1].raws.before //=> undefined
|
||||
* root.nodes[0].nodes[1].raw('before') //=> ' '
|
||||
* ```
|
||||
*
|
||||
* @param prop Name of code style property.
|
||||
* @param defaultType Name of default value, it can be missed
|
||||
* if the value is the same as prop.
|
||||
* @return {string} Code style value.
|
||||
*/
|
||||
raw(prop: string, defaultType?: string): string
|
||||
|
||||
/**
|
||||
* It removes the node from its parent and deletes its parent property.
|
||||
*
|
||||
* ```js
|
||||
* if (decl.prop.match(/^-webkit-/)) {
|
||||
* decl.remove()
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @return `this` for method chaining.
|
||||
*/
|
||||
remove(): this
|
||||
|
||||
/**
|
||||
* Inserts node(s) before the current node and removes the current node.
|
||||
*
|
||||
* ```js
|
||||
* AtRule: {
|
||||
* mixin: atrule => {
|
||||
* atrule.replaceWith(mixinRules[atrule.params])
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param nodes Mode(s) to replace current one.
|
||||
* @return Current node to methods chain.
|
||||
*/
|
||||
replaceWith(...nodes: NewChild[]): this
|
||||
|
||||
/**
|
||||
* Finds the Root instance of the node’s tree.
|
||||
*
|
||||
* ```js
|
||||
* root.nodes[0].nodes[0].root() === root
|
||||
* ```
|
||||
*
|
||||
* @return Root parent.
|
||||
*/
|
||||
root(): Root
|
||||
|
||||
/**
|
||||
* Fix circular links on `JSON.stringify()`.
|
||||
*
|
||||
* @return Cleaned object.
|
||||
*/
|
||||
toJSON(): object
|
||||
|
||||
/**
|
||||
* It compiles the node to browser readable cascading style sheets string
|
||||
* depending on it's type.
|
||||
*
|
||||
* ```js
|
||||
* new Rule({ selector: 'a' }).toString() //=> "a {}"
|
||||
* ```
|
||||
*
|
||||
* @param stringifier A syntax to use in string generation.
|
||||
* @return CSS string of this node.
|
||||
*/
|
||||
toString(stringifier?: Stringifier | Syntax): string
|
||||
|
||||
/**
|
||||
* It is a wrapper for {@link Result#warn}, providing convenient
|
||||
* way of generating warnings.
|
||||
*
|
||||
* ```js
|
||||
* Declaration: {
|
||||
* bad: (decl, { result }) => {
|
||||
* decl.warn(result, 'Deprecated property: bad')
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param result The `Result` instance that will receive the warning.
|
||||
* @param message Description for the warning.
|
||||
* @param options Options for the warning.
|
||||
*
|
||||
* @return `Warning` instance is returned
|
||||
*/
|
||||
warn(result: Result, message: string, options?: WarningOptions): Warning
|
||||
|
||||
/**
|
||||
* If this node isn't already dirty, marks it and its ancestors as such. This
|
||||
* indicates to the LazyResult processor that the {@link Root} has been
|
||||
* modified by the current plugin and may need to be processed again by other
|
||||
* plugins.
|
||||
*/
|
||||
protected markDirty(): void
|
||||
}
|
||||
|
||||
declare class Node extends Node_ {}
|
||||
|
||||
export = Node
|
||||
@@ -0,0 +1,23 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DEFAULT_PROJECT_FILES_ERROR_EXPLANATION = void 0;
|
||||
exports.validateDefaultProjectForFilesGlob = validateDefaultProjectForFilesGlob;
|
||||
exports.DEFAULT_PROJECT_FILES_ERROR_EXPLANATION = `
|
||||
|
||||
Having many files run with the default project is known to cause performance issues and slow down linting.
|
||||
|
||||
See https://tseslint.com/allowdefaultproject-glob-too-wide
|
||||
`;
|
||||
function validateDefaultProjectForFilesGlob(allowDefaultProject) {
|
||||
if (!allowDefaultProject?.length) {
|
||||
return;
|
||||
}
|
||||
for (const glob of allowDefaultProject) {
|
||||
if (glob === '*') {
|
||||
throw new Error(`allowDefaultProject contains the overly wide '*'.${exports.DEFAULT_PROJECT_FILES_ERROR_EXPLANATION}`);
|
||||
}
|
||||
if (glob.includes('**')) {
|
||||
throw new Error(`allowDefaultProject glob '${glob}' contains a disallowed '**'.${exports.DEFAULT_PROJECT_FILES_ERROR_EXPLANATION}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
"use strict";
|
||||
|
||||
var _class_apply_descriptor_set = require("./_class_apply_descriptor_set.cjs");
|
||||
var _class_check_private_static_access = require("./_class_check_private_static_access.cjs");
|
||||
var _class_check_private_static_field_descriptor = require("./_class_check_private_static_field_descriptor.cjs");
|
||||
|
||||
function _class_static_private_field_spec_set(receiver, classConstructor, descriptor, value) {
|
||||
_class_check_private_static_access._(receiver, classConstructor);
|
||||
_class_check_private_static_field_descriptor._(descriptor, "set");
|
||||
_class_apply_descriptor_set._(receiver, descriptor, value);
|
||||
|
||||
return value;
|
||||
}
|
||||
exports._ = _class_static_private_field_spec_set;
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
let { nanoid, customAlphabet } = require('..')
|
||||
|
||||
function print(msg) {
|
||||
process.stdout.write(msg + '\n')
|
||||
}
|
||||
|
||||
function error(msg) {
|
||||
process.stderr.write(msg + '\n')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (process.argv.includes('--help') || process.argv.includes('-h')) {
|
||||
print(`
|
||||
Usage
|
||||
$ nanoid [options]
|
||||
|
||||
Options
|
||||
-s, --size Generated ID size
|
||||
-a, --alphabet Alphabet to use
|
||||
-h, --help Show this help
|
||||
|
||||
Examples
|
||||
$ nanoid --s 15
|
||||
S9sBF77U6sDB8Yg
|
||||
|
||||
$ nanoid --size 10 --alphabet abc
|
||||
bcabababca`)
|
||||
process.exit()
|
||||
}
|
||||
|
||||
let alphabet, size
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
let arg = process.argv[i]
|
||||
if (arg === '--size' || arg === '-s') {
|
||||
size = Number(process.argv[i + 1])
|
||||
i += 1
|
||||
if (Number.isNaN(size) || size <= 0) {
|
||||
error('Size must be positive integer')
|
||||
}
|
||||
} else if (arg === '--alphabet' || arg === '-a') {
|
||||
alphabet = process.argv[i + 1]
|
||||
i += 1
|
||||
} else {
|
||||
error('Unknown argument ' + arg)
|
||||
}
|
||||
}
|
||||
|
||||
if (alphabet) {
|
||||
let customNanoid = customAlphabet(alphabet, size)
|
||||
print(customNanoid())
|
||||
} else {
|
||||
print(nanoid(size))
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const tsutils = __importStar(require("ts-api-utils"));
|
||||
const ts = __importStar(require("typescript"));
|
||||
const util_1 = require("../util");
|
||||
var RestTypeKind;
|
||||
(function (RestTypeKind) {
|
||||
RestTypeKind[RestTypeKind["Array"] = 0] = "Array";
|
||||
RestTypeKind[RestTypeKind["Tuple"] = 1] = "Tuple";
|
||||
RestTypeKind[RestTypeKind["Other"] = 2] = "Other";
|
||||
})(RestTypeKind || (RestTypeKind = {}));
|
||||
class FunctionSignature {
|
||||
paramTypes;
|
||||
restType;
|
||||
hasConsumedArguments = false;
|
||||
parameterTypeIndex = 0;
|
||||
constructor(paramTypes, restType) {
|
||||
this.paramTypes = paramTypes;
|
||||
this.restType = restType;
|
||||
}
|
||||
static create(checker, tsNode) {
|
||||
const signature = checker.getResolvedSignature(tsNode);
|
||||
if (!signature) {
|
||||
return null;
|
||||
}
|
||||
const paramTypes = [];
|
||||
let restType = null;
|
||||
const parameters = signature.getParameters();
|
||||
for (let i = 0; i < parameters.length; i += 1) {
|
||||
const param = parameters[i];
|
||||
const type = checker.getTypeOfSymbolAtLocation(param, tsNode);
|
||||
const decl = param.getDeclarations()?.[0];
|
||||
if (decl && (0, util_1.isRestParameterDeclaration)(decl)) {
|
||||
// is a rest param
|
||||
if (checker.isArrayType(type)) {
|
||||
restType = {
|
||||
type: checker.getTypeArguments(type)[0],
|
||||
index: i,
|
||||
kind: RestTypeKind.Array,
|
||||
};
|
||||
}
|
||||
else if (checker.isTupleType(type)) {
|
||||
restType = {
|
||||
index: i,
|
||||
kind: RestTypeKind.Tuple,
|
||||
typeArguments: checker.getTypeArguments(type),
|
||||
};
|
||||
}
|
||||
else {
|
||||
restType = {
|
||||
type,
|
||||
index: i,
|
||||
kind: RestTypeKind.Other,
|
||||
};
|
||||
}
|
||||
break;
|
||||
}
|
||||
paramTypes.push(type);
|
||||
}
|
||||
return new this(paramTypes, restType);
|
||||
}
|
||||
consumeRemainingArguments() {
|
||||
this.hasConsumedArguments = true;
|
||||
}
|
||||
getNextParameterType() {
|
||||
const index = this.parameterTypeIndex;
|
||||
this.parameterTypeIndex += 1;
|
||||
if (index >= this.paramTypes.length || this.hasConsumedArguments) {
|
||||
if (this.restType == null) {
|
||||
return null;
|
||||
}
|
||||
switch (this.restType.kind) {
|
||||
case RestTypeKind.Tuple: {
|
||||
const typeArguments = this.restType.typeArguments;
|
||||
if (this.hasConsumedArguments) {
|
||||
// all types consumed by a rest - just assume it's the last type
|
||||
// there is one edge case where this is wrong, but we ignore it because
|
||||
// it's rare and really complicated to handle
|
||||
// eg: function foo(...a: [number, ...string[], number])
|
||||
return typeArguments[typeArguments.length - 1];
|
||||
}
|
||||
const typeIndex = index - this.restType.index;
|
||||
if (typeIndex >= typeArguments.length) {
|
||||
return typeArguments[typeArguments.length - 1];
|
||||
}
|
||||
return typeArguments[typeIndex];
|
||||
}
|
||||
case RestTypeKind.Array:
|
||||
case RestTypeKind.Other:
|
||||
return this.restType.type;
|
||||
}
|
||||
}
|
||||
return this.paramTypes[index];
|
||||
}
|
||||
}
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-unsafe-argument',
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Disallow calling a function with a value with type `any`',
|
||||
recommended: 'recommended',
|
||||
requiresTypeChecking: true,
|
||||
},
|
||||
messages: {
|
||||
unsafeArgument: 'Unsafe argument of type {{sender}} assigned to a parameter of type {{receiver}}.',
|
||||
unsafeArraySpread: 'Unsafe spread of an {{sender}} array type.',
|
||||
unsafeSpread: 'Unsafe spread of an {{sender}} type.',
|
||||
unsafeTupleSpread: 'Unsafe spread of a tuple type. The argument is {{sender}} and is assigned to a parameter of type {{receiver}}.',
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
defaultOptions: [],
|
||||
create(context) {
|
||||
const services = (0, util_1.getParserServices)(context);
|
||||
const checker = services.program.getTypeChecker();
|
||||
function describeType(type) {
|
||||
if (tsutils.isIntrinsicErrorType(type)) {
|
||||
return 'error typed';
|
||||
}
|
||||
return `\`${checker.typeToString(type)}\``;
|
||||
}
|
||||
function describeTypeForSpread(type) {
|
||||
if (checker.isArrayType(type) &&
|
||||
tsutils.isIntrinsicErrorType(checker.getTypeArguments(type)[0])) {
|
||||
return 'error';
|
||||
}
|
||||
return describeType(type);
|
||||
}
|
||||
function describeTypeForTuple(type) {
|
||||
if (tsutils.isIntrinsicErrorType(type)) {
|
||||
return 'error typed';
|
||||
}
|
||||
return `of type \`${checker.typeToString(type)}\``;
|
||||
}
|
||||
function checkUnsafeArguments(args, callee, node) {
|
||||
if (args.length === 0) {
|
||||
return;
|
||||
}
|
||||
// ignore any-typed calls as these are caught by no-unsafe-call
|
||||
if ((0, util_1.isTypeAnyType)(services.getTypeAtLocation(callee))) {
|
||||
return;
|
||||
}
|
||||
const tsNode = services.esTreeNodeToTSNodeMap.get(node);
|
||||
const signature = (0, util_1.nullThrows)(FunctionSignature.create(checker, tsNode), 'Expected to a signature resolved');
|
||||
if (node.type === utils_1.AST_NODE_TYPES.TaggedTemplateExpression) {
|
||||
// Consumes the first parameter (TemplateStringsArray) of the function called with TaggedTemplateExpression.
|
||||
signature.getNextParameterType();
|
||||
}
|
||||
for (const argument of args) {
|
||||
switch (argument.type) {
|
||||
// spreads consume
|
||||
case utils_1.AST_NODE_TYPES.SpreadElement: {
|
||||
const spreadArgType = services.getTypeAtLocation(argument.argument);
|
||||
if ((0, util_1.isTypeAnyType)(spreadArgType)) {
|
||||
// foo(...any)
|
||||
context.report({
|
||||
node: argument,
|
||||
messageId: 'unsafeSpread',
|
||||
data: { sender: describeType(spreadArgType) },
|
||||
});
|
||||
}
|
||||
else if ((0, util_1.isTypeAnyArrayType)(spreadArgType, checker)) {
|
||||
// foo(...any[])
|
||||
// TODO - we could break down the spread and compare the array type against each argument
|
||||
context.report({
|
||||
node: argument,
|
||||
messageId: 'unsafeArraySpread',
|
||||
data: { sender: describeTypeForSpread(spreadArgType) },
|
||||
});
|
||||
}
|
||||
else if (checker.isTupleType(spreadArgType)) {
|
||||
// foo(...[tuple1, tuple2])
|
||||
const spreadTypeArguments = checker.getTypeArguments(spreadArgType);
|
||||
for (const tupleType of spreadTypeArguments) {
|
||||
const parameterType = signature.getNextParameterType();
|
||||
if (parameterType == null) {
|
||||
continue;
|
||||
}
|
||||
const result = (0, util_1.isUnsafeAssignment)(tupleType, parameterType, checker,
|
||||
// we can't pass the individual tuple members in here as this will most likely be a spread variable
|
||||
// not a spread array
|
||||
null);
|
||||
if (result) {
|
||||
context.report({
|
||||
node: argument,
|
||||
messageId: 'unsafeTupleSpread',
|
||||
data: {
|
||||
receiver: describeType(parameterType),
|
||||
sender: describeTypeForTuple(tupleType),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
if (spreadArgType.target.combinedFlags & ts.ElementFlags.Variable) {
|
||||
// the last element was a rest - so all remaining defined arguments can be considered "consumed"
|
||||
// all remaining arguments should be compared against the rest type (if one exists)
|
||||
signature.consumeRemainingArguments();
|
||||
}
|
||||
}
|
||||
else {
|
||||
// something that's iterable
|
||||
// handling this will be pretty complex - so we ignore it for now
|
||||
// TODO - handle generic iterable case
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
const parameterType = signature.getNextParameterType();
|
||||
if (parameterType == null) {
|
||||
continue;
|
||||
}
|
||||
const argumentType = services.getTypeAtLocation(argument);
|
||||
const result = (0, util_1.isUnsafeAssignment)(argumentType, parameterType, checker, argument);
|
||||
if (result) {
|
||||
context.report({
|
||||
node: argument,
|
||||
messageId: 'unsafeArgument',
|
||||
data: {
|
||||
receiver: describeType(parameterType),
|
||||
sender: describeType(argumentType),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
'CallExpression, NewExpression'(node) {
|
||||
checkUnsafeArguments(node.arguments, node.callee, node);
|
||||
},
|
||||
TaggedTemplateExpression(node) {
|
||||
checkUnsafeArguments(node.quasi.expressions, node.tag, node);
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { TSESTree } from '@typescript-eslint/types';
|
||||
import { DefinitionBase } from './DefinitionBase';
|
||||
import { DefinitionType } from './DefinitionType';
|
||||
export declare class FunctionNameDefinition extends DefinitionBase<DefinitionType.FunctionName, TSESTree.FunctionDeclaration | TSESTree.FunctionExpression | TSESTree.TSDeclareFunction | TSESTree.TSEmptyBodyFunctionExpression, null, TSESTree.Identifier> {
|
||||
readonly isTypeDefinition = false;
|
||||
readonly isVariableDefinition = true;
|
||||
constructor(name: TSESTree.Identifier, node: FunctionNameDefinition['node']);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name" : "eyes",
|
||||
"description" : "a customizable value inspector",
|
||||
"url" : "http://github.com/cloudhead/eyes.js",
|
||||
"keywords" : ["inspector", "debug", "inspect", "print"],
|
||||
"author" : "Alexis Sellier <self@cloudhead.net>",
|
||||
"contributors" : [{ "name": "Charlie Robbins", "email": "charlie@nodejitsu.com" }],
|
||||
"licenses" : ["MIT"],
|
||||
"main" : "./lib/eyes",
|
||||
"version" : "0.1.8",
|
||||
"scripts" : { "test": "node test/*-test.js" },
|
||||
"directories" : { "lib": "./lib", "test": "./test" },
|
||||
"engines" : { "node": "> 0.1.90" }
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
/**
|
||||
* @fileoverview Restrict usage of specified globals.
|
||||
* @author Benoît Zugmeyer
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const TYPE_NODES = new Set([
|
||||
"TSTypeReference",
|
||||
"TSInterfaceHeritage",
|
||||
"TSClassImplements",
|
||||
"TSTypeQuery",
|
||||
"TSQualifiedName",
|
||||
]);
|
||||
|
||||
const GLOBAL_OBJECTS = new Set(["globalThis", "self", "window"]);
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const arrayOfGlobals = {
|
||||
type: "array",
|
||||
items: {
|
||||
oneOf: [
|
||||
{
|
||||
type: "string",
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
message: { type: "string" },
|
||||
},
|
||||
required: ["name"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
uniqueItems: true,
|
||||
minItems: 0,
|
||||
};
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
docs: {
|
||||
description: "Disallow specified global variables",
|
||||
dialects: ["JavaScript", "TypeScript"],
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/no-restricted-globals",
|
||||
},
|
||||
|
||||
schema: {
|
||||
anyOf: [
|
||||
arrayOfGlobals,
|
||||
{
|
||||
type: "array",
|
||||
items: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
globals: arrayOfGlobals,
|
||||
checkGlobalObject: {
|
||||
type: "boolean",
|
||||
},
|
||||
globalObjects: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string",
|
||||
},
|
||||
uniqueItems: true,
|
||||
},
|
||||
},
|
||||
required: ["globals"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
additionalItems: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
messages: {
|
||||
defaultMessage: "Unexpected use of '{{name}}'.",
|
||||
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
|
||||
customMessage: "Unexpected use of '{{name}}'. {{customMessage}}",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const { sourceCode, options } = context;
|
||||
|
||||
const isGlobalsObject =
|
||||
typeof options[0] === "object" &&
|
||||
Object.hasOwn(options[0], "globals");
|
||||
|
||||
const restrictedGlobals = isGlobalsObject
|
||||
? options[0].globals
|
||||
: options;
|
||||
const checkGlobalObject = isGlobalsObject
|
||||
? options[0].checkGlobalObject
|
||||
: false;
|
||||
const userGlobalObjects = isGlobalsObject
|
||||
? options[0].globalObjects || []
|
||||
: [];
|
||||
|
||||
const globalObjects = new Set([
|
||||
...GLOBAL_OBJECTS,
|
||||
...userGlobalObjects,
|
||||
]);
|
||||
|
||||
// If no globals are restricted, we don't need to do anything
|
||||
if (restrictedGlobals.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const restrictedGlobalMessages = restrictedGlobals.reduce(
|
||||
(memo, option) => {
|
||||
if (typeof option === "string") {
|
||||
memo[option] = null;
|
||||
} else {
|
||||
memo[option.name] = option.message;
|
||||
}
|
||||
|
||||
return memo;
|
||||
},
|
||||
{},
|
||||
);
|
||||
|
||||
/**
|
||||
* Report a variable to be used as a restricted global.
|
||||
* @param {Reference} reference the variable reference
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function reportReference(reference) {
|
||||
const name = reference.identifier.name,
|
||||
customMessage = restrictedGlobalMessages[name],
|
||||
messageId = customMessage ? "customMessage" : "defaultMessage";
|
||||
|
||||
context.report({
|
||||
node: reference.identifier,
|
||||
messageId,
|
||||
data: {
|
||||
name,
|
||||
customMessage,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given name is a restricted global name.
|
||||
* @param {string} name name of a variable
|
||||
* @returns {boolean} whether the variable is a restricted global or not
|
||||
* @private
|
||||
*/
|
||||
function isRestricted(name) {
|
||||
return Object.hasOwn(restrictedGlobalMessages, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given reference occurs within a TypeScript type context.
|
||||
* @param {Reference} reference The variable reference to check.
|
||||
* @returns {boolean} Whether the reference is in a type context.
|
||||
* @private
|
||||
*/
|
||||
function isInTypeContext(reference) {
|
||||
const parent = reference.identifier.parent;
|
||||
|
||||
return TYPE_NODES.has(parent.type);
|
||||
}
|
||||
|
||||
return {
|
||||
Program(node) {
|
||||
const scope = sourceCode.getScope(node);
|
||||
|
||||
// Report variables declared elsewhere (ex: variables defined as "global" by eslint)
|
||||
scope.variables.forEach(variable => {
|
||||
if (!variable.defs.length && isRestricted(variable.name)) {
|
||||
variable.references.forEach(reference => {
|
||||
if (!isInTypeContext(reference)) {
|
||||
reportReference(reference);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Report variables not declared at all
|
||||
scope.through.forEach(reference => {
|
||||
if (
|
||||
isRestricted(reference.identifier.name) &&
|
||||
!isInTypeContext(reference)
|
||||
) {
|
||||
reportReference(reference);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
"Program:exit"(node) {
|
||||
if (!checkGlobalObject) {
|
||||
return;
|
||||
}
|
||||
|
||||
const globalScope = sourceCode.getScope(node);
|
||||
globalObjects.forEach(globalObjectName => {
|
||||
const variable = astUtils.getVariableByName(
|
||||
globalScope,
|
||||
globalObjectName,
|
||||
);
|
||||
|
||||
if (!variable) {
|
||||
return;
|
||||
}
|
||||
|
||||
variable.references.forEach(reference => {
|
||||
const identifier = reference.identifier;
|
||||
let parent = identifier.parent;
|
||||
|
||||
// To detect code like `window.window.Promise`.
|
||||
while (
|
||||
astUtils.isSpecificMemberAccess(
|
||||
parent,
|
||||
null,
|
||||
globalObjectName,
|
||||
)
|
||||
) {
|
||||
parent = parent.parent;
|
||||
}
|
||||
|
||||
const propertyName =
|
||||
astUtils.getStaticPropertyName(parent);
|
||||
if (propertyName && isRestricted(propertyName)) {
|
||||
const customMessage =
|
||||
restrictedGlobalMessages[propertyName];
|
||||
const messageId = customMessage
|
||||
? "customMessage"
|
||||
: "defaultMessage";
|
||||
|
||||
context.report({
|
||||
node: parent.property,
|
||||
messageId,
|
||||
data: {
|
||||
name: propertyName,
|
||||
customMessage,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,621 @@
|
||||
/*! *****************************************************************************
|
||||
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.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
||||
|
||||
// src/typescript/typescript.ts
|
||||
var typescript_exports = {};
|
||||
__reExport(typescript_exports, require("./typescript.js"));
|
||||
|
||||
// src/tsserver/common.ts
|
||||
function getLogLevel(level) {
|
||||
if (level) {
|
||||
const l = level.toLowerCase();
|
||||
for (const name in typescript_exports.server.LogLevel) {
|
||||
if (isNaN(+name) && l === name.toLowerCase()) {
|
||||
return typescript_exports.server.LogLevel[name];
|
||||
}
|
||||
}
|
||||
}
|
||||
return void 0;
|
||||
}
|
||||
|
||||
// src/tsserver/nodeServer.ts
|
||||
function parseLoggingEnvironmentString(logEnvStr) {
|
||||
if (!logEnvStr) {
|
||||
return {};
|
||||
}
|
||||
const logEnv = { logToFile: true };
|
||||
const args = logEnvStr.split(" ");
|
||||
const len = args.length - 1;
|
||||
for (let i = 0; i < len; i += 2) {
|
||||
const option = args[i];
|
||||
const { value, extraPartCounter } = getEntireValue(i + 1);
|
||||
i += extraPartCounter;
|
||||
if (option && value) {
|
||||
switch (option) {
|
||||
case "-file":
|
||||
logEnv.file = value;
|
||||
break;
|
||||
case "-level":
|
||||
const level = getLogLevel(value);
|
||||
logEnv.detailLevel = level !== void 0 ? level : typescript_exports.server.LogLevel.normal;
|
||||
break;
|
||||
case "-traceToConsole":
|
||||
logEnv.traceToConsole = value.toLowerCase() === "true";
|
||||
break;
|
||||
case "-logToFile":
|
||||
logEnv.logToFile = value.toLowerCase() === "true";
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return logEnv;
|
||||
function getEntireValue(initialIndex) {
|
||||
let pathStart = args[initialIndex];
|
||||
let extraPartCounter = 0;
|
||||
if (pathStart.charCodeAt(0) === typescript_exports.CharacterCodes.doubleQuote && pathStart.charCodeAt(pathStart.length - 1) !== typescript_exports.CharacterCodes.doubleQuote) {
|
||||
for (let i = initialIndex + 1; i < args.length; i++) {
|
||||
pathStart += " ";
|
||||
pathStart += args[i];
|
||||
extraPartCounter++;
|
||||
if (pathStart.charCodeAt(pathStart.length - 1) === typescript_exports.CharacterCodes.doubleQuote) break;
|
||||
}
|
||||
}
|
||||
return { value: (0, typescript_exports.stripQuotes)(pathStart), extraPartCounter };
|
||||
}
|
||||
}
|
||||
function parseServerMode() {
|
||||
const mode = typescript_exports.server.findArgument("--serverMode");
|
||||
if (!mode) return void 0;
|
||||
switch (mode.toLowerCase()) {
|
||||
case "semantic":
|
||||
return typescript_exports.LanguageServiceMode.Semantic;
|
||||
case "partialsemantic":
|
||||
return typescript_exports.LanguageServiceMode.PartialSemantic;
|
||||
case "syntactic":
|
||||
return typescript_exports.LanguageServiceMode.Syntactic;
|
||||
default:
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
function initializeNodeSystem() {
|
||||
const sys4 = typescript_exports.Debug.checkDefined(typescript_exports.sys);
|
||||
const childProcess = require("child_process");
|
||||
const fs = require("fs");
|
||||
class Logger {
|
||||
constructor(logFilename, traceToConsole, level) {
|
||||
this.logFilename = logFilename;
|
||||
this.traceToConsole = traceToConsole;
|
||||
this.level = level;
|
||||
this.seq = 0;
|
||||
this.inGroup = false;
|
||||
this.firstInGroup = true;
|
||||
this.fd = -1;
|
||||
if (this.logFilename) {
|
||||
try {
|
||||
this.fd = fs.openSync(this.logFilename, "w");
|
||||
} catch (_) {
|
||||
}
|
||||
}
|
||||
}
|
||||
static padStringRight(str, padding) {
|
||||
return (str + padding).slice(0, padding.length);
|
||||
}
|
||||
close() {
|
||||
if (this.fd >= 0) {
|
||||
fs.close(this.fd, typescript_exports.noop);
|
||||
}
|
||||
}
|
||||
getLogFileName() {
|
||||
return this.logFilename;
|
||||
}
|
||||
perftrc(s) {
|
||||
this.msg(s, typescript_exports.server.Msg.Perf);
|
||||
}
|
||||
info(s) {
|
||||
this.msg(s, typescript_exports.server.Msg.Info);
|
||||
}
|
||||
err(s) {
|
||||
this.msg(s, typescript_exports.server.Msg.Err);
|
||||
}
|
||||
startGroup() {
|
||||
this.inGroup = true;
|
||||
this.firstInGroup = true;
|
||||
}
|
||||
endGroup() {
|
||||
this.inGroup = false;
|
||||
}
|
||||
loggingEnabled() {
|
||||
return !!this.logFilename || this.traceToConsole;
|
||||
}
|
||||
hasLevel(level) {
|
||||
return this.loggingEnabled() && this.level >= level;
|
||||
}
|
||||
msg(s, type = typescript_exports.server.Msg.Err) {
|
||||
var _a, _b, _c;
|
||||
switch (type) {
|
||||
case typescript_exports.server.Msg.Info:
|
||||
(_a = typescript_exports.perfLogger) == null ? void 0 : _a.logInfoEvent(s);
|
||||
break;
|
||||
case typescript_exports.server.Msg.Perf:
|
||||
(_b = typescript_exports.perfLogger) == null ? void 0 : _b.logPerfEvent(s);
|
||||
break;
|
||||
default:
|
||||
(_c = typescript_exports.perfLogger) == null ? void 0 : _c.logErrEvent(s);
|
||||
break;
|
||||
}
|
||||
if (!this.canWrite()) return;
|
||||
s = `[${typescript_exports.server.nowString()}] ${s}
|
||||
`;
|
||||
if (!this.inGroup || this.firstInGroup) {
|
||||
const prefix = Logger.padStringRight(type + " " + this.seq.toString(), " ");
|
||||
s = prefix + s;
|
||||
}
|
||||
this.write(s, type);
|
||||
if (!this.inGroup) {
|
||||
this.seq++;
|
||||
}
|
||||
}
|
||||
canWrite() {
|
||||
return this.fd >= 0 || this.traceToConsole;
|
||||
}
|
||||
write(s, _type) {
|
||||
if (this.fd >= 0) {
|
||||
const buf = Buffer.from(s);
|
||||
fs.writeSync(
|
||||
this.fd,
|
||||
buf,
|
||||
0,
|
||||
buf.length,
|
||||
/*position*/
|
||||
null
|
||||
);
|
||||
}
|
||||
if (this.traceToConsole) {
|
||||
console.warn(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
const libDirectory = (0, typescript_exports.getDirectoryPath)((0, typescript_exports.normalizePath)(sys4.getExecutingFilePath()));
|
||||
const useWatchGuard = process.platform === "win32";
|
||||
const originalWatchDirectory = sys4.watchDirectory.bind(sys4);
|
||||
const logger = createLogger();
|
||||
typescript_exports.Debug.loggingHost = {
|
||||
log(level, s) {
|
||||
switch (level) {
|
||||
case typescript_exports.LogLevel.Error:
|
||||
case typescript_exports.LogLevel.Warning:
|
||||
return logger.msg(s, typescript_exports.server.Msg.Err);
|
||||
case typescript_exports.LogLevel.Info:
|
||||
case typescript_exports.LogLevel.Verbose:
|
||||
return logger.msg(s, typescript_exports.server.Msg.Info);
|
||||
}
|
||||
}
|
||||
};
|
||||
const pending = (0, typescript_exports.createQueue)();
|
||||
let canWrite = true;
|
||||
if (useWatchGuard) {
|
||||
const currentDrive = extractWatchDirectoryCacheKey(
|
||||
sys4.resolvePath(sys4.getCurrentDirectory()),
|
||||
/*currentDriveKey*/
|
||||
void 0
|
||||
);
|
||||
const statusCache = /* @__PURE__ */ new Map();
|
||||
sys4.watchDirectory = (path, callback, recursive, options) => {
|
||||
const cacheKey = extractWatchDirectoryCacheKey(path, currentDrive);
|
||||
let status = cacheKey && statusCache.get(cacheKey);
|
||||
if (status === void 0) {
|
||||
if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) {
|
||||
logger.info(`${cacheKey} for path ${path} not found in cache...`);
|
||||
}
|
||||
try {
|
||||
const args = [(0, typescript_exports.combinePaths)(libDirectory, "watchGuard.js"), path];
|
||||
if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) {
|
||||
logger.info(`Starting ${process.execPath} with args:${typescript_exports.server.stringifyIndented(args)}`);
|
||||
}
|
||||
childProcess.execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } });
|
||||
status = true;
|
||||
if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) {
|
||||
logger.info(`WatchGuard for path ${path} returned: OK`);
|
||||
}
|
||||
} catch (e) {
|
||||
status = false;
|
||||
if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) {
|
||||
logger.info(`WatchGuard for path ${path} returned: ${e.message}`);
|
||||
}
|
||||
}
|
||||
if (cacheKey) {
|
||||
statusCache.set(cacheKey, status);
|
||||
}
|
||||
} else if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) {
|
||||
logger.info(`watchDirectory for ${path} uses cached drive information.`);
|
||||
}
|
||||
if (status) {
|
||||
return watchDirectorySwallowingException(path, callback, recursive, options);
|
||||
} else {
|
||||
return typescript_exports.noopFileWatcher;
|
||||
}
|
||||
};
|
||||
} else {
|
||||
sys4.watchDirectory = watchDirectorySwallowingException;
|
||||
}
|
||||
sys4.write = (s) => writeMessage(Buffer.from(s, "utf8"));
|
||||
sys4.setTimeout = setTimeout;
|
||||
sys4.clearTimeout = clearTimeout;
|
||||
sys4.setImmediate = setImmediate;
|
||||
sys4.clearImmediate = clearImmediate;
|
||||
if (typeof global !== "undefined" && global.gc) {
|
||||
sys4.gc = () => {
|
||||
var _a;
|
||||
return (_a = global.gc) == null ? void 0 : _a.call(global);
|
||||
};
|
||||
}
|
||||
let cancellationToken;
|
||||
try {
|
||||
const factory = require("./cancellationToken");
|
||||
cancellationToken = factory(sys4.args);
|
||||
} catch (e) {
|
||||
cancellationToken = typescript_exports.server.nullCancellationToken;
|
||||
}
|
||||
const localeStr = typescript_exports.server.findArgument("--locale");
|
||||
if (localeStr) {
|
||||
(0, typescript_exports.validateLocaleAndSetLanguage)(localeStr, sys4);
|
||||
}
|
||||
const modeOrUnknown = parseServerMode();
|
||||
let serverMode;
|
||||
let unknownServerMode;
|
||||
if (modeOrUnknown !== void 0) {
|
||||
if (typeof modeOrUnknown === "number") serverMode = modeOrUnknown;
|
||||
else unknownServerMode = modeOrUnknown;
|
||||
}
|
||||
return {
|
||||
args: process.argv,
|
||||
logger,
|
||||
cancellationToken,
|
||||
serverMode,
|
||||
unknownServerMode,
|
||||
startSession: startNodeSession
|
||||
};
|
||||
function createLogger() {
|
||||
const cmdLineLogFileName = typescript_exports.server.findArgument("--logFile");
|
||||
const cmdLineVerbosity = getLogLevel(typescript_exports.server.findArgument("--logVerbosity"));
|
||||
const envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG);
|
||||
const unsubstitutedLogFileName = cmdLineLogFileName ? (0, typescript_exports.stripQuotes)(cmdLineLogFileName) : envLogOptions.logToFile ? envLogOptions.file || libDirectory + "/.log" + process.pid.toString() : void 0;
|
||||
const substitutedLogFileName = unsubstitutedLogFileName ? unsubstitutedLogFileName.replace("PID", process.pid.toString()) : void 0;
|
||||
const logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel;
|
||||
return new Logger(substitutedLogFileName, envLogOptions.traceToConsole, logVerbosity);
|
||||
}
|
||||
function writeMessage(buf) {
|
||||
if (!canWrite) {
|
||||
pending.enqueue(buf);
|
||||
} else {
|
||||
canWrite = false;
|
||||
process.stdout.write(buf, setCanWriteFlagAndWriteMessageIfNecessary);
|
||||
}
|
||||
}
|
||||
function setCanWriteFlagAndWriteMessageIfNecessary() {
|
||||
canWrite = true;
|
||||
if (!pending.isEmpty()) {
|
||||
writeMessage(pending.dequeue());
|
||||
}
|
||||
}
|
||||
function extractWatchDirectoryCacheKey(path, currentDriveKey) {
|
||||
path = (0, typescript_exports.normalizeSlashes)(path);
|
||||
if (isUNCPath(path)) {
|
||||
const firstSlash = path.indexOf(typescript_exports.directorySeparator, 2);
|
||||
return firstSlash !== -1 ? (0, typescript_exports.toFileNameLowerCase)(path.substring(0, firstSlash)) : path;
|
||||
}
|
||||
const rootLength = (0, typescript_exports.getRootLength)(path);
|
||||
if (rootLength === 0) {
|
||||
return currentDriveKey;
|
||||
}
|
||||
if (path.charCodeAt(1) === typescript_exports.CharacterCodes.colon && path.charCodeAt(2) === typescript_exports.CharacterCodes.slash) {
|
||||
return (0, typescript_exports.toFileNameLowerCase)(path.charAt(0));
|
||||
}
|
||||
if (path.charCodeAt(0) === typescript_exports.CharacterCodes.slash && path.charCodeAt(1) !== typescript_exports.CharacterCodes.slash) {
|
||||
return currentDriveKey;
|
||||
}
|
||||
return void 0;
|
||||
}
|
||||
function isUNCPath(s) {
|
||||
return s.length > 2 && s.charCodeAt(0) === typescript_exports.CharacterCodes.slash && s.charCodeAt(1) === typescript_exports.CharacterCodes.slash;
|
||||
}
|
||||
function watchDirectorySwallowingException(path, callback, recursive, options) {
|
||||
try {
|
||||
return originalWatchDirectory(path, callback, recursive, options);
|
||||
} catch (e) {
|
||||
logger.info(`Exception when creating directory watcher: ${e.message}`);
|
||||
return typescript_exports.noopFileWatcher;
|
||||
}
|
||||
}
|
||||
}
|
||||
function parseEventPort(eventPortStr) {
|
||||
const eventPort = eventPortStr === void 0 ? void 0 : parseInt(eventPortStr);
|
||||
return eventPort !== void 0 && !isNaN(eventPort) ? eventPort : void 0;
|
||||
}
|
||||
function startNodeSession(options, logger, cancellationToken) {
|
||||
const childProcess = require("child_process");
|
||||
const os = require("os");
|
||||
const net = require("net");
|
||||
const readline = require("readline");
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
terminal: false
|
||||
});
|
||||
const _NodeTypingsInstallerAdapter = class _NodeTypingsInstallerAdapter extends typescript_exports.server.TypingsInstallerAdapter {
|
||||
constructor(telemetryEnabled2, logger2, host, globalTypingsCacheLocation, typingSafeListLocation2, typesMapLocation2, npmLocation2, validateDefaultNpmLocation2, event) {
|
||||
super(
|
||||
telemetryEnabled2,
|
||||
logger2,
|
||||
host,
|
||||
globalTypingsCacheLocation,
|
||||
event,
|
||||
_NodeTypingsInstallerAdapter.maxActiveRequestCount
|
||||
);
|
||||
this.typingSafeListLocation = typingSafeListLocation2;
|
||||
this.typesMapLocation = typesMapLocation2;
|
||||
this.npmLocation = npmLocation2;
|
||||
this.validateDefaultNpmLocation = validateDefaultNpmLocation2;
|
||||
}
|
||||
createInstallerProcess() {
|
||||
if (this.logger.hasLevel(typescript_exports.server.LogLevel.requestTime)) {
|
||||
this.logger.info("Binding...");
|
||||
}
|
||||
const args = [typescript_exports.server.Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation];
|
||||
if (this.telemetryEnabled) {
|
||||
args.push(typescript_exports.server.Arguments.EnableTelemetry);
|
||||
}
|
||||
if (this.logger.loggingEnabled() && this.logger.getLogFileName()) {
|
||||
args.push(typescript_exports.server.Arguments.LogFile, (0, typescript_exports.combinePaths)((0, typescript_exports.getDirectoryPath)((0, typescript_exports.normalizeSlashes)(this.logger.getLogFileName())), `ti-${process.pid}.log`));
|
||||
}
|
||||
if (this.typingSafeListLocation) {
|
||||
args.push(typescript_exports.server.Arguments.TypingSafeListLocation, this.typingSafeListLocation);
|
||||
}
|
||||
if (this.typesMapLocation) {
|
||||
args.push(typescript_exports.server.Arguments.TypesMapLocation, this.typesMapLocation);
|
||||
}
|
||||
if (this.npmLocation) {
|
||||
args.push(typescript_exports.server.Arguments.NpmLocation, this.npmLocation);
|
||||
}
|
||||
if (this.validateDefaultNpmLocation) {
|
||||
args.push(typescript_exports.server.Arguments.ValidateDefaultNpmLocation);
|
||||
}
|
||||
const execArgv = [];
|
||||
for (const arg of process.execArgv) {
|
||||
const match = /^--((?:debug|inspect)(?:-brk)?)(?:=(\d+))?$/.exec(arg);
|
||||
if (match) {
|
||||
const currentPort = match[2] !== void 0 ? +match[2] : match[1].charAt(0) === "d" ? 5858 : 9229;
|
||||
execArgv.push(`--${match[1]}=${currentPort + 1}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
const typingsInstaller = (0, typescript_exports.combinePaths)((0, typescript_exports.getDirectoryPath)(typescript_exports.sys.getExecutingFilePath()), "typingsInstaller.js");
|
||||
this.installer = childProcess.fork(typingsInstaller, args, { execArgv });
|
||||
this.installer.on("message", (m) => this.handleMessage(m));
|
||||
this.host.setImmediate(() => this.event({ pid: this.installer.pid }, "typingsInstallerPid"));
|
||||
process.on("exit", () => {
|
||||
this.installer.kill();
|
||||
});
|
||||
return this.installer;
|
||||
}
|
||||
};
|
||||
// This number is essentially arbitrary. Processing more than one typings request
|
||||
// at a time makes sense, but having too many in the pipe results in a hang
|
||||
// (see https://github.com/nodejs/node/issues/7657).
|
||||
// It would be preferable to base our limit on the amount of space left in the
|
||||
// buffer, but we have yet to find a way to retrieve that value.
|
||||
_NodeTypingsInstallerAdapter.maxActiveRequestCount = 10;
|
||||
let NodeTypingsInstallerAdapter = _NodeTypingsInstallerAdapter;
|
||||
class IOSession extends typescript_exports.server.Session {
|
||||
constructor() {
|
||||
const event = (body, eventName) => {
|
||||
this.event(body, eventName);
|
||||
};
|
||||
const host = typescript_exports.sys;
|
||||
const typingsInstaller = disableAutomaticTypingAcquisition ? void 0 : new NodeTypingsInstallerAdapter(telemetryEnabled, logger, host, getGlobalTypingsCacheLocation(), typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, event);
|
||||
super({
|
||||
host,
|
||||
cancellationToken,
|
||||
...options,
|
||||
typingsInstaller,
|
||||
byteLength: Buffer.byteLength,
|
||||
hrtime: process.hrtime,
|
||||
logger,
|
||||
canUseEvents: true,
|
||||
typesMapLocation
|
||||
});
|
||||
this.eventPort = eventPort;
|
||||
if (this.canUseEvents && this.eventPort) {
|
||||
const s = net.connect({ port: this.eventPort }, () => {
|
||||
this.eventSocket = s;
|
||||
if (this.socketEventQueue) {
|
||||
for (const event2 of this.socketEventQueue) {
|
||||
this.writeToEventSocket(event2.body, event2.eventName);
|
||||
}
|
||||
this.socketEventQueue = void 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
this.constructed = true;
|
||||
}
|
||||
event(body, eventName) {
|
||||
typescript_exports.Debug.assert(!!this.constructed, "Should only call `IOSession.prototype.event` on an initialized IOSession");
|
||||
if (this.canUseEvents && this.eventPort) {
|
||||
if (!this.eventSocket) {
|
||||
if (this.logger.hasLevel(typescript_exports.server.LogLevel.verbose)) {
|
||||
this.logger.info(`eventPort: event "${eventName}" queued, but socket not yet initialized`);
|
||||
}
|
||||
(this.socketEventQueue || (this.socketEventQueue = [])).push({ body, eventName });
|
||||
return;
|
||||
} else {
|
||||
typescript_exports.Debug.assert(this.socketEventQueue === void 0);
|
||||
this.writeToEventSocket(body, eventName);
|
||||
}
|
||||
} else {
|
||||
super.event(body, eventName);
|
||||
}
|
||||
}
|
||||
writeToEventSocket(body, eventName) {
|
||||
this.eventSocket.write(typescript_exports.server.formatMessage(typescript_exports.server.toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8");
|
||||
}
|
||||
exit() {
|
||||
var _a;
|
||||
this.logger.info("Exiting...");
|
||||
this.projectService.closeLog();
|
||||
(_a = typescript_exports.tracing) == null ? void 0 : _a.stopTracing();
|
||||
process.exit(0);
|
||||
}
|
||||
listen() {
|
||||
rl.on("line", (input) => {
|
||||
const message = input.trim();
|
||||
this.onMessage(message);
|
||||
});
|
||||
rl.on("close", () => {
|
||||
this.exit();
|
||||
});
|
||||
}
|
||||
}
|
||||
class IpcIOSession extends IOSession {
|
||||
writeMessage(msg) {
|
||||
const verboseLogging = logger.hasLevel(typescript_exports.server.LogLevel.verbose);
|
||||
if (verboseLogging) {
|
||||
const json = JSON.stringify(msg);
|
||||
logger.info(`${msg.type}:${typescript_exports.server.indent(json)}`);
|
||||
}
|
||||
process.send(msg);
|
||||
}
|
||||
parseMessage(message) {
|
||||
return message;
|
||||
}
|
||||
toStringMessage(message) {
|
||||
return JSON.stringify(message, void 0, 2);
|
||||
}
|
||||
listen() {
|
||||
process.on("message", (e) => {
|
||||
this.onMessage(e);
|
||||
});
|
||||
process.on("disconnect", () => {
|
||||
this.exit();
|
||||
});
|
||||
}
|
||||
}
|
||||
const eventPort = parseEventPort(typescript_exports.server.findArgument("--eventPort"));
|
||||
const typingSafeListLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.TypingSafeListLocation);
|
||||
const typesMapLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.TypesMapLocation) || (0, typescript_exports.combinePaths)((0, typescript_exports.getDirectoryPath)(typescript_exports.sys.getExecutingFilePath()), "typesMap.json");
|
||||
const npmLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.NpmLocation);
|
||||
const validateDefaultNpmLocation = typescript_exports.server.hasArgument(typescript_exports.server.Arguments.ValidateDefaultNpmLocation);
|
||||
const disableAutomaticTypingAcquisition = typescript_exports.server.hasArgument("--disableAutomaticTypingAcquisition");
|
||||
const useNodeIpc = typescript_exports.server.hasArgument("--useNodeIpc");
|
||||
const telemetryEnabled = typescript_exports.server.hasArgument(typescript_exports.server.Arguments.EnableTelemetry);
|
||||
const commandLineTraceDir = typescript_exports.server.findArgument("--traceDirectory");
|
||||
const traceDir = commandLineTraceDir ? (0, typescript_exports.stripQuotes)(commandLineTraceDir) : process.env.TSS_TRACE;
|
||||
if (traceDir) {
|
||||
(0, typescript_exports.startTracing)("server", traceDir);
|
||||
}
|
||||
const ioSession = useNodeIpc ? new IpcIOSession() : new IOSession();
|
||||
process.on("uncaughtException", (err) => {
|
||||
ioSession.logError(err, "unknown");
|
||||
});
|
||||
process.noAsar = true;
|
||||
ioSession.listen();
|
||||
function getGlobalTypingsCacheLocation() {
|
||||
switch (process.platform) {
|
||||
case "win32": {
|
||||
const basePath = process.env.LOCALAPPDATA || process.env.APPDATA || os.homedir && os.homedir() || process.env.USERPROFILE || process.env.HOMEDRIVE && process.env.HOMEPATH && (0, typescript_exports.normalizeSlashes)(process.env.HOMEDRIVE + process.env.HOMEPATH) || os.tmpdir();
|
||||
return (0, typescript_exports.combinePaths)((0, typescript_exports.combinePaths)((0, typescript_exports.normalizeSlashes)(basePath), "Microsoft/TypeScript"), typescript_exports.versionMajorMinor);
|
||||
}
|
||||
case "openbsd":
|
||||
case "freebsd":
|
||||
case "netbsd":
|
||||
case "darwin":
|
||||
case "linux":
|
||||
case "android": {
|
||||
const cacheLocation = getNonWindowsCacheLocation(process.platform === "darwin");
|
||||
return (0, typescript_exports.combinePaths)((0, typescript_exports.combinePaths)(cacheLocation, "typescript"), typescript_exports.versionMajorMinor);
|
||||
}
|
||||
default:
|
||||
return typescript_exports.Debug.fail(`unsupported platform '${process.platform}'`);
|
||||
}
|
||||
}
|
||||
function getNonWindowsCacheLocation(platformIsDarwin) {
|
||||
if (process.env.XDG_CACHE_HOME) {
|
||||
return process.env.XDG_CACHE_HOME;
|
||||
}
|
||||
const usersDir = platformIsDarwin ? "Users" : "home";
|
||||
const homePath = os.homedir && os.homedir() || process.env.HOME || (process.env.LOGNAME || process.env.USER) && `/${usersDir}/${process.env.LOGNAME || process.env.USER}` || os.tmpdir();
|
||||
const cacheFolder = platformIsDarwin ? "Library/Caches" : ".cache";
|
||||
return (0, typescript_exports.combinePaths)((0, typescript_exports.normalizeSlashes)(homePath), cacheFolder);
|
||||
}
|
||||
}
|
||||
|
||||
// src/tsserver/server.ts
|
||||
function findArgumentStringArray(argName) {
|
||||
const arg = typescript_exports.server.findArgument(argName);
|
||||
if (arg === void 0) {
|
||||
return typescript_exports.emptyArray;
|
||||
}
|
||||
return arg.split(",").filter((name) => name !== "");
|
||||
}
|
||||
function start({ args, logger, cancellationToken, serverMode, unknownServerMode, startSession: startServer }, platform) {
|
||||
logger.info(`Starting TS Server`);
|
||||
logger.info(`Version: ${typescript_exports.version}`);
|
||||
logger.info(`Arguments: ${args.join(" ")}`);
|
||||
logger.info(`Platform: ${platform} NodeVersion: ${process.version} CaseSensitive: ${typescript_exports.sys.useCaseSensitiveFileNames}`);
|
||||
logger.info(`ServerMode: ${serverMode} hasUnknownServerMode: ${unknownServerMode}`);
|
||||
typescript_exports.setStackTraceLimit();
|
||||
if (typescript_exports.Debug.isDebugging) {
|
||||
typescript_exports.Debug.enableDebugInfo();
|
||||
}
|
||||
if (typescript_exports.sys.tryEnableSourceMapsForHost && /^development$/i.test(typescript_exports.sys.getEnvironmentVariable("NODE_ENV"))) {
|
||||
typescript_exports.sys.tryEnableSourceMapsForHost();
|
||||
}
|
||||
console.log = (...args2) => logger.msg(args2.length === 1 ? args2[0] : args2.join(", "), typescript_exports.server.Msg.Info);
|
||||
console.warn = (...args2) => logger.msg(args2.length === 1 ? args2[0] : args2.join(", "), typescript_exports.server.Msg.Err);
|
||||
console.error = (...args2) => logger.msg(args2.length === 1 ? args2[0] : args2.join(", "), typescript_exports.server.Msg.Err);
|
||||
startServer(
|
||||
{
|
||||
globalPlugins: findArgumentStringArray("--globalPlugins"),
|
||||
pluginProbeLocations: findArgumentStringArray("--pluginProbeLocations"),
|
||||
allowLocalPluginLoads: typescript_exports.server.hasArgument("--allowLocalPluginLoads"),
|
||||
useSingleInferredProject: typescript_exports.server.hasArgument("--useSingleInferredProject"),
|
||||
useInferredProjectPerProjectRoot: typescript_exports.server.hasArgument("--useInferredProjectPerProjectRoot"),
|
||||
suppressDiagnosticEvents: typescript_exports.server.hasArgument("--suppressDiagnosticEvents"),
|
||||
noGetErrOnBackgroundUpdate: typescript_exports.server.hasArgument("--noGetErrOnBackgroundUpdate"),
|
||||
canUseWatchEvents: typescript_exports.server.hasArgument("--canUseWatchEvents"),
|
||||
serverMode
|
||||
},
|
||||
logger,
|
||||
cancellationToken
|
||||
);
|
||||
}
|
||||
typescript_exports.setStackTraceLimit();
|
||||
start(initializeNodeSystem(), require("os").platform());
|
||||
//# sourceMappingURL=tsserver.js.map
|
||||
@@ -0,0 +1,194 @@
|
||||
export class Buffer extends Uint8Array {
|
||||
length: number
|
||||
write(string: string, offset?: number, length?: number, encoding?: string): number;
|
||||
toString(encoding?: string, start?: number, end?: number): string;
|
||||
toJSON(): { type: 'Buffer', data: any[] };
|
||||
equals(otherBuffer: Buffer): boolean;
|
||||
compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number;
|
||||
copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
|
||||
slice(start?: number, end?: number): Buffer;
|
||||
writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readUInt8(offset: number, noAssert?: boolean): number;
|
||||
readUInt16LE(offset: number, noAssert?: boolean): number;
|
||||
readUInt16BE(offset: number, noAssert?: boolean): number;
|
||||
readUInt32LE(offset: number, noAssert?: boolean): number;
|
||||
readUInt32BE(offset: number, noAssert?: boolean): number;
|
||||
readBigUInt64LE(offset: number): BigInt;
|
||||
readBigUInt64BE(offset: number): BigInt;
|
||||
readInt8(offset: number, noAssert?: boolean): number;
|
||||
readInt16LE(offset: number, noAssert?: boolean): number;
|
||||
readInt16BE(offset: number, noAssert?: boolean): number;
|
||||
readInt32LE(offset: number, noAssert?: boolean): number;
|
||||
readInt32BE(offset: number, noAssert?: boolean): number;
|
||||
readBigInt64LE(offset: number): BigInt;
|
||||
readBigInt64BE(offset: number): BigInt;
|
||||
readFloatLE(offset: number, noAssert?: boolean): number;
|
||||
readFloatBE(offset: number, noAssert?: boolean): number;
|
||||
readDoubleLE(offset: number, noAssert?: boolean): number;
|
||||
readDoubleBE(offset: number, noAssert?: boolean): number;
|
||||
reverse(): this;
|
||||
swap16(): Buffer;
|
||||
swap32(): Buffer;
|
||||
swap64(): Buffer;
|
||||
writeUInt8(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeBigUInt64LE(value: number, offset: number): BigInt;
|
||||
writeBigUInt64BE(value: number, offset: number): BigInt;
|
||||
writeInt8(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeBigInt64LE(value: number, offset: number): BigInt;
|
||||
writeBigInt64BE(value: number, offset: number): BigInt;
|
||||
writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
|
||||
fill(value: any, offset?: number, end?: number): this;
|
||||
indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
|
||||
lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
|
||||
includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
|
||||
|
||||
/**
|
||||
* Allocates a new buffer containing the given {str}.
|
||||
*
|
||||
* @param str String to store in buffer.
|
||||
* @param encoding encoding to use, optional. Default is 'utf8'
|
||||
*/
|
||||
constructor (str: string, encoding?: string);
|
||||
/**
|
||||
* Allocates a new buffer of {size} octets.
|
||||
*
|
||||
* @param size count of octets to allocate.
|
||||
*/
|
||||
constructor (size: number);
|
||||
/**
|
||||
* Allocates a new buffer containing the given {array} of octets.
|
||||
*
|
||||
* @param array The octets to store.
|
||||
*/
|
||||
constructor (array: Uint8Array);
|
||||
/**
|
||||
* Produces a Buffer backed by the same allocated memory as
|
||||
* the given {ArrayBuffer}.
|
||||
*
|
||||
*
|
||||
* @param arrayBuffer The ArrayBuffer with which to share memory.
|
||||
*/
|
||||
constructor (arrayBuffer: ArrayBuffer);
|
||||
/**
|
||||
* Allocates a new buffer containing the given {array} of octets.
|
||||
*
|
||||
* @param array The octets to store.
|
||||
*/
|
||||
constructor (array: any[]);
|
||||
/**
|
||||
* Copies the passed {buffer} data onto a new {Buffer} instance.
|
||||
*
|
||||
* @param buffer The buffer to copy.
|
||||
*/
|
||||
constructor (buffer: Buffer);
|
||||
prototype: Buffer;
|
||||
/**
|
||||
* Allocates a new Buffer using an {array} of octets.
|
||||
*
|
||||
* @param array
|
||||
*/
|
||||
static from(array: any[]): Buffer;
|
||||
/**
|
||||
* When passed a reference to the .buffer property of a TypedArray instance,
|
||||
* the newly created Buffer will share the same allocated memory as the TypedArray.
|
||||
* The optional {byteOffset} and {length} arguments specify a memory range
|
||||
* within the {arrayBuffer} that will be shared by the Buffer.
|
||||
*
|
||||
* @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer()
|
||||
* @param byteOffset
|
||||
* @param length
|
||||
*/
|
||||
static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer;
|
||||
/**
|
||||
* Copies the passed {buffer} data onto a new Buffer instance.
|
||||
*
|
||||
* @param buffer
|
||||
*/
|
||||
static from(buffer: Buffer | Uint8Array): Buffer;
|
||||
/**
|
||||
* Creates a new Buffer containing the given JavaScript string {str}.
|
||||
* If provided, the {encoding} parameter identifies the character encoding.
|
||||
* If not provided, {encoding} defaults to 'utf8'.
|
||||
*
|
||||
* @param str
|
||||
*/
|
||||
static from(str: string, encoding?: string): Buffer;
|
||||
/**
|
||||
* Returns true if {obj} is a Buffer
|
||||
*
|
||||
* @param obj object to test.
|
||||
*/
|
||||
static isBuffer(obj: any): obj is Buffer;
|
||||
/**
|
||||
* Returns true if {encoding} is a valid encoding argument.
|
||||
* Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
|
||||
*
|
||||
* @param encoding string to test.
|
||||
*/
|
||||
static isEncoding(encoding: string): boolean;
|
||||
/**
|
||||
* Gives the actual byte length of a string. encoding defaults to 'utf8'.
|
||||
* This is not the same as String.prototype.length since that returns the number of characters in a string.
|
||||
*
|
||||
* @param string string to test.
|
||||
* @param encoding encoding used to evaluate (defaults to 'utf8')
|
||||
*/
|
||||
static byteLength(string: string, encoding?: string): number;
|
||||
/**
|
||||
* Returns a buffer which is the result of concatenating all the buffers in the list together.
|
||||
*
|
||||
* If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.
|
||||
* If the list has exactly one item, then the first item of the list is returned.
|
||||
* If the list has more than one item, then a new Buffer is created.
|
||||
*
|
||||
* @param list An array of Buffer objects to concatenate
|
||||
* @param totalLength Total length of the buffers when concatenated.
|
||||
* If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.
|
||||
*/
|
||||
static concat(list: Uint8Array[], totalLength?: number): Buffer;
|
||||
/**
|
||||
* The same as buf1.compare(buf2).
|
||||
*/
|
||||
static compare(buf1: Uint8Array, buf2: Uint8Array): number;
|
||||
/**
|
||||
* Allocates a new buffer of {size} octets.
|
||||
*
|
||||
* @param size count of octets to allocate.
|
||||
* @param fill if specified, buffer will be initialized by calling buf.fill(fill).
|
||||
* If parameter is omitted, buffer will be filled with zeros.
|
||||
* @param encoding encoding used for call to buf.fill while initializing
|
||||
*/
|
||||
static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer;
|
||||
/**
|
||||
* Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents
|
||||
* of the newly created Buffer are unknown and may contain sensitive data.
|
||||
*
|
||||
* @param size count of octets to allocate
|
||||
*/
|
||||
static allocUnsafe(size: number): Buffer;
|
||||
/**
|
||||
* Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents
|
||||
* of the newly created Buffer are unknown and may contain sensitive data.
|
||||
*
|
||||
* @param size count of octets to allocate
|
||||
*/
|
||||
static allocUnsafeSlow(size: number): Buffer;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
'use strict';
|
||||
|
||||
const OriginalHttpsAgent = require('https').Agent;
|
||||
const HttpAgent = require('./agent');
|
||||
const {
|
||||
INIT_SOCKET,
|
||||
CREATE_HTTPS_CONNECTION,
|
||||
} = require('./constants');
|
||||
|
||||
class HttpsAgent extends HttpAgent {
|
||||
constructor(options) {
|
||||
super(options);
|
||||
|
||||
this.defaultPort = 443;
|
||||
this.protocol = 'https:';
|
||||
this.maxCachedSessions = this.options.maxCachedSessions;
|
||||
/* istanbul ignore next */
|
||||
if (this.maxCachedSessions === undefined) {
|
||||
this.maxCachedSessions = 100;
|
||||
}
|
||||
|
||||
this._sessionCache = {
|
||||
map: {},
|
||||
list: [],
|
||||
};
|
||||
}
|
||||
|
||||
createConnection(options, oncreate) {
|
||||
const socket = this[CREATE_HTTPS_CONNECTION](options, oncreate);
|
||||
this[INIT_SOCKET](socket, options);
|
||||
return socket;
|
||||
}
|
||||
}
|
||||
|
||||
// https://github.com/nodejs/node/blob/master/lib/https.js#L89
|
||||
HttpsAgent.prototype[CREATE_HTTPS_CONNECTION] = OriginalHttpsAgent.prototype.createConnection;
|
||||
|
||||
[
|
||||
'getName',
|
||||
'_getSession',
|
||||
'_cacheSession',
|
||||
// https://github.com/nodejs/node/pull/4982
|
||||
'_evictSession',
|
||||
].forEach(function(method) {
|
||||
/* istanbul ignore next */
|
||||
if (typeof OriginalHttpsAgent.prototype[method] === 'function') {
|
||||
HttpsAgent.prototype[method] = OriginalHttpsAgent.prototype[method];
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = HttpsAgent;
|
||||
Reference in New Issue
Block a user