UNPKG

lakutata

Version:

An IoC-based universal application framework.

1,468 lines (1,426 loc) 181 kB
/// <reference types="node" /> import './vendor/TypeDef.2.js'; import { PathLike } from 'fs'; import { I as IConstructor } from './vendor/TypeDef.11.js'; import { PathLike as PathLike$1, Dirent, Stats } from 'node:fs'; import { ReadableOptions, Readable } from 'node:stream'; import { win32, posix } from 'node:path'; import { EventEmitter } from 'node:events'; import { StringDecoder } from 'node:string_decoder'; /** * Convert Array to Set * @param arr * @constructor */ declare function ArrayToSet<T = any>(arr: T[]): Set<T>; /** * Type conversion * @param inp * @constructor */ declare function As<T = any>(inp: any): T; /** * Async delay function * @param ms * @constructor */ declare function Delay(ms: number): Promise<void>; /** * Just accept arguments * @param args * @constructor */ declare function DevNull(...args: any[]): void; /** * Get object's nesting depth * @param target * @constructor */ declare function GetObjectNestingDepth(target: Object): number; /** * Get all property paths in an object * @param target * @param basePath * @constructor */ declare function GetObjectPropertyPaths(target: Record<string, any>, basePath?: string): string[]; /** * Terminate program graceful * @param exitCode * @param functions * @constructor */ declare function GraceExit(exitCode: number, ...functions: (() => any)[]): void; /** * Whether an object is empty object or not * @param obj * @constructor */ declare function IsEmptyObject<T = any>(obj: T): boolean; /** * Returns `true` if the path exists, `false` otherwise. * @param path * @constructor */ declare function IsExists(path: PathLike): Promise<boolean>; /** * Whether a string is glob string or not * @param inp * @constructor */ declare function IsGlobString(inp: string): boolean; /** * Whether string is html * @param string * @constructor */ declare function IsHtml(string: string): boolean; /** * Whether a function is native function or not * @param target * @constructor */ declare function IsNativeFunction(target: any): boolean; /** * Whether an object is Promise object or not * @param target */ declare function IsPromise(target: any): boolean; /** * Whether an object is PromiseLike object or not * @param target * @constructor */ declare function IsPromiseLike(target: any): boolean; /** * Whether input value is symbol * @param inp * @constructor */ declare function IsSymbol(inp: any): boolean; /** * Whether string is XML * @param string * @constructor */ declare function IsXML(string: string): boolean; type Locale = string[] | string | false | undefined; interface SplitOptions { separateNumbers?: boolean; } interface NoCaseOptions extends SplitOptions { locale?: Locale; } /** * Convert any string into a lower case string with spaces between words. */ declare function NoCase(input: string, options?: NoCaseOptions): string; /** * Split any cased input strings into an array of words. */ declare function Split(input: string, options?: SplitOptions): string[]; declare function ToLower(locale: Locale): (input: string) => string; declare function ToUpper(locale: Locale): (input: string) => string; /** * Get object's constructor by its prototype * @param target * @constructor */ declare function ObjectConstructor<ObjectPrototype extends Object>(target: ObjectPrototype): IConstructor<ObjectPrototype>; type HashName = 'md4' | 'md4WithRSAEncryption' | 'md5' | 'md5WithRSAEncryption' | 'ripemd' | 'ripemd160' | 'ripemd160WithRSA' | 'rmd160' | 'rsa-md4' | 'rsa-md5' | 'rsa-ripemd160' | 'rsa-sha1' | 'rsa-sha1-2' | 'rsa-sha224' | 'rsa-sha256' | 'rsa-sha3-224' | 'rsa-sha3-256' | 'rsa-sha3-384' | 'rsa-sha3-512' | 'rsa-sha384' | 'rsa-sha512' | 'sha1' | 'sha1WithRSAEncryption' | 'sha224' | 'sha224WithRSAEncryption' | 'sha256' | 'sha256WithRSAEncryption' | 'sha3-224' | 'sha3-256' | 'sha3-384' | 'sha3-512' | 'sha384' | 'sha384WithRSAEncryption' | 'sha512' | 'sha512WithRSAEncryption'; type ObjectHashOptions = { /** * @default 'hex' */ encoding?: 'hex' | 'binary' | 'base64' | undefined; /** * @default 'sha1' */ algorithm?: HashName | 'passthrough' | undefined; excludeKeys?: ((key: string) => boolean) | undefined; /** * @default false */ excludeValues?: boolean | undefined; /** * @default false */ ignoreUnknown?: boolean | undefined; replacer?: ((value: any) => any) | undefined; /** * @default true */ respectFunctionNames?: boolean | undefined; /** * @default true */ respectFunctionProperties?: boolean | undefined; /** * @default true */ respectType?: boolean | undefined; /** * @default false */ unorderedArrays?: boolean | undefined; /** * @default true */ unorderedObjects?: boolean | undefined; /** * @default true */ unorderedSets?: boolean | undefined; }; /** * Generate an object hash * @param value * @param options * @constructor */ declare function ObjectHash(value: any, options?: ObjectHashOptions): string; /** * Get class's parent constructor * @param target * @constructor */ declare function ObjectParentConstructor<ClassConstructor extends Function>(target: ClassConstructor): Function | null; declare function ObjectParentConstructor<ClassPrototype extends Object>(target: IConstructor<ClassPrototype>): Function | null; /** * Get class's parent constructors * @param target * @constructor */ declare function ObjectParentConstructors<ClassConstructor extends Function>(target: ClassConstructor): Function[]; declare function ObjectParentConstructors<ClassPrototype extends Object>(target: IConstructor<ClassPrototype>): Function[]; type InferPrototype<ObjectConstruct extends Function> = ObjectConstruct extends new (...args: any[]) => infer ObjectPrototype ? ObjectPrototype : never; /** * Get object's prototype by its constructor * @param target * @constructor */ declare function ObjectPrototype<ObjectConstruct extends Function>(target: ObjectConstruct): InferPrototype<ObjectConstruct>; /** * Convert Set to Array * @param set * @constructor */ declare function SetToArray<T = any>(set: Set<T>): T[]; declare class MissingValueError extends Error { key: string; constructor(key: string); } interface TemplatingOptions { ignoreMissing?: boolean; transform?: ({ value, key }: { value: any; key: string; }) => any; } declare function Templating(template: string, data: object | any[], { ignoreMissing, transform }?: TemplatingOptions): string; /** * Unique array * @param arr * @constructor */ declare function UniqueArray<T>(arr: T[]): T[]; /** * Convert object to map * @param obj * @constructor */ declare function ObjectToMap<K extends (string | number | symbol), V>(obj: Record<K, V>): Map<K, V>; /** * Whether input string is path or not * @param inp * @constructor */ declare function IsPath(inp: string | PathLike$1): boolean; /** * Convert array-like input to iterable * @param inp * @constructor */ declare function ConvertArrayLikeToIterable(inp: string | Buffer | NodeJS.TypedArray): Generator; /** * Convert buffer to readable stream * @param inp * @param options * @constructor */ declare function ConvertArrayLikeToStream(inp: Buffer, options?: ReadableOptions): Readable; /** * Convert typed-array to readable stream * @param inp * @param options * @constructor */ declare function ConvertArrayLikeToStream(inp: NodeJS.TypedArray, options?: ReadableOptions): Readable; /** * Convert string to readable stream * @param inp * @param options * @constructor */ declare function ConvertArrayLikeToStream(inp: string, options?: ReadableOptions): Readable; /** * Merge two set * @param s1 * @param s2 * @constructor */ declare function MergeSet<T = any, U = any>(s1: Set<T>, s2: Set<U>): Set<T | U>; /** * Merge two array * @param arr1 * @param arr2 * @constructor */ declare function MergeArray<T = any, U = any>(arr1: T[], arr2: U[]): (T | U)[]; /** * Merge two map * @param m1 * @param m2 * @constructor */ declare function MergeMap<K1, V1, K2, V2>(m1: Map<K1, V1>, m2: Map<K2, V2>): Map<K1 | K2, V1 | V2>; interface SortOptions<Computed> { /** * One or more property names or computed fields to sort by. * Specifying property names is only relevant when sorting an array of * objects. */ by?: string | string[]; /** * One or more sort orders. Specify 'asc', 'desc' or a property name from * the options.customOrders object. */ order?: string | string[]; /** * A dictionary object containing one or more custom orders. Each custom * order value must be an array defining the order expected values must be * sorted in. */ customOrders?: { [key: string]: any; }; /** * A dictionary object containing one or more computed field functions. The * function will be invoked once per item in the array. Each invocation * will receive the array item as input and must return a primitive value * by which the array can be sorted. */ computed?: { [key: string]: (item: Computed) => number | string | boolean | bigint | symbol | null | undefined; }; /** * Configures whether null values will be sorted before or after defined * values. Set to -1 for before, 1 for after. Defaults to 1. * @default 1 */ nullRank?: -1 | 1; /** * Configures whether undefined values will be sorted before or after * defined values. Set to -1 for before, 1 for after. Defaults to 1. * @default 1 */ undefinedRank?: -1 | 1; } /** * Sort array * @param arr * @param options * @constructor */ declare function SortArray<T = any>(arr: T[], ...options: SortOptions<T>[]): T[]; /** * Sort keys options */ interface SortKeysOptions { deep?: boolean; compare?: (a: string, b: string) => number; } /** * Sort keys * @param object * @param options * @constructor */ declare function SortKeys(object: any, options?: SortKeysOptions): any; /** * Sort keys options */ interface SortObjectOptions { deep?: boolean; order?: 'asc' | 'desc'; } /** * Sort object * @param object * @param options * @constructor */ declare function SortObject<T extends Record<string, any>>(object: T, options?: SortObjectOptions): T; /** * Generate a random string * @constructor */ declare function RandomString(): string; /** * Generate a random string of specified length * @param length * @constructor */ declare function RandomString(length: number): string; /** * Generates a string of specified length containing only characters within the character set * @param length * @param charset * @constructor */ declare function RandomString(length: number, charset: string): string; /** * Generate a string of specified length containing only [0-9 a-z A-Z] * @param length * @param charset * @constructor */ declare function RandomString(length: number, charset: 'alphanumeric'): string; /** * Generate a string of specified length containing only [a-z A-Z] * @param length * @param charset * @constructor */ declare function RandomString(length: number, charset: 'alphabetic'): string; /** * Generate a string of specified length containing only [0-9] * @param length * @param charset * @constructor */ declare function RandomString(length: number, charset: 'numeric'): string; /** * Generate a string of specified length containing only [0-9 a-f] * @param length * @param charset * @constructor */ declare function RandomString(length: number, charset: 'hex'): string; /** * Generate a string of specified length containing only [01] * @param length * @param charset * @constructor */ declare function RandomString(length: number, charset: 'binary'): string; /** * Generate a string of specified length containing only [0-7] * @param length * @param charset * @constructor */ declare function RandomString(length: number, charset: 'octal'): string; /** * Generates a string of specified length containing only character rules within the character set array * @param length * @param charset * @constructor */ declare function RandomString(length: number, charset: ('alphanumeric' | 'alphabetic' | 'numeric' | 'hex' | 'binary' | 'octal' | string)[]): string; /** * Generate a random string of length 32 * @constructor */ declare function NonceStr(): string; /** * Is abort error * @param error * @constructor */ declare function IsAbortError(error: Error | any): boolean; /** * Same as StringDecoder, but exposing the `lastNeed` flag on the type */ type SD = StringDecoder & { lastNeed: boolean; }; declare const EOF: unique symbol; declare const MAYBE_EMIT_END: unique symbol; declare const EMITTED_END: unique symbol; declare const EMITTING_END: unique symbol; declare const EMITTED_ERROR: unique symbol; declare const CLOSED: unique symbol; declare const READ: unique symbol; declare const FLUSH: unique symbol; declare const FLUSHCHUNK: unique symbol; declare const ENCODING: unique symbol; declare const DECODER: unique symbol; declare const FLOWING: unique symbol; declare const PAUSED: unique symbol; declare const RESUME: unique symbol; declare const BUFFER: unique symbol; declare const PIPES: unique symbol; declare const BUFFERLENGTH: unique symbol; declare const BUFFERPUSH: unique symbol; declare const BUFFERSHIFT: unique symbol; declare const OBJECTMODE: unique symbol; declare const DESTROYED: unique symbol; declare const ERROR: unique symbol; declare const EMITDATA: unique symbol; declare const EMITEND: unique symbol; declare const EMITEND2: unique symbol; declare const ASYNC: unique symbol; declare const ABORT: unique symbol; declare const ABORTED: unique symbol; declare const SIGNAL: unique symbol; declare const DATALISTENERS: unique symbol; declare const DISCARDED: unique symbol; /** * Options that may be passed to stream.pipe() */ interface PipeOptions { /** * end the destination stream when the source stream ends */ end?: boolean; /** * proxy errors from the source stream to the destination stream */ proxyErrors?: boolean; } /** * Internal class representing a pipe to a destination stream. * * @internal */ declare class Pipe<T extends unknown> { src: Minipass<T>; dest: Minipass<any, T>; opts: PipeOptions; ondrain: () => any; constructor(src: Minipass<T>, dest: Minipass.Writable, opts: PipeOptions); unpipe(): void; proxyErrors(_er: any): void; end(): void; } declare namespace Minipass { /** * Encoding used to create a stream that outputs strings rather than * Buffer objects. */ export type Encoding = BufferEncoding | 'buffer' | null; /** * Any stream that Minipass can pipe into */ export type Writable = Minipass<any, any, any> | NodeJS.WriteStream | (NodeJS.WriteStream & { fd: number; }) | (EventEmitter & { end(): any; write(chunk: any, ...args: any[]): any; }); /** * Any stream that can be read from */ export type Readable = Minipass<any, any, any> | NodeJS.ReadStream | (NodeJS.ReadStream & { fd: number; }) | (EventEmitter & { pause(): any; resume(): any; pipe(...destArgs: any[]): any; }); /** * Utility type that can be iterated sync or async */ export type DualIterable<T> = Iterable<T> & AsyncIterable<T>; type EventArguments = Record<string | symbol, unknown[]>; /** * The listing of events that a Minipass class can emit. * Extend this when extending the Minipass class, and pass as * the third template argument. The key is the name of the event, * and the value is the argument list. * * Any undeclared events will still be allowed, but the handler will get * arguments as `unknown[]`. */ export interface Events<RType extends any = Buffer> extends EventArguments { readable: []; data: [chunk: RType]; error: [er: unknown]; abort: [reason: unknown]; drain: []; resume: []; end: []; finish: []; prefinish: []; close: []; [DESTROYED]: [er?: unknown]; [ERROR]: [er: unknown]; } /** * String or buffer-like data that can be joined and sliced */ export type ContiguousData = Buffer | ArrayBufferLike | ArrayBufferView | string; export type BufferOrString = Buffer | string; /** * Options passed to the Minipass constructor. */ export type SharedOptions = { /** * Defer all data emission and other events until the end of the * current tick, similar to Node core streams */ async?: boolean; /** * A signal which will abort the stream */ signal?: AbortSignal; /** * Output string encoding. Set to `null` or `'buffer'` (or omit) to * emit Buffer objects rather than strings. * * Conflicts with `objectMode` */ encoding?: BufferEncoding | null | 'buffer'; /** * Output data exactly as it was written, supporting non-buffer/string * data (such as arbitrary objects, falsey values, etc.) * * Conflicts with `encoding` */ objectMode?: boolean; }; /** * Options for a string encoded output */ export type EncodingOptions = SharedOptions & { encoding: BufferEncoding; objectMode?: false; }; /** * Options for contiguous data buffer output */ export type BufferOptions = SharedOptions & { encoding?: null | 'buffer'; objectMode?: false; }; /** * Options for objectMode arbitrary output */ export type ObjectModeOptions = SharedOptions & { objectMode: true; encoding?: null; }; /** * Utility type to determine allowed options based on read type */ export type Options<T> = ObjectModeOptions | (T extends string ? EncodingOptions : T extends Buffer ? BufferOptions : SharedOptions); export {}; } /** * Main export, the Minipass class * * `RType` is the type of data emitted, defaults to Buffer * * `WType` is the type of data to be written, if RType is buffer or string, * then any {@link Minipass.ContiguousData} is allowed. * * `Events` is the set of event handler signatures that this object * will emit, see {@link Minipass.Events} */ declare class Minipass<RType extends unknown = Buffer, WType extends unknown = RType extends Minipass.BufferOrString ? Minipass.ContiguousData : RType, Events extends Minipass.Events<RType> = Minipass.Events<RType>> extends EventEmitter implements Minipass.DualIterable<RType> { [FLOWING]: boolean; [PAUSED]: boolean; [PIPES]: Pipe<RType>[]; [BUFFER]: RType[]; [OBJECTMODE]: boolean; [ENCODING]: BufferEncoding | null; [ASYNC]: boolean; [DECODER]: SD | null; [EOF]: boolean; [EMITTED_END]: boolean; [EMITTING_END]: boolean; [CLOSED]: boolean; [EMITTED_ERROR]: unknown; [BUFFERLENGTH]: number; [DESTROYED]: boolean; [SIGNAL]?: AbortSignal; [ABORTED]: boolean; [DATALISTENERS]: number; [DISCARDED]: boolean; /** * true if the stream can be written */ writable: boolean; /** * true if the stream can be read */ readable: boolean; /** * If `RType` is Buffer, then options do not need to be provided. * Otherwise, an options object must be provided to specify either * {@link Minipass.SharedOptions.objectMode} or * {@link Minipass.SharedOptions.encoding}, as appropriate. */ constructor(...args: [Minipass.ObjectModeOptions] | (RType extends Buffer ? [] | [Minipass.Options<RType>] : [Minipass.Options<RType>])); /** * The amount of data stored in the buffer waiting to be read. * * For Buffer strings, this will be the total byte length. * For string encoding streams, this will be the string character length, * according to JavaScript's `string.length` logic. * For objectMode streams, this is a count of the items waiting to be * emitted. */ get bufferLength(): number; /** * The `BufferEncoding` currently in use, or `null` */ get encoding(): BufferEncoding | null; /** * @deprecated - This is a read only property */ set encoding(_enc: BufferEncoding | null); /** * @deprecated - Encoding may only be set at instantiation time */ setEncoding(_enc: Minipass.Encoding): void; /** * True if this is an objectMode stream */ get objectMode(): boolean; /** * @deprecated - This is a read-only property */ set objectMode(_om: boolean); /** * true if this is an async stream */ get ['async'](): boolean; /** * Set to true to make this stream async. * * Once set, it cannot be unset, as this would potentially cause incorrect * behavior. Ie, a sync stream can be made async, but an async stream * cannot be safely made sync. */ set ['async'](a: boolean); [ABORT](): void; /** * True if the stream has been aborted. */ get aborted(): boolean; /** * No-op setter. Stream aborted status is set via the AbortSignal provided * in the constructor options. */ set aborted(_: boolean); /** * Write data into the stream * * If the chunk written is a string, and encoding is not specified, then * `utf8` will be assumed. If the stream encoding matches the encoding of * a written string, and the state of the string decoder allows it, then * the string will be passed through to either the output or the internal * buffer without any processing. Otherwise, it will be turned into a * Buffer object for processing into the desired encoding. * * If provided, `cb` function is called immediately before return for * sync streams, or on next tick for async streams, because for this * base class, a chunk is considered "processed" once it is accepted * and either emitted or buffered. That is, the callback does not indicate * that the chunk has been eventually emitted, though of course child * classes can override this function to do whatever processing is required * and call `super.write(...)` only once processing is completed. */ write(chunk: WType, cb?: () => void): boolean; write(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): boolean; /** * Low-level explicit read method. * * In objectMode, the argument is ignored, and one item is returned if * available. * * `n` is the number of bytes (or in the case of encoding streams, * characters) to consume. If `n` is not provided, then the entire buffer * is returned, or `null` is returned if no data is available. * * If `n` is greater that the amount of data in the internal buffer, * then `null` is returned. */ read(n?: number | null): RType | null; [READ](n: number | null, chunk: RType): RType; /** * End the stream, optionally providing a final write. * * See {@link Minipass#write} for argument descriptions */ end(cb?: () => void): this; end(chunk: WType, cb?: () => void): this; end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this; [RESUME](): void; /** * Resume the stream if it is currently in a paused state * * If called when there are no pipe destinations or `data` event listeners, * this will place the stream in a "discarded" state, where all data will * be thrown away. The discarded state is removed if a pipe destination or * data handler is added, if pause() is called, or if any synchronous or * asynchronous iteration is started. */ resume(): void; /** * Pause the stream */ pause(): void; /** * true if the stream has been forcibly destroyed */ get destroyed(): boolean; /** * true if the stream is currently in a flowing state, meaning that * any writes will be immediately emitted. */ get flowing(): boolean; /** * true if the stream is currently in a paused state */ get paused(): boolean; [BUFFERPUSH](chunk: RType): void; [BUFFERSHIFT](): RType; [FLUSH](noDrain?: boolean): void; [FLUSHCHUNK](chunk: RType): boolean; /** * Pipe all data emitted by this stream into the destination provided. * * Triggers the flow of data. */ pipe<W extends Minipass.Writable>(dest: W, opts?: PipeOptions): W; /** * Fully unhook a piped destination stream. * * If the destination stream was the only consumer of this stream (ie, * there are no other piped destinations or `'data'` event listeners) * then the flow of data will stop until there is another consumer or * {@link Minipass#resume} is explicitly called. */ unpipe<W extends Minipass.Writable>(dest: W): void; /** * Alias for {@link Minipass#on} */ addListener<Event extends keyof Events>(ev: Event, handler: (...args: Events[Event]) => any): this; /** * Mostly identical to `EventEmitter.on`, with the following * behavior differences to prevent data loss and unnecessary hangs: * * - Adding a 'data' event handler will trigger the flow of data * * - Adding a 'readable' event handler when there is data waiting to be read * will cause 'readable' to be emitted immediately. * * - Adding an 'endish' event handler ('end', 'finish', etc.) which has * already passed will cause the event to be emitted immediately and all * handlers removed. * * - Adding an 'error' event handler after an error has been emitted will * cause the event to be re-emitted immediately with the error previously * raised. */ on<Event extends keyof Events>(ev: Event, handler: (...args: Events[Event]) => any): this; /** * Alias for {@link Minipass#off} */ removeListener<Event extends keyof Events>(ev: Event, handler: (...args: Events[Event]) => any): this; /** * Mostly identical to `EventEmitter.off` * * If a 'data' event handler is removed, and it was the last consumer * (ie, there are no pipe destinations or other 'data' event listeners), * then the flow of data will stop until there is another consumer or * {@link Minipass#resume} is explicitly called. */ off<Event extends keyof Events>(ev: Event, handler: (...args: Events[Event]) => any): this; /** * Mostly identical to `EventEmitter.removeAllListeners` * * If all 'data' event handlers are removed, and they were the last consumer * (ie, there are no pipe destinations), then the flow of data will stop * until there is another consumer or {@link Minipass#resume} is explicitly * called. */ removeAllListeners<Event extends keyof Events>(ev?: Event): this; /** * true if the 'end' event has been emitted */ get emittedEnd(): boolean; [MAYBE_EMIT_END](): void; /** * Mostly identical to `EventEmitter.emit`, with the following * behavior differences to prevent data loss and unnecessary hangs: * * If the stream has been destroyed, and the event is something other * than 'close' or 'error', then `false` is returned and no handlers * are called. * * If the event is 'end', and has already been emitted, then the event * is ignored. If the stream is in a paused or non-flowing state, then * the event will be deferred until data flow resumes. If the stream is * async, then handlers will be called on the next tick rather than * immediately. * * If the event is 'close', and 'end' has not yet been emitted, then * the event will be deferred until after 'end' is emitted. * * If the event is 'error', and an AbortSignal was provided for the stream, * and there are no listeners, then the event is ignored, matching the * behavior of node core streams in the presense of an AbortSignal. * * If the event is 'finish' or 'prefinish', then all listeners will be * removed after emitting the event, to prevent double-firing. */ emit<Event extends keyof Events>(ev: Event, ...args: Events[Event]): boolean; [EMITDATA](data: RType): boolean; [EMITEND](): boolean; [EMITEND2](): boolean; /** * Return a Promise that resolves to an array of all emitted data once * the stream ends. */ collect(): Promise<RType[] & { dataLength: number; }>; /** * Return a Promise that resolves to the concatenation of all emitted data * once the stream ends. * * Not allowed on objectMode streams. */ concat(): Promise<RType>; /** * Return a void Promise that resolves once the stream ends. */ promise(): Promise<void>; /** * Asynchronous `for await of` iteration. * * This will continue emitting all chunks until the stream terminates. */ [Symbol.asyncIterator](): AsyncGenerator<RType, void, void>; /** * Synchronous `for of` iteration. * * The iteration will terminate when the internal buffer runs out, even * if the stream has not yet terminated. */ [Symbol.iterator](): Generator<RType, void, void>; /** * Destroy a stream, preventing it from being used for any further purpose. * * If the stream has a `close()` method, then it will be called on * destruction. * * After destruction, any attempt to write data, read data, or emit most * events will be ignored. * * If an error argument is provided, then it will be emitted in an * 'error' event. */ destroy(er?: unknown): this; /** * Alias for {@link isStream} * * Former export location, maintained for backwards compatibility. * * @deprecated */ static get isStream(): (s: any) => s is NodeJS.WriteStream | NodeJS.ReadStream | Minipass<any, any, any> | (NodeJS.ReadStream & { fd: number; }) | (EventEmitter & { pause(): any; resume(): any; pipe(...destArgs: any[]): any; }) | (NodeJS.WriteStream & { fd: number; }) | (EventEmitter & { end(): any; write(chunk: any, ...args: any[]): any; }); } /** * @module LRUCache */ declare const TYPE: unique symbol; type Index = number & { [TYPE]: 'LRUCache Index'; }; type UintArray = Uint8Array | Uint16Array | Uint32Array; type NumberArray = UintArray | number[]; declare class ZeroArray extends Array<number> { constructor(size: number); } type StackLike = Stack | Index[]; declare class Stack { #private; heap: NumberArray; length: number; static create(max: number): StackLike; constructor(max: number, HeapCls: { new (n: number): NumberArray; }); push(n: Index): void; pop(): Index; } /** * Promise representing an in-progress {@link LRUCache#fetch} call */ type BackgroundFetch<V> = Promise<V | undefined> & { __returned: BackgroundFetch<V> | undefined; __abortController: AbortController; __staleWhileFetching: V | undefined; }; declare namespace LRUCache { /** * An integer greater than 0, reflecting the calculated size of items */ type Size = number; /** * Integer greater than 0, representing some number of milliseconds, or the * time at which a TTL started counting from. */ type Milliseconds = number; /** * An integer greater than 0, reflecting a number of items */ type Count = number; /** * The reason why an item was removed from the cache, passed * to the {@link Disposer} methods. * * - `evict`: The item was evicted because it is the least recently used, * and the cache is full. * - `set`: A new value was set, overwriting the old value being disposed. * - `delete`: The item was explicitly deleted, either by calling * {@link LRUCache#delete}, {@link LRUCache#clear}, or * {@link LRUCache#set} with an undefined value. * - `expire`: The item was removed due to exceeding its TTL. * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned * `undefined` or was aborted, causing the item to be deleted. */ type DisposeReason = 'evict' | 'set' | 'delete' | 'expire' | 'fetch'; /** * A method called upon item removal, passed as the * {@link OptionsBase.dispose} and/or * {@link OptionsBase.disposeAfter} options. */ type Disposer<K, V> = (value: V, key: K, reason: DisposeReason) => void; /** * The reason why an item was added to the cache, passed * to the {@link Inserter} methods. * * - `add`: the item was not found in the cache, and was added * - `update`: the item was in the cache, with the same value provided * - `replace`: the item was in the cache, and replaced */ type InsertReason = 'add' | 'update' | 'replace'; /** * A method called upon item insertion, passed as the * {@link OptionsBase.insert} */ type Inserter<K, V> = (value: V, key: K, reason: InsertReason) => void; /** * A function that returns the effective calculated size * of an entry in the cache. */ type SizeCalculator<K, V> = (value: V, key: K) => Size; /** * Options provided to the * {@link OptionsBase.fetchMethod} function. */ interface FetcherOptions<K, V, FC = unknown> { signal: AbortSignal; options: FetcherFetchOptions<K, V, FC>; /** * Object provided in the {@link FetchOptions.context} option to * {@link LRUCache#fetch} */ context: FC; } /** * Occasionally, it may be useful to track the internal behavior of the * cache, particularly for logging, debugging, or for behavior within the * `fetchMethod`. To do this, you can pass a `status` object to the * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set}, * {@link LRUCache#memo}, and {@link LRUCache#has} methods. * * The `status` option should be a plain JavaScript object. The following * fields will be set on it appropriately, depending on the situation. */ interface Status<V> { /** * The status of a set() operation. * * - add: the item was not found in the cache, and was added * - update: the item was in the cache, with the same value provided * - replace: the item was in the cache, and replaced * - miss: the item was not added to the cache for some reason */ set?: 'add' | 'update' | 'replace' | 'miss'; /** * the ttl stored for the item, or undefined if ttls are not used. */ ttl?: Milliseconds; /** * the start time for the item, or undefined if ttls are not used. */ start?: Milliseconds; /** * The timestamp used for TTL calculation */ now?: Milliseconds; /** * the remaining ttl for the item, or undefined if ttls are not used. */ remainingTTL?: Milliseconds; /** * The calculated size for the item, if sizes are used. */ entrySize?: Size; /** * The total calculated size of the cache, if sizes are used. */ totalCalculatedSize?: Size; /** * A flag indicating that the item was not stored, due to exceeding the * {@link OptionsBase.maxEntrySize} */ maxEntrySizeExceeded?: true; /** * The old value, specified in the case of `set:'update'` or * `set:'replace'` */ oldValue?: V; /** * The results of a {@link LRUCache#has} operation * * - hit: the item was found in the cache * - stale: the item was found in the cache, but is stale * - miss: the item was not found in the cache */ has?: 'hit' | 'stale' | 'miss'; /** * The status of a {@link LRUCache#fetch} operation. * Note that this can change as the underlying fetch() moves through * various states. * * - inflight: there is another fetch() for this key which is in process * - get: there is no {@link OptionsBase.fetchMethod}, so * {@link LRUCache#get} was called. * - miss: the item is not in cache, and will be fetched. * - hit: the item is in the cache, and was resolved immediately. * - stale: the item is in the cache, but stale. * - refresh: the item is in the cache, and not stale, but * {@link FetchOptions.forceRefresh} was specified. */ fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'; /** * The {@link OptionsBase.fetchMethod} was called */ fetchDispatched?: true; /** * The cached value was updated after a successful call to * {@link OptionsBase.fetchMethod} */ fetchUpdated?: true; /** * The reason for a fetch() rejection. Either the error raised by the * {@link OptionsBase.fetchMethod}, or the reason for an * AbortSignal. */ fetchError?: Error; /** * The fetch received an abort signal */ fetchAborted?: true; /** * The abort signal received was ignored, and the fetch was allowed to * continue. */ fetchAbortIgnored?: true; /** * The fetchMethod promise resolved successfully */ fetchResolved?: true; /** * The fetchMethod promise was rejected */ fetchRejected?: true; /** * The status of a {@link LRUCache#get} operation. * * - fetching: The item is currently being fetched. If a previous value * is present and allowed, that will be returned. * - stale: The item is in the cache, and is stale. * - hit: the item is in the cache * - miss: the item is not in the cache */ get?: 'stale' | 'hit' | 'miss'; /** * A fetch or get operation returned a stale value. */ returnedStale?: true; } /** * options which override the options set in the LRUCache constructor * when calling {@link LRUCache#fetch}. * * This is the union of {@link GetOptions} and {@link SetOptions}, plus * {@link OptionsBase.noDeleteOnFetchRejection}, * {@link OptionsBase.allowStaleOnFetchRejection}, * {@link FetchOptions.forceRefresh}, and * {@link FetcherOptions.context} * * Any of these may be modified in the {@link OptionsBase.fetchMethod} * function, but the {@link GetOptions} fields will of course have no * effect, as the {@link LRUCache#get} call already happened by the time * the fetchMethod is called. */ interface FetcherFetchOptions<K, V, FC = unknown> extends Pick<OptionsBase<K, V, FC>, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' | 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL' | 'noDeleteOnFetchRejection' | 'allowStaleOnFetchRejection' | 'ignoreFetchAbort' | 'allowStaleOnFetchAbort'> { status?: Status<V>; size?: Size; } /** * Options that may be passed to the {@link LRUCache#fetch} method. */ interface FetchOptions<K, V, FC> extends FetcherFetchOptions<K, V, FC> { /** * Set to true to force a re-load of the existing data, even if it * is not yet stale. */ forceRefresh?: boolean; /** * Context provided to the {@link OptionsBase.fetchMethod} as * the {@link FetcherOptions.context} param. * * If the FC type is specified as unknown (the default), * undefined or void, then this is optional. Otherwise, it will * be required. */ context?: FC; signal?: AbortSignal; status?: Status<V>; } /** * Options provided to {@link LRUCache#fetch} when the FC type is something * other than `unknown`, `undefined`, or `void` */ interface FetchOptionsWithContext<K, V, FC> extends FetchOptions<K, V, FC> { context: FC; } /** * Options provided to {@link LRUCache#fetch} when the FC type is * `undefined` or `void` */ interface FetchOptionsNoContext<K, V> extends FetchOptions<K, V, undefined> { context?: undefined; } interface MemoOptions<K, V, FC = unknown> extends Pick<OptionsBase<K, V, FC>, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' | 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL' | 'noDeleteOnFetchRejection' | 'allowStaleOnFetchRejection' | 'ignoreFetchAbort' | 'allowStaleOnFetchAbort'> { /** * Set to true to force a re-load of the existing data, even if it * is not yet stale. */ forceRefresh?: boolean; /** * Context provided to the {@link OptionsBase.memoMethod} as * the {@link MemoizerOptions.context} param. * * If the FC type is specified as unknown (the default), * undefined or void, then this is optional. Otherwise, it will * be required. */ context?: FC; status?: Status<V>; } /** * Options provided to {@link LRUCache#memo} when the FC type is something * other than `unknown`, `undefined`, or `void` */ interface MemoOptionsWithContext<K, V, FC> extends MemoOptions<K, V, FC> { context: FC; } /** * Options provided to {@link LRUCache#memo} when the FC type is * `undefined` or `void` */ interface MemoOptionsNoContext<K, V> extends MemoOptions<K, V, undefined> { context?: undefined; } /** * Options provided to the * {@link OptionsBase.memoMethod} function. */ interface MemoizerOptions<K, V, FC = unknown> { options: MemoizerMemoOptions<K, V, FC>; /** * Object provided in the {@link MemoOptions.context} option to * {@link LRUCache#memo} */ context: FC; } /** * options which override the options set in the LRUCache constructor * when calling {@link LRUCache#memo}. * * This is the union of {@link GetOptions} and {@link SetOptions}, plus * {@link MemoOptions.forceRefresh}, and * {@link MemoOptions.context} * * Any of these may be modified in the {@link OptionsBase.memoMethod} * function, but the {@link GetOptions} fields will of course have no * effect, as the {@link LRUCache#get} call already happened by the time * the memoMethod is called. */ interface MemoizerMemoOptions<K, V, FC = unknown> extends Pick<OptionsBase<K, V, FC>, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' | 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'> { status?: Status<V>; size?: Size; start?: Milliseconds; } /** * Options that may be passed to the {@link LRUCache#has} method. */ interface HasOptions<K, V, FC> extends Pick<OptionsBase<K, V, FC>, 'updateAgeOnHas'> { status?: Status<V>; } /** * Options that may be passed to the {@link LRUCache#get} method. */ interface GetOptions<K, V, FC> extends Pick<OptionsBase<K, V, FC>, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'> { status?: Status<V>; } /** * Options that may be passed to the {@link LRUCache#peek} method. */ interface PeekOptions<K, V, FC> extends Pick<OptionsBase<K, V, FC>, 'allowStale'> { } /** * Options that may be passed to the {@link LRUCache#set} method. */ interface SetOptions<K, V, FC> extends Pick<OptionsBase<K, V, FC>, 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'> { /** * If size tracking is enabled, then setting an explicit size * in the {@link LRUCache#set} call will prevent calling the * {@link OptionsBase.sizeCalculation} function. */ size?: Size; /** * If TTL tracking is enabled, then setting an explicit start * time in the {@link LRUCache#set} call will override the * default time from `performance.now()` or `Date.now()`. * * Note that it must be a valid value for whichever time-tracking * method is in use. */ start?: Milliseconds; status?: Status<V>; } /** * The type signature for the {@link OptionsBase.fetchMethod} option. */ type Fetcher<K, V, FC = unknown> = (key: K, staleValue: V | undefined, options: FetcherOptions<K, V, FC>) => Promise<V | undefined | void> | V | undefined | void; /** * the type signature for the {@link OptionsBase.memoMethod} option. */ type Memoizer<K, V, FC = unknown> = (key: K, staleValue: V | undefined, options: MemoizerOptions<K, V, FC>) => V; /** * Options which may be passed to the {@link LRUCache} constructor. * * Most of these may be overridden in the various options that use * them. * * Despite all being technically optional, the constructor requires that * a cache is at minimum limited by one or more of {@link OptionsBase.max}, * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}. * * If {@link OptionsBase.ttl} is used alone, then it is strongly advised * (and in fact required by the type definitions here) that the cache * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially * unbounded storage. * * All options are also available on the {@link LRUCache} instance, making * it safe to pass an LRUCache instance as the options argumemnt to * make another empty cache of the same type. * * Some options are marked as read-only, because changing them after * instantiation is not safe. Changing any of the other options will of * course only have an effect on subsequent method calls. */ interface OptionsBase<K, V, FC> { /** * The maximum number of items to store in the cache before evicting * old entries. This is read-only on the {@link LRUCache} instance, * and may not be overridden. * * If set, then storage space will be pre-allocated at construction * time, and the cache will perform significantly faster. * * Note that significantly fewer items may be stored, if * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also * set. * * **It is strongly recommended to set a `max` to prevent unbounded growth * of the cache.** */ max?: Count; /** * Max time in milliseconds for items to live in cache before they are * considered stale. Note that stale items are NOT preemptively removed by * default, and MAY live in the cache, contributing to its LRU max, long * after they have expired, unless {@link OptionsBase.ttlAutopurge} is * set. * * If set to `0` (the default value), then that means "do not track * TTL", not "expire immediately". * * Also, as this cache is optimized for LRU/MRU operations, some of * the staleness/TTL checks will reduce performance, as they will incur * overhead by deleting items. * * This is not primarily a TTL cache, and does not make strong TTL * guarantees. There is no pre-emptive pruning of expired items, but you * _may_ set a TTL on the cache, and it will treat expired items as missing * when they are fetched, and delete them. * * Optional, but must be a non-negative integer in ms if specified. * * This may be overridden by passing an options object to `cache.set()`. * * At least one of `max`, `maxSize`, or `TTL` is required. This must be a * positive integer if set. * * Even if ttl tracking is enabled, **it is strongly recommended to set a * `max` to prevent unbounded growth of the cache.** * * If ttl tracking is enabled, and `max` and `maxSize` are not set, * and `ttlAutopurge` is not set, then a warning will be emitted * cautioning about the potential for unbounded memory consumption. * (The TypeScript definitions will also discourage this.) */ ttl?: Milliseconds; /** * Minimum amount of time in ms in which to check for staleness. * Defaults to 1, which means that the current time is checked * at most once per millisecond. * * Set to 0 to check the current time every time staleness is tested. * (This reduces performance, and is theoretically unnecessary.) * * Setting this to a higher value will improve performance somewhat * while using ttl tracking, albeit at the expense of keeping stale * items around a bit longer than their TTLs would indicate. * * @default 1 */ ttlResolution?: Milliseconds; /** * Preemptively remove stale items from the cache. * * Note that this may *significantly* degrade performance, e