import { Arrayable as Arrayable$1 } from "@/types/types.js"; type ItemType = T extends Array ? X : T extends string ? string : Exclude; type ArrayableValue = T extends object ? Readonly : T; /** * Converts a value into an array. This function handles different types of input, * converting them to arrays as follows: * - If the value is already an array, it returns it as-is. * - If the value is a string, it splits the string by commas and trims the elements. * - If the value is null or undefined, it returns an empty array. * - Otherwise, it wraps the value in an array. * * @example * arrayable(42); // [42] * arrayable('a, b, c'); // ['a', 'b', 'c'] * arrayable([1, 2, 3]); // [1, 2, 3] * arrayable(null); // [] * arrayable(undefined); // [] * * @param value The value to convert into an array. It can be of any type. * @returns An array derived from the input value. * * @group Array */ declare function arrayable(value: ArrayableValue): ItemType[]; /** * Calculates the average value from an array of numbers. * * The function sums up all valid numbers in the array and divides by the count of those valid numbers. * If the array is empty or contains no valid numbers, it returns `0`. * * @example * avg([5, 5, 5]); // 5 * avg([10, 20, 30]); // 20 * avg([1, 2, 'three', 4]); // 2.33 (ignores non-numeric values) * avg([]); // 0 * * @param values An array of numbers (could include invalid values, which will be ignored). * @returns The average value of the valid numbers in the array, or `0` if no valid numbers exist. * * @group Array */ declare const avg: (values: readonly number[]) => number; /** * Computes the average of circular values using vector summation. * * This function calculates the circular mean of an array of values, * which is useful for cyclic data (e.g., time of day, angles). * * @param {readonly number[]} values - The array of numbers representing circular values. * @param {number} max - The maximum possible value in the cycle (e.g., 24 for hours, 360 for degrees). * @returns {number} - The computed circular mean, wrapped within the range [0, max). * * @example * // Averaging angles in degrees * avgCircular([350, 10, 20], 360); // Returns approximately 0 * * @example * // Averaging times in hours (on a 24-hour clock) * avgCircular([23, 1, 2], 24); // Returns approximately 0 * * @group Array */ declare const avgCircular: (values: readonly number[], max: number) => number; /** * Splits an array into smaller sub-arrays (chunks) of a specified size. * * If the array can't be evenly divided, the last chunk will contain the remaining elements. * * @example * const data = [1, 2, 3, 4, 5, 6, 7, 8, 9]; * const chunkSize = 3; * const result = chunk(data, chunkSize); * console.log(result); * // [ * // [1, 2, 3], * // [4, 5, 6], * // [7, 8, 9] * // ] * * @example * const data = [1, 2, 3, 4, 5]; * const chunkSize = 2; * const result = chunk(data, chunkSize); * console.log(result); * // [ * // [1, 2], * // [3, 4], * // [5] * // ] * * @param list The array to be split into chunks. * @param size The size of each chunk. Defaults to `1` if not specified. * @returns An array of arrays (chunks), each containing up to `size` elements from the original array. * * @group Array */ declare function chunk(list: readonly T[], size?: number): T[][]; /** * Collapses a continuous series into a tuple of two elements. * * Where the first element is the beginning of the series. * Where the second element is the end of the series. * * ⚠️ Tuple may consist only one element if the series not started, like: [1, 3] => [[1], [3]] * * @example * const numbers = [1, 2, 3, 8, 9, 10, 15]; * * chunkSeries(numbers); // [[1, 3], [8, 10], [15]] * * @group Array */ declare function chunkSeries(list: readonly number[], step?: number): number[][]; /** * Computes the difference between arrays. * * This function takes arrays and returns a new array containing the elements * that are not present in any other arrays. * * @template T * @param arrays - The arrays from which to derive the difference. * @returns {T[]} A new array containing the elements that are not present in other arrays. * * @example * const array1 = [1, 2, 3, 4, 5]; * const array2 = [2, 4]; * const array3 = [1, 5]; * const result = difference(array1, array2, array3); * // result will be [3] since 1, 2, 4 and 5 are in other arrays and are excluded from the result. * * @group Array */ declare function difference(...arrays: (readonly T[])[]): T[]; /** * Source: https://github.com/kourge/ts-brand/blob/master/src/index.ts */ /** * A `Brand` is a type that takes at minimum two type parameters. Given a base * type `Base` and some unique and arbitrary branding type `Branding`, it * produces a type based on but distinct from `Base`. The resulting branded * type is not directly assignable from the base type, and not mutually * assignable with another branded type derived from the same base type. * * Take care that the branding type is unique. Two branded types that share the * same base type and branding type are considered the same type! There are two * ways to avoid this. * * The first way is to supply a third type parameter, `ReservedName`, with a * string literal type that is not `__type__`, which is the default. * * The second way is to define a branded type in terms of its surrounding * interface, thereby forming a recursive type. This is possible because there * are no constraints on what the branding type must be. It does not have to * be a string literal type, even though it often is. * * @example * ``` * type Path = Brand; * type UserId = Brand; * type DifferentUserId = Brand; * interface Post { id: Brand } * ``` */ type Brand = Base & { [K in ReservedName]: Branding } & { __witness__: Base; }; /** * An `AnyBrand` is a branded type based on any base type branded with any * branding type. By itself it is not useful, but it can act as type constraint * when manipulating branded types in general. */ type AnyBrand = Brand; /** * `BrandTypeOf` is a type that takes any branded type `B` and yields its base type. */ type BrandTypeOf = B['__witness__']; type Arrayable = T[] | T; type Awaitable = Promise | T; type ArgumentsType = T extends ((...args: infer U) => any) ? U : never; type FunctionArgs = (...args: Args) => Return; type DeepPartial = T extends Date ? T : T extends object ? { [P in keyof T]?: DeepPartial } : T; type DeepReadonly = T extends unknown[] ? Readonly : T extends object ? Readonly<{ [P in keyof T]: DeepReadonly }> : Readonly; type AnyFunction = (...args: any[]) => any; type Data = Record; type GenericObject = Record; interface SelectOptionItem { text: string; value: T; props?: any; } type SelectOptions = SelectOptionItem[]; type OverwriteWith = IsAny extends true ? T1 : Omit & T2; type IsAny = boolean extends (T extends never ? true : false) ? true : false; type IfAny = 0 extends 1 & T ? Y : N; /** * @example * LiteralUnion<'foo' | 'bar', string> * * @see {@link https://github.com/microsoft/TypeScript/issues/29729} */ type LiteralUnion = Union | (Type & Nothing); interface Nothing {} type ValuesOfObject = T[keyof T]; type Fn$1 = () => void; type PromisifyFn = (...args: ArgumentsType) => Promise>; /** * A time value, which can be a string (e.g., "HH:MM"), * an object with `h` (hours) and `m` (minutes) properties, or a similar format * that `createTimeObject` can parse. */ type TimeValue = TimeString | TimeObject; /** * Represent time string in 24h format */ type TimeString = string; /** * Represent time object in 24h format ("HH:MM") */ type TimeObject = { /** * Hour (0 - 23). */ h: number; /** * Minutes (0 - 59). */ m: number; }; /** * Represent date object */ type DateObject = { /** * The year of the date (e.g., 2024). */ year: number; /** * The month of the date (1 = January, 12 = December). */ month: number; /** * The day of the month (1-31). */ date: number; }; interface ThemeConfig { colors: { [x: string]: Record; }; variables: { [x: string]: Record; }; } type Prettify = { [K in keyof T]: T[K] } & {}; interface SelectOptionItem { text: string; value: T; props?: any; } type Primitive = null | undefined | string | number | bigint | boolean | symbol; type SpecialValue = Brand; type ExecResult = ExecSuccess | ExecSkip; type ExecSuccess = { success: true; code: string; reason?: string; } & T; type ExecSkip = { skip: true; code: string; reason?: string; } & T; type ExecResultToSuccess = T extends ExecSuccess ? ExecSuccess : ExecSuccess; type ExecResultToSkip = T extends ExecSkip ? ExecSkip : ExecSkip; type ExecSkipData = T extends ExecSkip ? X : never; type ExecSkipExtract = ExecSkip>; type ExecSuccessData = T extends ExecSuccess ? X : never; type ExecSuccessExtract = ExecSuccess>; interface Logger { info: (...args: unknown[]) => void; warn: (...args: unknown[]) => void; error: (...args: unknown[]) => void; debug: (...args: unknown[]) => void; log: (...args: unknown[]) => void; extend: (...args: unknown[]) => Logger; } /** * Filters and maps an array in a single pass. * * The callback receives a `skip` sentinel as its second argument. Return any * mapped value to keep it, or return `skip` to exclude the current element from * the result. This avoids the extra allocation of chaining `.filter().map()`. * * @param array - The source array to iterate over. It is not mutated. * @param callbackfn - Called for each element with `(value, skip, index, array)`. * Return the mapped value to keep, or `skip` to drop the element. * @returns A new array of the mapped values, excluding any skipped elements. * * @example * ```ts * // Keep even numbers and double them, dropping the rest. * filterMap([1, 2, 3, 4], (value, skip) => * value % 2 === 0 ? value * 2 : skip, * ); * // => [4, 8] * ``` * * @example * ```ts * // Parse valid numbers, skipping entries that fail to parse. * filterMap(['1', 'x', '3'], (value, skip) => { * const n = Number(value); * return Number.isNaN(n) ? skip : n; * }); * // => [1, 3] * ``` * * @group Array */ declare function filterMap(array: T[], callbackfn: (value: T, skip: SpecialValue, index: number, array: T[]) => U | SpecialValue): U[]; type PropertyKeyLiteralToType = T extends string ? string : T extends number ? number : T extends symbol ? symbol : T; type IsPropertyKey = T extends object ? V extends keyof T ? T[V] : L : PropertyKeyLiteralToType; type ToPropertyKey = T extends PropertyKey ? T : string; declare function groupBy(array: readonly T[], keyBy: K, objectMode?: false): Map, T[]>; declare function groupBy(array: readonly T[], keyBy: K, objectMode?: false): Map, T[]>; declare function groupBy(array: readonly T[], keyBy: (item: T) => K, objectMode?: false): Map; declare function groupBy(array: readonly T[], keyBy: K, objectMode: true): Record, T[]>; declare function groupBy(array: readonly T[], keyBy: K, objectMode?: true): Record>, T[]>; declare function groupBy(array: readonly T[], keyBy: (item: T) => K, objectMode: true): Record, T[]>; /** * Returns the intersection of arrays. * * This function takes arrays and returns a new array containing the elements that are * present in all arrays. * * @template T - The type of elements in the array. * @returns {T[]} A new array containing the elements that are present in both arrays. * * @example * const array1 = [1, 2, 3, 4, 5]; * const array2 = [3, 4, 5, 6, 7]; * const result = intersection(array1, array2); * // result will be [3, 4, 5] since these elements are in both arrays. * * @group Array */ declare function intersection(...arrays: (readonly T[])[]): T[]; declare function intersectionBy(keyBy: keyof T, ...arrays: (readonly T[])[]): T[]; declare function intersectionBy(keyBy: PropertyKey, ...arrays: (readonly T[])[]): T[]; declare function intersectionBy(keyBy: (item: T) => unknown, ...arrays: (readonly T[])[]): T[]; declare function keyBy(array: readonly T[], keyBy: K, objectMode?: false): Map, T>; declare function keyBy(array: readonly T[], keyBy: K, objectMode?: false): Map, T[]>; declare function keyBy(array: readonly T[], keyBy: (item: T) => K, objectMode?: false): Map; declare function keyBy(array: readonly T[], keyBy: K, objectMode: true): Record, T>; declare function keyBy(array: readonly T[], keyBy: K, objectMode?: true): Record>, T>; declare function keyBy(array: readonly T[], keyBy: (item: T) => K, objectMode: true): Record, T>; /** * Sort array by multiple fields * * @example * // Sample data: an array of objects representing users * const users = [ * { name: 'Alice', age: 30, score: 85 }, * { name: 'Bob', age: 25, score: 90 }, * { name: 'Charlie', age: 35, score: 90 }, * { name: 'Dave', age: 30, score: 70 }, * ]; * * // Sort users first by score in descending order, then by age in ascending order * const sortedUsers = orderBy(users, ['score', 'age'], ['desc', 'asc']); * * // Output the sorted array * console.log(sortedUsers); * * @group Array */ declare function orderBy(array: readonly T[], fields: (string | ((item: T) => any))[], orders: ('asc' | 'desc')[]): readonly T[]; /** * Randomizes the order of elements in an array using the Fisher-Yates algorithm. * * This function takes an array and returns a new array with its elements shuffled in a random order. * * @template T - The type of elements in the array. * @param {T[]} arr - The array to shuffle. * @returns {T[]} A new array with its elements shuffled in random order. * * @example * const array = [1, 2, 3, 4, 5]; * const shuffledArray = shuffle(array); * // shuffledArray will be a new array with elements of array in random order, e.g., [3, 1, 4, 5, 2] * * @group Array */ declare function shuffle(arr: readonly T[]): T[]; /** * Function that compares two elements and returns a number indicating their relative order. * - Negative number if a < b * - Zero if a equals b * - Positive number if a > b * * @template T The type of elements in the array */ type SortedArrayCompareFn = (a: T, b: T) => number; declare const SYM_COMPARE_FN: unique symbol; /** * A self-sorting array that maintains elements in a sorted order based on a comparison function. * All mutating operations preserve the sorted order of elements. * * @template T The type of elements in the array * * @example * // Create a numerically sorted array * const arr = new SortedArray((a, b) => a - b); * arr.push(3, 2, 1); * console.log(arr); // [1, 2, 3] * * @example * // Create a sorted array with initial values * const names = new SortedArray((a, b) => a.localeCompare(b), ["Charlie", "Alice", "Bob"]); * console.log(names); // ["Alice", "Bob", "Charlie"] * * @example * // Create a sorted array with a custom comparator * const people = new SortedArray( * (a, b) => a.age - b.age || a.name.localeCompare(b.name), * [{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }] * ); * * @group Array */ declare class SortedArray extends Array { private [SYM_COMPARE_FN]; /** * Creates a new SortedArray instance. * * @param compareFn The comparison function to determine the sort order * @param items Optional initial items to add to the array (will be sorted immediately) */ constructor(compareFn: SortedArrayCompareFn, items?: T[]); /** * Inserts multiple items while maintaining sort order * @param items The items to insert * @returns The new length of the array */ push(...items: T[]): number; /** * Override Array methods that would break the sorted order */ unshift(...items: T[]): number; /** * Creates a new SortedArray with the same comparison function * @returns A new SortedArray instance */ slice(start?: number, end?: number): SortedArray; /** * Concatenates arrays or values while maintaining sort order * @param items Arrays or values to concatenate * @returns A new SortedArray with the concatenated elements */ concat(...items: (T | ConcatArray)[]): SortedArray; } /** * Sums the values in an array of numbers, ignoring non-numeric values. * * This function adds all valid numbers in the array and returns the sum. * Non-numeric values (e.g., `null`, `undefined`, `NaN` are ignored in the sum. * * @example * sum([2, 2]); // 4 * sum([1, 'a', 3, 4]); // 8 (non-numeric 'a' is ignored) * sum([5, null, 10]); // 15 (null is ignored) * sum([]); // 0 (empty array returns 0) * * @param values The array of numbers to be summed. * @returns The sum of the numbers in the array. * * @group Array */ declare const sum: (values: readonly number[]) => number; /** * Creates an array of unique values from all given arrays. * * This function takes two arrays, merges them into a single array, and returns a new array * containing only the unique values from the merged array. * * @template T - The type of elements in the array. * @param {T[]} arr1 - The first array to merge and filter for unique values. * @param {T[]} arr2 - The second array to merge and filter for unique values. * @returns {T[]} A new array of unique values. * * @example * const array1 = [1, 2, 3]; * const array2 = [3, 4, 5]; * const result = union(array1, array2); * // result will be [1, 2, 3, 4, 5] * * @group Array */ declare function union(...arrays: (readonly T[])[]): T[]; /** * Returns a new array with duplicates removed. * * This function creates a new array that contains only unique values, * preserving the order of the original elements. * * @example * uniq([1, 2, 3, 4, 1, 3]); // [1, 2, 3, 4] * uniq([5, 5, 5, 5, 5]); // [5] * uniq(['a', 'b', 'a', 'c']); // ['a', 'b', 'c'] * uniq([]); // [] (returns an empty array for empty input) * * @param value The array from which duplicates will be removed. * @returns A new array containing only the unique values from the input array. * * @group Array */ declare function uniq(value: readonly T[]): T[]; /** * Extracts unique elements from an array based on a comparator function or property key. * * This function allows you to determine uniqueness based on custom criteria by passing * a comparator function or a property key. The function will return a new array containing * only the first occurrence of elements that are unique according to the specified comparator. * If the comparator is a property key, uniqueness will be determined based on the value * of that property. * * @example * const users = [ * { id: 1, role: 'admin' }, * { id: 2, role: 'admin' }, * { id: 3, role: 'user' }, * { id: 4, role: 'user' }, * ]; * * const uniqRoles = uniqBy(users, (v) => v.role); * // [ * // { id: 1, role: 'admin' }, * // { id: 3, role: 'user' }, * // ] * * @example * const products = [ * { id: 1, category: 'electronics', name: 'Phone' }, * { id: 2, category: 'electronics', name: 'Laptop' }, * { id: 3, category: 'furniture', name: 'Sofa' }, * ]; * * const uniqCategories = uniqBy(products, 'category'); * // [ * // { id: 1, category: 'electronics', name: 'Phone' }, * // { id: 3, category: 'furniture', name: 'Sofa' }, * // ] * * @param array The array to extract unique elements from. * @param comparator A function that computes the value to determine uniqueness or a property key. * If a string is passed, it is treated as a property key, and uniqueness is * determined based on the value of that property. * @returns A new array containing only the first occurrence of each unique element based on the comparator. * * @group Array */ declare function uniqBy(array: readonly T[], comparator: ((value: T) => any) | PropertyKey): T[]; type WrrItem = { item: T; weight?: number; }; /** * Creates a function that returns a weighted round-robin item from the provided array. * * The input array should contain objects with an `item` property and a `weight` property. * The `weight` determines the relative likelihood of selecting an item. * Items with higher weights will appear more frequently in the selection. * * If the `weight` property is missing or falsy, it defaults to `1`. * An empty array will result in a function that always returns `undefined`. * * @example * const getItem = weightedRoundRobin([ * { item: 'a', weight: 2 }, * { item: 'b', weight: 3 }, * { item: 'c' }, * ]); * * console.log(getItem()); // 'a', 'b', or 'c' * * @group Array */ declare function weightedRoundRobin(arr: WrrItem[]): () => T; declare namespace assert_d_exports { export { array, arrayNumbers, arrayStrings, bigint, boolean, date, equal, execSkip, execSuccess, fn$1 as fn, greaterThan, lessThan, notEmpty, notEmptyString, number, object, ok, string }; } declare function ok(value: unknown, message?: string | Error): asserts value; declare function equal(actual: unknown, expected: T, message?: string | Error): asserts actual is T; declare function notEmpty(value: unknown, message?: string | Error): asserts value; declare function object(value: unknown, message?: string | Error): asserts value is object; declare function string(value: unknown, message?: string | Error): asserts value is string; declare function boolean(value: unknown, message?: string | Error): asserts value is boolean; declare function notEmptyString(value: unknown, message?: string | Error): asserts value is string; declare function number(value: unknown, message?: string | Error): asserts value is number; declare function bigint(value: unknown, message?: string | Error): asserts value is bigint; declare function date(value: unknown, message?: string | Error): asserts value is Date; declare function fn$1(value: unknown, message?: string | Error): asserts value is Function; declare function greaterThan(value: unknown, target: number, message?: string | Error): asserts value is number; declare function lessThan(value: unknown, target: number, message?: string | Error): asserts value is number; declare function array(value: unknown, message?: string | Error): asserts value is unknown[]; declare function arrayStrings(value: unknown, message?: string | Error): asserts value is string[]; declare function arrayNumbers(value: unknown, message?: string | Error): asserts value is number[]; declare function execSuccess(value: unknown, message?: string | Error): asserts value is ExecSuccess; declare function execSkip(value: unknown, message?: string | Error): asserts value is ExecSkip; /** * Base62 encoder/decoder for binary data. * * @example Basic usage * ```typescript * const data = new Uint8Array([255, 128, 64]); * const encoded = base62.encode(data); * console.log(encoded); * * const decoded = base62.decode(encoded); * console.log(decoded); // Uint8Array [255, 128, 64] * ``` * * @example Text encoding * ```typescript * const text = "Hello World!"; * const bytes = new TextEncoder().encode(text); * const encoded = base62.encode(bytes); * const decoded = base62.decode(encoded); * const result = new TextDecoder().decode(decoded); * console.log(result); // "Hello World!" * ``` * * @group Binary */ declare const base62: BaseX; interface BaseX { /** * Base alphabet */ alphabet: string; /** * Base padding chars */ padding: string; /** * Encodes binary data into a BaseX string representation * * @param input - The binary data to encode * @returns The encoded string */ encode(input: Uint8Array): string; /** * Decodes a baseX string back into binary data * * @param input - The encoded string to decode * @returns The decoded binary data * @throws {Error} When the input contains invalid characters or format */ decode(input: string): Uint8Array; } /** * Create custom base alphabet encoding. * * @example * ```typescript * const base16 = basex('0123456789abcdef') * const data = new Uint8Array([255, 255]); * console.log(base16.encode(data)); * ``` * * @example * ```typescript * const base16 = basex('0123456789abcdef') * const encoded = "16FA"; * console.log(base16.decode(encoded)); * ``` * * @group Binary */ declare function basex(alphabet: string): BaseX; /** * Base62-like encoder/decoder for binary data but **super fast**. Useful for human readable tokens generation * * **Warning!** Not RFC standard * * @example Basic usage * ```typescript * const data = new Uint8Array([255, 128, 64]); * const encoded = base62.encode(data); * console.log(encoded); * * const decoded = base62.decode(encoded); * console.log(decoded); // Uint8Array [255, 128, 64] * ``` * * @example Text encoding * ```typescript * const text = "Hello World!"; * const bytes = new TextEncoder().encode(text); * const encoded = base62.encode(bytes); * const decoded = base62.decode(encoded); * const result = new TextDecoder().decode(decoded); * console.log(result); // "Hello World!" * ``` * * @group Binary */ declare const base62Fast: BaseX; declare class Base64Encoding implements BaseX { alphabet: string; padding: string; private decodeMap; constructor(alphabet: string, options?: { padding?: string; }); /** * Encodes binary data into a base64 string representation * * @param input - The binary data to encode * @returns The encoded string * * @example * ```typescript * const data = new Uint8Array([255, 255]); * console.log(base64.encode(data)); * ``` */ encode(data: Uint8Array, options?: { includePadding?: boolean; }): string; /** * Decodes a base64 string back into binary data * * @param input - The encoded string to decode * @returns The decoded binary data * @throws {Error} When the input contains invalid characters or format * * @example * ```typescript * const encoded = "AA=="; * console.log(base64.decode(encoded)); // Uint8Array [255, 255] * ``` */ decode(data: string, options?: { strict?: boolean; }): Uint8Array; } /** * Base64 encoder/decoder for binary data * * @example Basic usage * ```typescript * const data = new Uint8Array([255, 128, 64]); * const encoded = base64.encode(data); * console.log(encoded); * * const decoded = base64.decode(encoded); * console.log(decoded); // Uint8Array [255, 128, 64] * ``` * * @example Text encoding * ```typescript * const text = "Hello World!"; * const bytes = new TextEncoder().encode(text); * const encoded = base64.encode(bytes); * const decoded = base64.decode(encoded); * const result = new TextDecoder().decode(decoded); * console.log(result); // "Hello World!" * ``` * * @group Binary */ declare const base64: Base64Encoding; /** * Base64 encoder/decoder for binary data * * @example Basic usage * ```typescript * const data = new Uint8Array([255, 128, 64]); * const encoded = base64url.encode(data); * console.log(encoded); * * const decoded = base64url.decode(encoded); * console.log(decoded); // Uint8Array [255, 128, 64] * ``` * * @example Text encoding * ```typescript * const text = "Hello World!"; * const bytes = new TextEncoder().encode(text); * const encoded = base64url.encode(bytes); * const decoded = base64url.decode(encoded); * const result = new TextDecoder().decode(decoded); * console.log(result); // "Hello World!" * ``` * * @group Binary */ declare const base64url: Base64Encoding; type Base64ToBytesOptions = { /** * Encoding type */ encoding?: 'base64' | 'base64url'; /** * Whether to enforce strict Base64 decoding. */ strict?: boolean; /** * Prefer to use native `Uint8Array.fromBase64` and `Uint8Array.fromBase64` when possible * @default true */ native?: boolean; }; /** * Decodes a Base64 or Base64URL encoded string into a `Uint8Array`. * * This function supports decoding data from both standard Base64 and Base64URL formats. * * @param {string} data - The encoded string to decode. Must be a valid Base64 or Base64URL encoded string. * @param {Base64ToBytesOptions} [options] - Optional configuration options for decoding. * @returns {Uint8Array} - The decoded byte array. * * @example * // Example 1: Decoding a Base64 string * const base64String = 'SGVsbG8gd29ybGQ='; // "Hello world" * const decodedBytes = base64ToBytes(base64String); * console.log(decodedBytes); // Output: Uint8Array [ 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100 ] * * @example * // Example 2: Decoding a Base64URL encoded string * const base64urlString = 'SGVsbG8gd29ybGQ'; // "Hello world" * const decodedBytes2 = base64ToBytes(base64urlString, { encoding: 'base64url' }); * console.log(decodedBytes2); // Output: Uint8Array [ 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100 ] * * @example * // Example 3: Strict decoding with Base64 * const base64StringStrict = 'SGVsbG8gd29ybGQ='; * const decodedStrict = base64ToBytes(base64StringStrict, { strict: true }); * console.log(decodedStrict); // Output: Uint8Array [ 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100 ] * * @group Binary */ declare function base64ToBytes(data: string, { encoding, strict, native }?: Base64ToBytesOptions): Uint8Array; /** * Converts a `bigint` value into a byte array (`Uint8Array`) in big-endian order. * * This function encodes the absolute value of the provided `bigint` into a minimal byte array, * ensuring that the bytes represent the value in big-endian format. * * @param {bigint} value - The input `bigint` value to convert into bytes. * @returns {Uint8Array} - The byte array (`Uint8Array`) representing the provided `bigint`. * * @example * // Example 1: Convert a positive bigint to bytes * const value = 1234567890123456789n; * const bytes = bigIntBytes(value); * console.log(bytes); // Output: Uint8Array representing the bytes in big-endian * * @example * // Example 2: Convert a negative bigint to bytes * const valueNegative = -1234567890123456789n; * const bytesNegative = bigIntBytes(valueNegative); * console.log(bytesNegative); // Output: Uint8Array representing the absolute value in big-endian * * @example * // Example 3: Handle very small bigints * const smallValue = 42n; * const bytesSmall = bigIntBytes(smallValue); * console.log(bytesSmall); // Output: Uint8Array [ 42 ] * * @example * // Example 4: Convert zero value * const zeroValue = 0n; * const bytesZero = bigIntBytes(zeroValue); * console.log(bytesZero); // Output: Uint8Array [ 0 ] * * @group Binary */ declare function bigIntBytes(value: bigint): Uint8Array; /** * Converts a byte array (`Uint8Array`) into a `bigint`. The byte array is interpreted in big-endian order. * * This function takes a byte array and decodes it into its corresponding `bigint` value by treating * the byte array as a big-endian encoded number. * * @param {Uint8Array} bytes - The byte array to decode into a `bigint`. Must have at least one byte. * @returns {bigint} - The decoded `bigint` value. * * @throws {Error} Will throw an error if the input byte array is empty. * * @example * // Example 1: Decode a simple byte array * const byteArray = new Uint8Array([0, 0, 0, 42]); // Represents the number 42 in big-endian * const decodedValue = bigIntFromBytes(byteArray); * console.log(decodedValue); // Output: 42n * * @example * // Example 2: Decode a multi-byte number * const byteArrayMulti = new Uint8Array([0x12, 0x34, 0x56, 0x78]); // Represents the number 305419896 * const decodedMulti = bigIntFromBytes(byteArrayMulti); * console.log(decodedMulti); // Output: 305419896n * * @example * // Example 3: Decode a single byte number * const byteArraySingle = new Uint8Array([255]); // Represents the number 255 * const decodedSingle = bigIntFromBytes(byteArraySingle); * console.log(decodedSingle); // Output: 255n * * @example * // Example 4: Attempt decoding an invalid empty array * try { * const emptyArray = new Uint8Array([]); * const decodedEmpty = bigIntFromBytes(emptyArray); * } catch (error) { * console.error(error); // Output: Error: Empty Uint8Array * } * * @group Binary */ declare function bigIntFromBytes(bytes: Uint8Array): bigint; declare namespace BitPack { type Field = { name: string; bits: number; take: Take; }; type Options = { totalBits: number; fields: TFields; debug?: boolean; optimize?: boolean; }; type Take = 'low' | 'high'; type API = { buffer: Fn.Buffer; number: Fn.Number; bigint: Fn.BigInt; bits: Fn.Bits; plan?: Plan[]; }; namespace Fn { type Buffer = WithDebug<(data: FieldOptions) => Uint8Array>; type Number = WithDebug<(data: FieldOptions) => number>; type BigInt = WithDebug<(data: FieldOptions) => bigint>; type Bits = WithDebug<(data: FieldOptions) => string>; } type WithDebug = T & { code?: string; }; type ExtractFieldNames = T[number]['name']; type FieldOptions = { [P in T]: number }; } type Plan = { object: 'set' | 'value'; container?: number; bits?: number; offset?: number; value?: unknown; child?: Plan; }; /** * Define compact packed structure * @group Binary * * @example * ```typescript * const snowflake = bitPack({ * totalBits: 64, * fields: [ * { name: 'timestamp', bits: 42, take: 'low' }, * { name: 'workerId', bits: 5, take: 'low' }, * { name: 'processId', bits: 5, take: 'low' }, * { name: 'increment', bits: 12, take: 'low' }, * ], * optimize: true, * }); * * const userId = snowflake.bigint({ * timestamp: 1781295314562, * workerId: 1, * processId: 0, * increment: 0 * }); // 7471294063048785920n * ``` */ declare function bitPack>(options: BitPack.Options): BitPack.API; declare namespace BitUnpack { type Field = { name: string; bits: number; }; type Options = { totalBits: number; fields: TFields; debug?: boolean; }; type API = { buffer: Fn.Buffer; number: Fn.Number; bigint: Fn.BigInt; bits: Fn.Bits; }; namespace Fn { type Buffer = WithDebug<(data: Uint8Array) => FieldResult>; type Number = WithDebug<(data: number) => FieldResult>; type BigInt = WithDebug<(data: bigint) => FieldResult>; type Bits = WithDebug<(data: string) => FieldResult>; } type WithDebug = T & { code?: string; }; type ExtractFieldNames = T[number]['name']; type FieldResult = { [P in T]: number }; } /** * Define compact unpacked structure * @group Binary * * @example * ```typescript * const snowflake = bitUnpack({ * totalBits: 64, * fields: [ * { name: 'timestamp', bits: 42, take: 'low' }, * { name: 'workerId', bits: 5, take: 'low' }, * { name: 'processId', bits: 5, take: 'low' }, * { name: 'increment', bits: 12, take: 'low' }, * ], * }); * * console.log( * snowflake.bigint(7471294063048785920n) * ); // { timestamp: 1781295314562, workerId: 1, processId: 0, increment: 0 } * ``` */ declare function bitUnpack>(options: BitUnpack.Options): BitUnpack.API; type BytesToBase64Options = { /** * Specifies the encoding type. */ encoding?: 'base64' | 'base64url'; /** * Whether or not to include padding (`=`) in the encoded result. Defaults to `true` for Base64, `false` for Base64URL. */ padding?: boolean; /** * Prefer to use native `Uint8Array.toBase64` and `Uint8Array.toBase64` when possible * @default true */ native?: boolean; }; /** * Encodes a byte array (`Uint8Array`) into a Base64 or Base64URL encoded string. * * The function can encode bytes in either the standard Base64 format or Base64URL format, * depending on the specified options. It also allows control over whether padding is included. * * @param {Uint8Array} data - The byte array to encode into Base64 or Base64URL. * @param {BytesToBase64Options} [options] - Optional configuration options. * @returns {string} - The encoded Base64 or Base64URL string. * * @example * // Example 1: Encoding with Base64 with default padding * const byteArray = new Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]); // "Hello world" * const encodedBase64 = bytesToBase64(byteArray); * console.log(encodedBase64); // Output: 'SGVsbG8gd29ybGQ=' * * @example * // Example 2: Encoding with Base64URL without padding * const byteArray2 = new Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]); // "Hello world" * const encodedBase64URL = bytesToBase64(byteArray2, { encoding: 'base64url', padding: false }); * console.log(encodedBase64URL); // Output: 'SGVsbG8gd29ybGQ' * * @example * // Example 3: Encoding with Base64 with no padding * const byteArray3 = new Uint8Array([1, 2, 3, 4]); * const encodedNoPadding = bytesToBase64(byteArray3, { encoding: 'base64', padding: false }); * console.log(encodedNoPadding); // Output: 'AQIDBA' * * @example * // Example 4: Handling invalid encoding options * try { * const invalidEncoding = bytesToBase64(byteArray3, { encoding: 'invalid' }); * } catch (error) { * console.error(error); // Output: Error: Invalid encoding options: invalid * } * * @group Binary */ declare function bytesToBase64(data: Uint8Array, { encoding, padding, native }?: BytesToBase64Options): string; /** * Compares two `Uint8Array` instances to check if their contents are identical. * * This function compares each byte of the two provided byte arrays. It returns `true` * only if both byte arrays are of the same length **and** contain identical byte values * at every index. Otherwise, it returns `false`. * * @param {Uint8Array} a - The first byte array to compare. * @param {Uint8Array} b - The second byte array to compare. * @returns {boolean} `true` if the byte arrays are identical; otherwise, `false`. * * @example * // Example with identical byte arrays * const a = new Uint8Array([1, 2, 3]); * const b = new Uint8Array([1, 2, 3]); * console.log(compareBytes(a, b)); // Output: true * * @example * // Example with different contents * const a = new Uint8Array([1, 2, 3]); * const b = new Uint8Array([1, 2, 4]); * console.log(compareBytes(a, b)); // Output: false * * @example * // Example with different lengths * const a = new Uint8Array([1, 2]); * const b = new Uint8Array([1, 2, 3]); * console.log(compareBytes(a, b)); // Output: false * * @example * // Example with both arrays empty * const a = new Uint8Array([]); * const b = new Uint8Array([]); * console.log(compareBytes(a, b)); // Output: true * * @group Binary */ declare function compareBytes(a: Uint8Array, b: Uint8Array): boolean; /** * Concatenates two `Uint8Array` instances into a single new `Uint8Array`. * * This function takes two byte arrays, `a` and `b`, and creates a new `Uint8Array` * that combines their contents in order. The result will have a length equal to the * sum of the lengths of `a` and `b`. * * @param {Uint8Array} a - The first byte array to concatenate. * @param {Uint8Array} b - The second byte array to concatenate. * @returns {Uint8Array} A new `Uint8Array` containing the concatenation of `a` and `b`. * * @example * // Example with simple byte arrays * const a = new Uint8Array([1, 2, 3]); * const b = new Uint8Array([4, 5, 6]); * const result = concatenateBytes(a, b); * console.log(result); // Output: Uint8Array(6) [1, 2, 3, 4, 5, 6] * * @example * // Example with empty arrays * const a = new Uint8Array([]); * const b = new Uint8Array([1, 2, 3]); * const result = concatenateBytes(a, b); * console.log(result); // Output: Uint8Array(3) [1, 2, 3] * * @example * // Example with reversed order * const a = new Uint8Array([10, 20]); * const b = new Uint8Array([30, 40]); * const result = concatenateBytes(a, b); * console.log(result); // Output: Uint8Array(4) [10, 20, 30, 40] * * @group Binary */ declare function concatenateBytes(a: Uint8Array, b: Uint8Array): Uint8Array; /** * Decode a run-length encoded buffer. * * Decodes `[value, count]` pairs back into runs of `value`. * All other bytes pass through unchanged. * * @param buf - RLE-encoded buffer to decode * @param value - Byte value that was compressed (default: 0) * @returns Decoded buffer * @group Binary */ declare function rleDecode(buf: Uint8Array, value?: number): Uint8Array; /** * Run-length encode a buffer, compressing runs of a specific byte value. * * Runs of `value` are encoded as [value, count] pairs (count ≤ 255). * All other bytes pass through unchanged. * * @param buf - Input buffer to encode * @param value - Byte value to compress runs of (default: 0) * @returns RLE-encoded buffer * @group Binary */ declare function rleEncode(buf: Uint8Array, value?: number): Uint8Array; /** * Converts a `Uint16Array` into a `Uint8Array`. * * @param {Uint16Array} value - The input `Uint16Array` to convert. * @returns {Uint8Array} - The resulting `Uint8Array`, with length twice that of the input `Uint16Array`. * * @example * // Example 1: Converting a valid Uint16Array into a Uint8Array * const uint16Array = new Uint16Array([0x1234, 0x5678]); * const uint8Array = uint16ToUint8(uint16Array); * console.log(uint8Array); // Output: Uint8Array [ 0x34, 0x12, 0x78, 0x56 ] * * @example * // Example 2: Another conversion example * const uint16Array2 = new Uint16Array([0xabcd, 0x1234, 0x5678]); * const uint8Array2 = uint16ToUint8(uint16Array2); * console.log(uint8Array2); // Output: Uint8Array [ 0xcd, 0xab, 0x34, 0x12, 0x78, 0x56 ] * * @group Binary */ declare function uint16ToUint8(value: Uint16Array): Uint8Array; /** * Converts a `Uint32Array` into a `Uint8Array`. * * @param {Uint32Array} value - The input `Uint32Array` to convert. * @returns {Uint8Array} - The resulting `Uint8Array`, with length four times that of the input `Uint32Array`. * * @example * // Example 1: Converting a valid Uint32Array into a Uint8Array * const uint32Array = new Uint32Array([0x12345678, 0x9abcdef0]); * const uint8Array = uint32ToUint8(uint32Array); * console.log(uint8Array); // Output: Uint8Array [ 0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a ] * * @example * // Example 2: Another conversion example with different numbers * const uint32Array2 = new Uint32Array([0xffffffff, 0x00000000]); * const uint8Array2 = uint32ToUint8(uint32Array2); * console.log(uint8Array2); // Output: Uint8Array [ 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 ] * * @example * // Example 3: Handling edge values * const uint32Array3 = new Uint32Array([0x0, 0x00000001]); * const uint8Array3 = uint32ToUint8(uint32Array3); * console.log(uint8Array3); // Output: Uint8Array [ 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 ] * * @group Binary */ declare function uint32ToUint8(value: Uint32Array): Uint8Array; /** * Converts a Uint8Array to a Uint16Array. * * @param {Uint8Array} value - The input byte array to convert. Must have an even length. * @returns {Uint16Array} - The converted Uint16Array. * * @example * // Example 1: Converting a valid Uint8Array into a Uint16Array * const uint8Array = new Uint8Array([0x12, 0x34, 0x56, 0x78]); * const uint16Array = uint8ToUint16(uint8Array); * console.log(uint16Array); // Output: Uint16Array [ 0x1234, 0x5678 ] * * @example * // Example 2: Another conversion example * const uint8Array2 = new Uint8Array([0xff, 0xee, 0xdd, 0xcc]); * const uint16Array2 = uint8ToUint16(uint8Array2); * console.log(uint16Array2); // Output: Uint16Array [ 0xffee, 0xddcc ] * * @group Binary */ declare function uint8ToUint16(value: Uint8Array): Uint16Array; /** * Converts a `Uint8Array` into a `Uint32Array`. * * @param {Uint8Array} value - The input byte array to convert. Length must be a multiple of 4. * @returns {Uint32Array} - The converted array of 32-bit unsigned integers. * * @example * // Example 1: Converting a valid Uint8Array into a Uint32Array * const uint8Array = new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0]); * const uint32Array = uint8ToUint32(uint8Array); * console.log(uint32Array); // Output: Uint32Array [ 0x78563412, 0xf0debc9a ] * * @example * // Example 2: Another conversion example * const uint8Array2 = new Uint8Array([0xff, 0xee, 0xdd, 0xcc, 0xab, 0xcd, 0xef, 0x01]); * const uint32Array2 = uint8ToUint32(uint8Array2); * console.log(uint32Array2); // Output: Uint32Array [ 0xccddeeff, 0x01abcded ] * * @group Binary */ declare function uint8ToUint32(value: Uint8Array): Uint32Array; interface ArgToKeyOptions { /** * Object key generation strategy. * * When `json` we will use `JSON.stringify` which not quite effective. * Also may not hit into cache when object has different key order. * * When `ref` we will use WeakMap to store object key which more effective but may produce unexpected cache hit. * * @default `ref` */ objectStrategy: 'json' | 'ref'; } interface CreateWithCacheOptions extends Partial { getBucket: (pointer: WithCachePointer) => WithCacheStorage; getPointer: () => WithCachePointer; fn: T; } type WithCachePointer = object | Function | symbol; interface WithCacheStorage { get(key: unknown): unknown; has(key: unknown): boolean; delete(key: unknown): void; set(key: unknown, value: unknown): void; } interface WithCache { $cache: { getBucket: () => WithCacheStorage; getPointer: () => WithCachePointer; argToKeyOptions: ArgToKeyOptions; }; } type WithCacheResult = T & WithCache; declare function createWithCache({ fn, getPointer, getBucket, objectStrategy }: CreateWithCacheOptions): WithCacheResult; /** * Returns true when function is cached * @group Cache */ declare function isWithCache(value: unknown): value is WithCacheResult; /** * Drop cached result * * @example * const findUser = withCache((id: number) => db.users.findById(id)); * * dropCache(findUser, 100500); * * @group Cache */ declare function dropCache(cachePointer: WithCachePointer, ...args: any[]): boolean; /** * A Map-like class with a fixed capacity, where entries are automatically removed * when the capacity is exceeded. This allows for efficient caching behavior, * ensuring that the map never grows beyond the specified capacity. * * When the map reaches its capacity, the oldest entries (in insertion order) * are removed to make room for new ones. * * @example * const cache = new FixedMap(3); * cache.set('a', 1); * cache.set('b', 2); * cache.set('c', 3); * cache.set('d', 4); // 'a' will be evicted, as it's the oldest entry * * console.log(cache.get('a')); // undefined * console.log(cache.get('b')); // 2 * * @group Cache */ declare class FixedMap extends Map { private _capacity; private _tail; constructor(_capacity: number); set(key: K, value: V): this; delete(key: K): boolean; clear(): void; get capacity(): number; set capacity(value: number); private _drain; } /** * A `WeakMap`-like class with a fixed capacity. Entries are automatically removed * when the map exceeds the specified capacity. Unlike a regular `WeakMap`, the * entries are limited to a defined size, and the oldest entries are evicted when * new ones are added after the capacity is reached. * * This class behaves similarly to a `WeakMap`, but with the additional constraint * of a fixed size. It automatically removes the least recently added key-value * pairs when the map grows beyond the specified capacity. * * @example * const cache = new FixedWeakMap(3); * const obj1 = { id: 1 }; * const obj2 = { id: 2 }; * const obj3 = { id: 3 }; * * cache.set(obj1, 1); * cache.set(obj2, 2); * cache.set(obj3, 3); * * const obj4 = { id: 4 }; * cache.set(obj4, 4); // obj1 will be evicted as it's the oldest * * console.log(cache.get(obj1)); // undefined * console.log(cache.get(obj2)); // 2 * console.log(cache.get(obj4)); // 4 * * @group Cache */ declare class FixedWeakMap extends WeakMap { private _capacity; private _tail; constructor(_capacity: number); set(key: K, value: V): this; delete(key: K): boolean; clear(): void; get size(): number; get capacity(): number; set capacity(value: number); private _drain; } /** * Check if function has cached result * * @example * const findUser = withCache((id: number) => db.users.findById(id)); * * const user = findUser(100500); * * isCached(findUser, 100500); // true * * @group Cache */ declare function isCached(fn: AnyFunction, ...args: Parameters): boolean; /** * A simple implementation of a Least Recently Used (LRU) cache. This cache stores * key-value pairs and ensures that the most recently accessed items are kept * in the cache, while the least recently used items are evicted when the cache * reaches its capacity. * * The cache is implemented as a doubly linked list where the head represents * the most recently accessed item, and the tail represents the least recently * accessed item. When the cache is full, the least recently used item (tail) * is removed to make space for new items. * * @group Cache */ declare class LruCache { private capacity; private items; private forward; private backward; private K; private V; size: number; private head; private tail; constructor(capacity: number); /** * Method used to clear the structure. */ clear(): void; set(key: TKey, value: TValue): this; has(key: TKey): boolean; delete(key: TKey): void; get(key: TKey): TValue | undefined; /** * Method used to get the value attached to the given key. Does not modify * the ordering of the underlying linked list. */ peek(key: TKey): TValue | undefined; /** * Method used to create an iterator over the cache's keys from most * recently used to least recently used. */ keys(): IterableIterator; /** * Method used to create an iterator over the cache's values from most * recently used to least recently used. * */ values(): IterableIterator; /** * Method used to create an iterator over the cache's entries from most * recently used to least recently used. * * @return {IterableIterator<[TKey, TValue | undefined]>} */ entries(): { [Symbol.iterator](): { [Symbol.iterator](): /*elided*/any; next(): { done: boolean; value: undefined; } | { done: boolean; value: (TKey | TValue | undefined)[]; }; }; next(): { done: boolean; value: undefined; } | { done: boolean; value: (TKey | TValue | undefined)[]; }; }; /** * Method used to splay a value on top. * * @param {number} pointer - Pointer of the value to splay on top. */ splayOnTop(pointer: number): this; [Symbol.iterator](): { [Symbol.iterator](): /*elided*/any; next(): { done: boolean; value: undefined; } | { done: boolean; value: (TKey | TValue | undefined)[]; }; }; } interface TimeBucketOptions { /** * The size of each time bucket in milliseconds. This is the interval at which * the records in the bucket will expire and be dropped. */ sizeMs: number; /** * The maximum number of entries the bucket can hold. Once the capacity is * reached, the least recently used entry will be removed. * @default Infinity */ capacity?: number; } /** * A time-based bucket that holds records for a specific interval defined by `sizeMs`. * The records in the bucket will be dropped once the interval elapses, based on the * current time. The `TimeBucket` is designed to avoid using timers to track expirations. * * It can be used to store data that expires over fixed time intervals (e.g., caching, * throttling). * * @example * const bucket = new TimeBucket({ sizeMs: 1000, capacity: 10 }); * bucket.set('key1', 'value1'); * console.log(bucket.get('key1')); // 'value1' * * // After 1 second, the bucket will drop the expired records. * * @group Cache */ declare class TimeBucket { private _pointer; private _sizeMs; private _bucket; constructor({ capacity, sizeMs }: TimeBucketOptions); get capacity(): number; get sizeMs(): number; set sizeMs(value: number); get size(): number; set(key: K, value: V): this; get(key: K): any | undefined; has(key: K): boolean; delete(key: K): boolean; clear(): void; keys(): IterableIterator; values(): IterableIterator; entries(): IterableIterator<[K, V]>; forEach(callbackfn: (value: V, key: K, map: TimeBucket) => void, thisArg?: any): void; private _drainBucket; } interface WithCacheOptions extends Partial { /** * Custom cache pointer */ cachePointer?: WithCachePointer; } declare const cache: WeakMap>; /** * Wrap a function to cache results by arguments * * @example * const sum = withCache((a, b) => { * console.log('calc?'); * return a + b; * }); * * sum(1, 2); // calc? * sum(1, 2); * sum(1, 3) // calc? * * @group Cache */ declare function withCache(fn: T): WithCacheResult; declare function withCache(options: WithCacheOptions, fn: T): WithCacheResult; interface WithCacheBucketOptions extends Partial { /** * Define cached records drops interval. */ sizeMs: number; /** * Capacity of cached records */ capacity?: number; /** * Custom cache pointer */ cachePointer?: WithCachePointer; } declare const cacheBucket: WeakMap>; /** * Wrap a function to cache results by arguments * * But with time and capacity limitation * * @example * const sum = withCacheBucket({ capacity: 1, sizeMs: 1000000 }, (a, b) => { * console.log('calc?'); * return a + b; * }); * * sum(1, 2); // calc? * sum(1, 2); * sum(1, 3) // calc? * sum(1, 3) * sum(1, 2); // calc? * * @group Cache */ declare function withCacheBucket({ capacity, sizeMs, cachePointer, ...options }: WithCacheBucketOptions, fn: T): WithCacheResult; interface WithCacheBucketBatchOptions { /** * Define cached records drops interval. */ sizeMs: number; /** * Cache record by object key. */ key: K; /** * Amount of items which will handled by resolver function. */ batchSize?: number; /** * Capacity of cached records */ capacity?: number; /** * Custom cache pointer */ cachePointer?: WithCachePointer; /** * Should we retry resolving for provided item key when previously we got empty result. */ retryEmpty?: boolean; /** * Resolving item function */ resolver?: (values: T[K][]) => Promise; } /** * In this way we will cache item of resulted array by `key`. * * Useful when we need for example fetch batch of users by ids but took already cached results if it available. * * @example TODO * * @beta * * @group Cache */ declare function withCacheBucketBatch({ capacity, sizeMs, key, batchSize, cachePointer, retryEmpty }: WithCacheBucketBatchOptions, resolver: (values: T[K][]) => Promise): WithCacheResult<(values: T[K][]) => Promise>>>; interface WithCacheFixedOptions extends Partial { /** * Capacity of cached records */ capacity: number; /** * Custom cache pointer */ cachePointer?: WithCachePointer; } declare const cacheFixed: WeakMap>; /** * Wrap a function to cache results by arguments * * But with capacity limitation * * @example * const sum = withCacheFixed({ capacity: 1 }, (a, b) => { * console.log('calc?'); * return a + b; * }); * * sum(1, 2); // calc? * sum(1, 2); * sum(1, 3) // calc? * sum(1, 3) * sum(1, 2); // calc? * * @group Cache */ declare function withCacheFixed({ capacity, cachePointer, ...options }: WithCacheFixedOptions, fn: T): WithCacheResult; interface WithCacheLruOptions extends Partial { capacity: number; cachePointer?: WithCachePointer; } declare const cacheLRU: WeakMap>; /** * Wrap a function to cache results by arguments * * But with LRU * * @example * const sum = withCacheLRU({ capacity: 100 }, (a, b) => { * console.log('calc?'); * return a + b; * }); * * sum(1, 2); // calc? * sum(1, 2); * * @group Cache */ declare function withCacheLRU({ capacity, cachePointer, ...options }: WithCacheLruOptions, fn: T): WithCacheResult; /** * Make deep cloning of function result before returning. * * @example * const findUser = withDeepClone( * withCache((id: number) => { * return { id, name: 'Andrew' }; * }) * ); * * const user1 = findUser(100500); * const user2 = findUser(100500); * user1.name = 'ABC'; * * console.log(user1.name); // ABC * console.log(user2.name); // Andrew * * @group Cache */ declare function withDeepClone(fn: T): T; /** * @example TODO * @group Cache * @beta */ declare function withPointerCache(pointer: object, dependencies: string[], fn: () => T): T; /** * Capture stack trace till the function and returns as a `string` * * @example * * function main() { * const userId = getUserId(); * } * * function getUserId() { * const stackTrace = captureStackTrace(doCoolStuff); * console.warn('Please, use getAccountId instead.', stackTrace); * } * * @group Errors */ declare function captureStackTrace(till: AnyFunction): string; type CatchErrorResult = T extends Promise ? Promise> | ErrorResult> : OkResult | ErrorResult; type ErrorResult = [Error, undefined]; type OkResult = [undefined, T]; /** * You're tired to write `try... catch`, and so are we. * * Also supports `async/await` * * @example * const [err, result] = catchError(() => { * // danger code * }); * * @group Errors */ declare function catchError(fn: () => T): CatchErrorResult; declare namespace Color { /** * From 0 to 1 */ type Alpha = number; type HSLA = { h: number; s: number; l: number; a: Alpha; }; type RGBA = { r: number; g: number; b: number; a: Alpha; }; type HEX = string; /** * Unified color representation in [red, green, blue, alpha] */ type ColorChannels = [number, number, number, number]; } declare function parseHEX(value: unknown): Color.ColorChannels | null; /** * Parse a string as a hsl color */ declare function parseHSL(value: string): Color.HSLA | null; declare function parseRGB(value: unknown): Color.RGBA | null; /** * Check if provided value represents color channels * @group Colors */ declare function isColorChannels(value: unknown): value is Color.ColorChannels; /** * Returns css valid color with adjusted alpha channel * * @example * alpha('rgba(0, 0, 0, 0.87)', 1); // 'rgba(0, 0, 0, 1)' * * @group Colors */ declare function alpha(color: string | Color.ColorChannels, newAlpha: number): string; /** * Just mixing of two colors * * @example * const colorA = 'rgb(50, 100, 100)'; * const colorB = 'rgb(150, 0, 0)'; * * // [100, 50, 50, 1] * blendColors(colorA, colorB, 0.5); * * @group Colors */ declare function blendColors(color1: Color.ColorChannels | string, color2: Color.ColorChannels | string, factor: number): Color.ColorChannels; /** * Build css valid color from color channels * * @example * const channels = [255, 255, 255, 0.5]; * * buildCssColor(channels); // 'rgba(255, 255, 255, 0.5)' * * // with applied opacity factor * buildCssColor(channels, 0.1); // 'rgba(255, 255, 255, 0.05)' * * @group Colors */ declare function buildCssColor([r, g, b, a]: Color.ColorChannels, opacity?: number): string; /** * Converts color channels into hex * * @example * const channels = [255, 255, 255, 1]; * * // with alpha channel * channelsToHex(channels); // '#FFFFFFFF' * * // without alpha channel * channelsToHex(channels, false); // '#FFFFFF' * @group Colors */ declare function channelsToHex(channels: Color.ColorChannels, withAlpha?: boolean): string; /** * Converts color channels into HSL * @group Colors */ declare function channelsToHSL([r, g, b, a]: Color.ColorChannels): Color.HSLA; /** * Converts color channels into RGB * @group Colors */ declare function channelsToRGB([r, g, b, a]: Color.ColorChannels): Color.RGBA; /** * Parse css color and returns color channels * @group Colors */ declare function colorToChannels(color: string | Color.ColorChannels): Color.ColorChannels; /** * Calculate WCAG 2.0 contrast ratio of two luminance * * @example * const l1 = luminance([255, 255, 255, 1]); * const l2 = luminance([0, 0, 0, 1]); * * contrastRatio(l1, l2); // 21 * * @group Colors */ declare function contrastRatio(l1: number, l2: number): number; /** * Create a getter of css variable for container * @group Colors */ declare function cssVariable(container: HTMLElement): (name: string) => string; /** * Parsing hex string as color channels * * @example * hexToChannels('#FFFFFF'); // [255, 255, 255, 1] * hexToChannels('#FFF'); // [255, 255, 255, 1] * * @group Colors */ declare function hexToChannels(hexWithAlpha: string): Color.ColorChannels; /** * Parsing HSL string as color channels * * @example * // [128, 51, 204, 0.15] * hslToChannels('hsl(270 60% 50% / 15%)'); * * @group Colors */ declare function hslToChannels(value: string): Color.ColorChannels; /** * Linear color interpolating * * @example * // 'rgba(50, 50, 50, 1)' * interpolateColor( * 'rgb(0, 0, 0)', * 'rgb(100, 100, 100)', * 0.5 * ); * * @group Colors */ declare function interpolateColor(color1: string | Color.ColorChannels, color2: string | Color.ColorChannels, factor: number): Color.ColorChannels; /** * Calculate luminance of color * * @example * luminance([255, 255, 255, 1]); // 1 * luminance([0, 0, 0, 1]); // 0 * * @group Colors */ declare function luminance([r, g, b]: Color.ColorChannels): number; /** * Parse alpha channel value and normalize it from 0 to 1 * * @param value Value to be parsed * @param fallback Value which will be used as fallback when failed to parse * * @example * parseAlpha('0.1'); // 0.1 * parseAlpha('10%'); // 0.1 * parseAlpha(0.1); // 0.1 * * @group Colors */ declare function parseAlpha(value: unknown, fallback?: number): number; /** * Parsing rgb() string as color channels * * @example * // [255, 0, 0, 0.2] * rgbToChannels('rgba(100% 0% 0% / 20%)'); * * @group Colors */ declare function rgbToChannels(value: string): Color.ColorChannels; /** * Returns a color text color that should be on background to keep good contrast * * @example * const bgColor = 'rgb(255, 255, 255)'; * const tint = 1; * * // 'rgba(0, 0, 0, 1)' * const textColor = tintedTextColor(bgColor, tint); * * @group Colors */ declare function tintedTextColor(background: string | Color.ColorChannels, tintPercentage?: number): Color.ColorChannels; type ColorChannels = Color.ColorChannels; /** * General color parser api * @group Colors */ declare const ColorParser: { HSL: typeof parseHSL; RGB: typeof parseRGB; HEX: typeof parseHEX; }; /** * Calculate crc32 hash from string * @group Crypto */ declare function crc32(value: Uint8Array | Uint8Array[] | string, seed?: number): number; type DateObjectInput = Date | string | number | DateObject; declare function createDateObject(value: DateObjectInput): DateObject; declare function createDateObject(value: DateObjectInput, returnsNullWhenInvalid: true): DateObject | null; type TimeObjectInput = Date | number | string | TimeObject; declare function createTimeObject(value: TimeObjectInput): TimeObject; declare function createTimeObject(value: TimeObjectInput, returnsNullWhenInvalid: true): TimeObject | null; type TimeSpanUnit = 'ms' | 's' | 'm' | 'h' | 'd' | 'w'; /** * A class representing a span of time with a specific value and unit of measurement. * Provides methods for conversion between time units and arithmetic operations (add, subtract). */ declare class TimeSpan { constructor(value: number, unit: TimeSpanUnit); /** * The numeric value of the time span */ value: number; /** * The unit of the time span. */ unit: TimeSpanUnit; /** * Converts the time span to milliseconds. * * @returns {number} The equivalent time span in milliseconds. * @example * const ts = new TimeSpan(2, 'h'); * ts.milliseconds(); // Returns 7200000 */ milliseconds(): number; /** * Converts the time span to seconds. * * @returns {number} The equivalent time span in seconds. * @example * const ts = new TimeSpan(2, 'm'); * ts.seconds(); // Returns 120 */ seconds(): number; /** * Converts the time span to minutes. * * @returns {number} The equivalent time span in minutes. * @example * const ts = new TimeSpan(120, 's'); * ts.minutes(); // Returns 2 */ minutes(): number; /** * Converts the time span to hours. * * @returns {number} The equivalent time span in hours. * @example * const ts = new TimeSpan(120, 'm'); * ts.hours(); // Returns 2 */ hours(): number; /** * Converts the time span to days. * * @returns {number} The equivalent time span in days. * @example * const ts = new TimeSpan(48, 'h'); * ts.days(); // Returns 2 */ days(): number; /** * Converts the time span to weeks. * * @returns {number} The equivalent time span in weeks. * @example * const ts = new TimeSpan(14, 'd'); * ts.weeks(); // Returns 2 */ weeks(): number; /** * Adds a specified value and unit to the current time span. * * Returns new instance. * * @param {number} value - The value to add. * @param {TimeSpanUnit} [unit='ms'] - The unit of the value to add (default is milliseconds). * @returns {TimeSpan} A new TimeSpan instance with the added value. * @example * const ts = new TimeSpan(1, 'h'); * ts.add(30, 'm'); // Represents 1.5 hours */ add(value: number, unit?: TimeSpanUnit): TimeSpan; /** * Subtracts a specified value and unit from the current time span. * * Returns new instance. * * @param {number} value - The value to subtract. * @param {TimeSpanUnit} [unit='ms'] - The unit of the value to subtract (default is milliseconds). * @returns {TimeSpan} A new TimeSpan instance with the subtracted value. * @example * const ts = new TimeSpan(1, 'h'); * ts.subtract(30, 'm'); // Represents 30 minutes less than 1 hour */ subtract(value: number, unit?: TimeSpanUnit): TimeSpan; } /** * Creates a new instance of `TimeSpan`. * * This utility function allows you to create a `TimeSpan` object by providing a numeric value and a unit of time. * The default unit is `'ms'` (milliseconds). * * @param {number} value - The numeric value representing the timespan. * @param {TimeSpanUnit} [unit='ms'] - The unit of time for the timespan value. Options are `'ms'`, `'s'`, `'m'`, `'h'`, `'d'`, `'w'`. * @returns {TimeSpan} An instance of the `TimeSpan` class. * @example * // Create a TimeSpan with 500 milliseconds * const ts = createTimeSpan(500); * console.log(ts.milliseconds()); // 500 * * @example * // Create a TimeSpan with 2 hours * const ts = createTimeSpan(2, 'h'); * console.log(ts.seconds()); // 120 * * @example * // Create a TimeSpan with 7 days * const ts = createTimeSpan(7, 'd'); * console.log(ts.weeks()); // 1 * * @group Date */ declare function createTimeSpan(value: number, unit?: TimeSpanUnit): TimeSpan; /** * The base time as a timestamp, `Date` object, * or a similar format that the `timestampMs` function can parse. */ type TimestampMsInput = Date | string | number; /** * Returns or converts the given input into milliseconds since the Unix epoch. * * @param {TimestampMsInput} [fromValue=Date.now()] - The input value to be converted to milliseconds. * Can be a `Date` object, a timestamp (number), or a string representing a date. * Defaults to the current time. * @returns {number} The number of milliseconds since the Unix epoch. Returns `0` if the input is invalid. * * @example * // Get milliseconds from a Date object * timestampMs(new Date('2023-01-01T00:00:00Z')); // 1672531200000 * * @example * // Get milliseconds from a timestamp * timestampMs(1672531200000); // 1672531200000 * * @example * // Get milliseconds from a date string * timestampMs('2023-01-01T00:00:00Z'); // 1672531200000 * * @example * // Handle invalid input * timestampMs('invalid-date'); // 0 * * @example * // Use the default value (current time) * timestampMs(); // Current timestamp in milliseconds * * @group Date */ declare function timestampMs(fromValue?: TimestampMsInput): number; /** * Returns a `Date` object representing a time that is the given number of days * before or after a base time. * * @param {number} days - The number of days to add to or subtract from the base time. * Positive values move forward in time, and negative values move backward. * @param {TimestampMsInput} [fromValue=Date.now()] - The base time as a timestamp. * @returns {Date} A `Date` object representing the computed time. * * @example * // Get the date 7 days from now * dateInDays(7); // Returns a Date object 7 days in the future * * @example * // Get the date 5 days before a specific time * dateInDays(-5, new Date('2023-01-01T00:00:00Z')); // Returns 2022-12-27T00:00:00Z * * @example * // Use a timestamp as the base time * dateInDays(2, 1672531200000); // Returns a Date object 2 days after the base timestamp * * @group Date */ declare function dateInDays(days: number, fromValue?: TimestampMsInput): Date; /** * Returns a `Date` object representing a time that is the given number of seconds * before or after a base time. * * @param {number} seconds - The number of seconds to add to or subtract from the base time. * Positive values move forward in time, and negative values move backward. * @param {TimestampMsInput} [fromValue=Date.now()] - The base time. * @returns {Date} A `Date` object representing the computed time. * * @example * // Get the date 60 seconds from now * dateInSeconds(60); // Returns a Date object 1 minute in the future * * @example * // Get the date 30 seconds before a specific time * dateInSeconds(-30, new Date('2023-01-01T00:00:00Z')); // Returns 2022-12-31T23:59:30Z * * @example * // Use a timestamp as the base time * dateInSeconds(10, 1672531200000); // Returns a Date object 10 seconds after the base timestamp * * @group Date */ declare function dateInSeconds(seconds: number, fromValue?: TimestampMsInput): Date; /** * Gets a random time within the specified range. * * Generates a random hour (`h`) and minute (`m`) between the given `startTime` and `endTime`. * If no range is provided, it defaults to the full day from `{ h: 0, m: 0 }` to `{ h: 23, m: 59 }`. * * @param {TimeObject} [startTime={ h: 0, m: 0 }] - The starting range for the random time. * @param {TimeObject} [endTime={ h: 23, m: 59 }] - The ending range for the random time. * @returns {TimeObject} - A random time object with `h` and `m` values within the given range. * * @example * // Generate a random time within the full day * const randomTime = getRandomTime(); * console.log(randomTime); // e.g., { h: 12, m: 34 } * * @example * // Generate a random time between 9:00 and 17:00 * const randomTime = getRandomTime({ h: 9, m: 0 }, { h: 17, m: 0 }); * console.log(randomTime); // e.g., { h: 12, m: 15 } * * @example * // Generate a random time between 8:30 and 10:30 * const randomTime = getRandomTime({ h: 8, m: 30 }, { h: 10, m: 30 }); * console.log(randomTime); // e.g., { h: 9, m: 45 } * * @group Date */ declare function getRandomTime(startTime?: TimeObject, endTime?: TimeObject): TimeObject; /** * Converts a decimal representation of hours and minutes (HH.MM) into total seconds. * * This function takes a decimal number in the format `HH.MM`, where: * - The integer part represents the number of hours. * - The fractional part represents the minutes (in decimal) and is converted accordingly. * * It returns the total time in seconds. * * @param {number} hm - The time represented in HH.MM format (e.g., 2.30 for 2 hours and 30 minutes). * @returns {number} - The total number of seconds equivalent to the provided HH.MM value. * * @example * hmToSeconds(1.00); * // Returns 3600 (1 hour = 3600 seconds) * * @example * hmToSeconds(2.30); * // Returns 9000 (2 hours and 30 minutes = 2 * 3600 + 30 * 60 = 9000 seconds) * * @example * hmToSeconds(0.15); * // Returns 900 (0 hours and 15 minutes = 15 minutes = 900 seconds) * * @example * hmToSeconds(3.45); * // Returns 13500 (3 hours and 45 minutes = 3 * 3600 + 45 * 60 = 13500 seconds) * * @group Date */ declare function hmToSeconds(hm: number): number; /** * Checks if a given value is a valid `DateObject`. * * A valid `DateObject` is an object that contains numeric `year`, `month`, and `date` properties. * * @param {unknown} value - The value to be checked. * @returns {value is DateObject} - Returns `true` if the value is a valid `DateObject`; otherwise, `false`. * * @example * // Valid DateObject * isDateObject({ year: 2024, month: 11, date: 8 }); // true * * @example * // Missing properties * isDateObject({ year: 2024, month: 11 }); // false * * @example * // Non-numeric values * isDateObject({ year: '2024', month: 11, date: 8 }); // false * * @example * // Non-object input * isDateObject('invalid'); // false * * @example * // Additional properties (still valid) * isDateObject({ year: 2024, month: 11, date: 8, extra: 'property' }); // true * * @group Date */ declare function isDateObject(value: unknown): value is DateObject; /** * Checks if a given value is a valid `TimeObject`. * * @param {unknown} value - The value to check if it's a valid `TimeObject`. * @returns {value is TimeObject} - Returns `true` if the value is a valid `TimeObject`, otherwise `false`. * * @example * // Valid TimeObject * isTimeObject({ h: 15, m: 30 }); // true * * @example * // Invalid TimeObject (missing `m`) * isTimeObject({ h: 15 }); // false * * @example * // Invalid TimeObject (non-number values) * isTimeObject({ h: '15', m: 30 }); // false * isTimeObject({ h: 15, m: '30' }); // false * * @example * // Invalid TimeObject (out-of-range hours) * isTimeObject({ h: -1, m: 30 }); // false * isTimeObject({ h: 24, m: 30 }); // false * * @example * // Invalid TimeObject (out-of-range minutes) * isTimeObject({ h: 15, m: -1 }); // false * isTimeObject({ h: 15, m: 60 }); // false * * @example * // Invalid TimeObject (non-object input) * isTimeObject('string'); // false * isTimeObject(123); // false * isTimeObject([]); // false * * @group Date */ declare function isTimeObject(value: unknown): value is TimeObject; /** * Checks if a given value is a valid `TimeString`. * * @param {unknown} value - The value to check if it's a valid `TimeString`. * @returns {value is TimeObject} - Returns `true` if the value is a valid `TimeString`, otherwise `false`. * * @example * // Valid TimeString * isTimeString('15:30'); // true * * @example * // Invalid TimeString * isTimeObject('15:30:00'); // false * * @example * // Invalid TimeString (out-of-range hours) * isTimeObject('26:00'); // false * * @group Date */ declare function isTimeString(value: unknown): value is TimeString; /** * Checks if a given value is a valid `TimeValue`. * * @param {unknown} value - The value to check if it's a valid `TimeValue`. * @returns {value is TimeObject} - Returns `true` if the value is a valid `TimeValue`, otherwise `false`. * * @example * // Valid TimeObject * isTimeValue({ h: 15, m: 30 }); // true * * @example * // Valid TimeString * isTimeValue('15:30'); // true * * @group Date */ declare function isTimeValue(value: unknown): value is TimeValue; /** * Checks if a given value is a valid weekday number. * * A valid weekday number is a number between 1 (Monday) and 7 (Sunday), inclusive. * * @param {unknown} value - The value to check if it's a valid weekday number. * @returns {value is number} - Returns `true` if the value is a number and represents a valid weekday, otherwise `false`. * * @example * // Valid weekday numbers * isValidWeekDay(1); // true * isValidWeekDay(7); // true * * @example * // Invalid weekday numbers * isValidWeekDay(0); // false * isValidWeekDay(8); // false * isValidWeekDay(-1); // false * isValidWeekDay('3'); // false * isValidWeekDay(null); // false * isValidWeekDay(undefined); // false * * @group Date */ declare function isValidWeekDay(value: unknown): value is number; /** * Converts seconds to a decimal representation of hours and minutes (HH.MM) rounded to two decimal places. * * This function takes a number of seconds, calculates the number of whole hours and minutes, * and converts them into a two-decimal representation where: * - The integer part represents the hours. * - The fractional part represents the minutes (rounded to 2 digits). * * @param {number} seconds - The total number of seconds to convert into hours and minutes. * @returns {number} - A decimal number in the format HH.MM representing the converted time. * * @example * secondsToHm(3661); * // Returns 1.01 (1 hour and 1 minute) * * @example * secondsToHm(7322); * // Returns 2.02 (2 hours and 2 minutes) * * @example * secondsToHm(59); * // Returns 0.59 (0 hours and 59 minutes) * * @example * secondsToHm(3600); * // Returns 1.00 (exactly 1 hour) * * @group Date */ declare function secondsToHm(seconds: number): number; declare function timeFromMinutes(value: number): TimeObject; declare function timeFromMinutes(value: number, returnsNullWhenInvalid: true): TimeObject | null; /** * Returns the number of seconds since the Unix epoch (January 1, 1970). * * This function accepts either a `Date` object or a timestamp in milliseconds (number). * If no argument is provided, it defaults to the current timestamp in seconds. * * @param {Date | number} [fromValue=Date.now()] - The date or timestamp to convert. * If not provided, the current date and time will be used. * * @returns {number} The number of seconds since the Unix epoch for the provided date or timestamp. * * @example * // Using a Date object * const date = new Date('2020-01-01T00:00:00Z'); * console.log(timestamp(date)); // Returns 1577836800 (seconds since Unix epoch) * * // Using a timestamp in milliseconds * const timestampInMs = 1609459200000; * console.log(timestamp(timestampInMs)); // Returns 1609459200 (seconds since Unix epoch) * * // Using the current time * console.log(timestamp()); // Returns current seconds since Unix epoch * * @group Date */ declare function timestamp(fromValue?: Date | number): number; /** * Converts a Unix timestamp (in seconds) to a `Date` object. * * This function accepts a timestamp in seconds (number) and returns a `Date` object * corresponding to that timestamp. If an invalid number is passed (non-numeric or NaN), * it returns `null`. * * @param {number} value - The Unix timestamp (in seconds) to convert into a `Date` object. * @returns {Date | null} The `Date` object corresponding to the provided timestamp, or `null` * if the value is not a valid number. * * @example * const date = timestampToDate(1609459200); * console.log(date); // Outputs: Thu Jan 01 2021 00:00:00 GMT+0000 (UTC) * * // Invalid input * console.log(timestampToDate('invalid')); // Outputs: null * console.log(timestampToDate(NaN)); // Outputs: null * console.log(timestampToDate(null)); // Outputs: null * * @group Date */ declare function timestampToDate(value: number): Date | null; declare function timeStringify(value: TimeValue): string; declare function timeStringify(value: TimeValue, returnsNullWhenInvalid: true): string | null; /** * Converts a time value into the total number of minutes. * * @param {TimeValue} value - A time value * * @returns {number} The total number of minutes represented by the time value. * * @example * // Assuming createTimeObject("2:30") returns { h: 2, m: 30 } * timeToMinutes("2:30"); // 150 * * // Assuming createTimeObject({ h: 1, m: 45 }) returns { h: 1, m: 45 } * timeToMinutes({ h: 1, m: 45 }); // 105 * * @group Date */ declare function timeToMinutes(value: TimeValue): number; /** * Determines the number of ISO weeks in a given year. * * The ISO week numbering system defines a year as having 52 or 53 full weeks. * * @param {number} year - The year for which to calculate the number of ISO weeks. * @returns {number} - Returns 52 or 53 based on the ISO 8601 standard. * * @example * // Common year with 52 weeks * weeksInYear(2023); // 52 * * @example * // Leap year with 53 weeks * weeksInYear(2020); // 53 * * @group Date */ declare function weeksInYear(year: number): number; type EJSONType = { /** * The string placeholder (must start with `$`) that represents the custom type. */ placeholder: string; /** * Should encoded value inlined to original key */ encodeInline?: boolean; /** * Function to encode a value into a custom representation using a custom type handler. * * If the function returns `undefined`, it signals that encoding for this value should * be delegated to another type handler or encoding logic. * * @param {any} value - The value to be encoded. * @param {(value: any) => any} encode - A reference to the general encoding function * (useful for recursive encoding logic if necessary). * @returns {any} - The custom-encoded value or `undefined` to delegate encoding to another type handler. */ encode: (value: any, encode: (value: any) => any) => any; /** * A function to decode a custom representation back into a valid JavaScript value. */ decode: (value: any) => any; }; /** * EJSON - Extended JSON handler class for custom encoding and decoding with vendor support. * This class provides methods to encode, decode, stringify, and parse JSON with custom type handlers. */ declare class EJSON { /** @internal */ protected typeHandlers: Map>; /** @internal */ protected replacerReady: (value: any, key: PropertyKey | undefined) => any; /** @internal */ protected encode: (value: any) => any; /** @internal */ protected reviewerReady: (_: string, value: any) => any; /** @internal */ protected pure: boolean; protected _vendorName: string | null; /** * MIME type based on the provided vendor name or defaults to 'application/json'. */ mimetype: string; readonly Type: { readonly Date: EJSONType; readonly Map: EJSONType; readonly Set: EJSONType; readonly RegExp: EJSONType; readonly Infinity: EJSONType; readonly BigInt: EJSONType; readonly Binary: EJSONType; }; constructor(); /** * The vendor name used for the custom MIME type definition. * If null, defaults to 'application/json'. */ get vendorName(): string | null; set vendorName(value: string | null); /** * Adds a custom type handler for encoding/decoding logic. * Ensures type placeholders are unique and adhere to conventions. */ addType(type: Readonly): this; /** * Stringifies a JavaScript value using custom encoding logic. * @param {any} value - The value to encode and stringify. * @param {string | number} [space] - Optional space for pretty-printing. * @returns {string} - The JSON stringified value. */ stringify(value: any, space?: string | number): string; /** * Parses a JSON string using custom decoding logic. * @param {string} value - The JSON string to parse. * @returns {any} - The decoded JavaScript object. */ parse(value: string): T; /** @internal */ protected _replacer(value: any, key: PropertyKey | undefined): any; /** @internal */ protected _reviewer(_: string, value: any): any; } /** * Creates a new instance of the `EJSON` (Extensible JSON) with optional basic types pre-registered. * * This function allows you to initialize an `EJSON` instance with commonly used types like `Map`, `Set`, * `Date`, `RegExp`, `Infinity`, `BigInt` and `Uint8Array`. These types are added to the type handlers only when `withBasicTypes` is set to `true`. * * | Type | Placeholder | Alias | * |-------------|-------------|----------------| * | Date | $date | EJSON.Date | * | Map | $map | EJSON.Map | * | Set | $set | EJSON.Set | * | Infinity | $inf | EJSON.Infinity | * | BigInt | $bigint | EJSON.BigInt | * | RegExp | $regexp | EJSON.RegExp | * | Uint8Array | $binary | EJSON.Binary | * | Uint16Array | $binary | EJSON.Binary | * | Uint32Array | $binary | EJSON.Binary | * * @param {boolean} [withBasicTypes=false] - Indicates whether to include basic types like Map, Set, Date, and BigInt. * @returns {EJSON} - A new instance of the `EJSON` class configured with optional basic types. * * @example * // Instance with basic types (Map, Set, Date, BigInt, Uint8Array) * import { EJSON } from '@andrew_l/toolkit'; * * EJSON.stringify({ value: new Date(0) }); * // {"value":{"$date": 0}} * * @example * // Create an EJSON instance without any additional types * const ejson = createEJSON(); * * ejson.stringify({ value: new Date(0) }); * // {"value":"1970-01-01T00:00:00.000Z"} * * @example * // Custom type * import { EJSON, createEJSON } from '@andrew_l/toolkit'; * * const ejson = createEJSON(); * * ejson.vendorName = 'Andrew'; * * // Add pre-build date type * ejson.addType(EJSON.Date); * * // Add custom buffer type * ejson.addType({ * placeholder: '$buffer', * encode(value) { * if (Buffer.isBuffer(value)) { * return value.toString('hex'); * } * }, * decode(value) { * return Buffer.from(value, 'hex'); * } * }); * * ejson.stringify({ * value: [ * Buffer.from('Hello World', 'utf8'), * new Date(0) * ] * }); * // {"value":[{"$buffer":"48656c6c6f20576f726c64"},{"$date":0}]} * * console.log(ejson.mimetype); // application/vnd.andrew+json * * @group EJSON */ declare function createEJSON(withBasicTypes?: boolean): EJSON; interface EJSONStreamOptions { /** * EJSON Instance */ ejson: EJSON; /** * Starting encoding symbol */ op: string; /** * Separator symbol */ sep: string; /** * Ending symbol */ cl: string; /** @internal */ onStart?: (controller: TransformStreamDefaultController) => Promise; /** @internal */ onFlush?: (controller: TransformStreamDefaultController) => Promise; } declare class EJSONStream extends TransformStream { protected ejson: EJSON; constructor({ ejson, cl, op, sep, onFlush, onStart }: EJSONStreamOptions); /** * The vendor name used for the custom MIME type definition. * If null, defaults to 'application/json'. */ get vendorName(): string | null; /** * MIME type based on the provided vendor name or defaults to 'application/json'. */ get mimetype(): string; } interface EJSONStreamOptionsWithPayload extends Partial { prepend?: () => Awaitable; append?: () => Awaitable; resultKey: string; } /** * Creates an instance of `EJSONStream`. This function provides flexibility to create a simple stream * or one with custom payload transformations, such as appending or prepending data. * * The function has overloads to handle either basic streaming options or more advanced use cases * with payload functions (`append`, `prepend`, `resultKey`) to modify how JSON payloads are streamed. * * @function * @param {Partial | EJSONStreamOptionsWithPayload} [options] - Options to configure the EJSONStream. * @returns {EJSONStream} An instance of the `EJSONStream`. * * @example * // Example 1: Create a simple EJSONStream without custom payload transformations * const stream = createEJSONStream(); * * @example * // Example 2: Create EJSONStream with specific options * const stream = createEJSONStream({ * cl: ']', * op: '[', * sep: ',', * ejson: someInstance * }); * * @example * // Example 3: Using prepend and append payloads * const streamWithPayloads = createEJSONStream({ * prepend: async () => ({ key1: 'value1' }), * append: async () => ({ key2: 'value2' }), * resultKey: 'payload' * }); * * // {"key1":"value1","payload": [...data],"key2":"value2"} * * @group EJSON */ declare function createEJSONStream(options?: Partial): EJSONStream; declare function createEJSONStream(options: EJSONStreamOptionsWithPayload): EJSONStream; declare const instance: EJSON; type Dict = { [key: string]: T | undefined; }; type ListTypeName = 'bool' | 'int' | 'decimal' | 'string'; type ListTypeNameToType = T extends 'bool' ? boolean : T extends 'int' ? number : T extends 'decimal' ? number : T extends 'string' ? string : never; /** * Environment variable parser * * @group Environment */ interface EnvParser { /** * NODE_ENV is `development` */ readonly isDevelopment: boolean; /** * NODE_ENV is `production` */ readonly isProduction: boolean; /** * NODE_ENV is `stage` */ readonly isStage: boolean; /** * NODE_ENV is `test` */ readonly isTest: boolean; /** * Returns `true` when environment key has set to `"true"` * * Returns `defaultValue` when key is not defined */ bool(key: string, defaultValue?: boolean): boolean; /** * Returns `number` when environment key has correct number value. * * Returns `defaultValue` when environment key is not defined or has invalid number value */ int(key: string, defaultValue?: number): number; /** * Returns `number` when environment key has correct number value. * * Returns `defaultValue` when environment key is not defined or has invalid number value */ decimal(key: string, dights?: number, defaultValue?: number): number; /** * Returns `string` when environment key has defined. * * Returns `defaultValue` when environment key is not defined */ string(key: string, defaultValue?: string): string; /** * Returns `array` of parsed environment value. * * Returns `defaultValue` when key is not defined */ list(key: string, itemType: T, defaultValue?: ListTypeNameToType[]): ListTypeNameToType[]; /** * Returns parsed json value. * * Returns `defaultValue` when key is not defined or invalid json value */ json(key: string, defaultValue?: T | null): T | null; } /** * Ready-to-use environment parser. * * Target: `process.env` * * Fallback: `import.meta.env` * * @example * * // env.string * const API_KEY = env.string('API_KEY', 'test_key'); * * // env.bool * const TEST_FEATURE = env.bool('TEST_FEATURE', false); * * // env.int * const RETRY_ATTEMPTS = env.int('RETRY_ATTEMPTS', 5); * * // env.decimal * const DELAY_SECONDS = env.decimal('DELAY_SECONDS', 2, 5); // round to 2 dights * * // env.list * const TARGET_ROLES = env.list('TARGET_ROLES', 'string', ['ADMIN']); * * // env.json * const GOOGLE_CREDS = env.json<{ projectId: string; token: string; }>('GOOGLE_CREDS'); * * @group Environment */ declare const env: Readonly; /** * @example * const env = createEnvParser(process.env); * // const env = createEnvParser(import.meta.env); * * const API_KEY = env.string('API_KEY', 'test_key'); * * @group Environment */ declare function createEnvParser(targetObject: Record | Dict): Readonly; interface AppErrorOptions extends ErrorOptions { /** * Custom error code */ code?: string; } /** * Simple application error class with the code * @group Errors */ declare class AppError extends Error { /** * HTTP valid status code */ statusCode: number; /** * Custom error code */ code?: string; constructor(message: string, statusCode?: number, options?: AppErrorOptions); /** * Message will be generated from status code */ constructor(statusCode: number, options?: AppErrorOptions); get name(): string; static is(value: any): value is AppError; } /** * @group Errors */ declare class AssertionError extends Error { /** * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. */ actual: unknown; /** * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. */ expected: unknown; /** * Set to the passed in operator value. */ operator: string; /** * Indicates if the message was auto-generated (`true`) or not. */ generatedMessage: boolean; /** * Value is always `ERR_ASSERTION` to show that the error is an assertion error. */ code: 'ERR_ASSERTION'; constructor(options?: { /** If provided, the error message is set to this value. */message?: string | undefined; /** The `actual` property on the error instance. */ actual?: unknown | undefined; /** The `expected` property on the error instance. */ expected?: unknown | undefined; /** The `operator` property on the error instance. */ operator?: string | undefined; /** If provided, the generated stack trace omits frames before this function. */ stackStartFn?: Function | undefined; }); } /** * Extract file extension from string * * @example * getFileExtension('Andrew L - CV.pdf'); // 'pdf' * * @group Files */ declare function getFileExtension(name: string, withDot?: boolean): string | null; /** * Extract filename from string * * @example * getFileName('Andrew L - CV.pdf'); // 'Andrew L - CV' * * @group Files */ declare function getFileName(value: string): string | null; /** * Filters an array of paths to retain only the most specific (deepest) paths, * removing any path that is a prefix of another path. * * @param {string[]} keys - An array of dot-separated string paths. * @returns {string[]} - A new array containing only the most specific paths. * * @example * const inputPaths = [ * 'profile', * 'profile.basic', * 'profile.basic.fullName', * 'profile.updatedAt' * ]; * * const result = getMostSpecificPaths(inputPaths); * console.log(result); // ['profile.basic.fullName', 'profile.updatedAt'] * * @group Files */ declare function getMostSpecificPaths(keys: string[]): string[]; /** * Converts bytes amount into human readably string * * @example * humanFileSize(1024); // 1KB * * @group Files */ declare function humanFileSize(bytes: number, digits?: number, withSpace?: boolean): string; /** * Creates a new function that always returns `value`. * * @template T - The type of the value to return. * @param value - The value to return from the new function. * @returns Returns the new constant function. * * @group Utility Functions */ declare function constant(value: T): () => T; /** * Creates a new function that always returns `undefined`. * * @returns Returns the new constant function. * * @group Utility Functions */ declare function constant(): () => undefined; type WithCode = T & { code: string; }; declare function createFunction(fnName: string, code: string, ...args: any[]): WithCode; interface DebounceOptions { /** * An optional AbortSignal to cancel the debounced function. */ signal?: AbortSignal; /** * An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both. * If `edges` includes "leading", the function will be invoked at the start of the delay period. * If `edges` includes "trailing", the function will be invoked at the end of the delay period. * If both "leading" and "trailing" are included, the function will be invoked at both the start and end of the delay period. * @default ["trailing"] */ edges?: Array<'leading' | 'trailing'>; } interface DebouncedFunction void> { (...args: Parameters): void; /** * Schedules the execution of the debounced function after the specified debounce delay. * This method resets any existing timer, ensuring that the function is only invoked * after the delay has elapsed since the last call to the debounced function. * It is typically called internally whenever the debounced function is invoked. * * @returns {void} */ schedule: () => void; /** * Cancels any pending execution of the debounced function. * This method clears the active timer and resets any stored context or arguments. */ cancel: () => void; /** * Immediately invokes the debounced function if there is a pending execution. * This method also cancels the current timer, ensuring that the function executes right away. */ flush: () => void; } /** * Creates a debounced function that delays invoking the provided function until after `debounceMs` milliseconds * have elapsed since the last time the debounced function was invoked. The debounced function also has a `cancel` * method to cancel any pending execution. * * @template F - The type of function. * @param {F} func - The function to debounce. * @param {number} debounceMs - The number of milliseconds to delay. * @param {DebounceOptions} options - The options object * @param {AbortSignal} options.signal - An optional AbortSignal to cancel the debounced function. * @returns A new debounced function with a `cancel` method. * * @example * const debouncedFunction = debounce(() => { * console.log('Function executed'); * }, 1000); * * // Will log 'Function executed' after 1 second if not called again in that time * debouncedFunction(); * * // Will not log anything as the previous call is canceled * debouncedFunction.cancel(); * * // With AbortSignal * const controller = new AbortController(); * const signal = controller.signal; * const debouncedWithSignal = debounce(() => { * console.log('Function executed'); * }, 1000, { signal }); * * debouncedWithSignal(); * * // Will cancel the debounced function call * controller.abort(); * * @author es-toolkit * @group Utility Functions */ declare function debounce void>(func: F, debounceMs: number, { signal, edges }?: DebounceOptions): DebouncedFunction; /** * @group Utility Functions */ declare function isSuccess(value: T): value is ExecResultToSuccess; /** * @group Utility Functions */ declare function isSkip(value: T): value is ExecResultToSkip; /** * @group Utility Functions */ declare function stringifyExecResult(value: ExecResult): string; /** * Returns the input value unchanged. * * @template T - The type of the input value. * @param x - The value to be returned. * @returns The input value. * * @example * // Returns 5 * identity(5); * * @example * // Returns 'hello' * identity('hello'); * * @example * // Returns { key: 'value' } * identity({ key: 'value' }); * * @group Utility Functions */ declare function identity(x: T): T; /** * Creates a function that negates the result of the predicate function. * * @template F - The type of the function to negate. * @param func - The function to negate. * @returns The new negated function, which negates the boolean result of `func`. * * @example * const array = [1, 2, 3, 4, 5, 6]; * const isEven = (n: number) => n % 2 === 0; * const result = array.filter(negate(isEven)); * // result will be [1, 3, 5] * * @group Utility Functions */ declare function negate boolean>(func: F): F; type TypeOf = keyof TypeOfMap; type TypeOfMap = { null: null; undefined: undefined; object: Record; string: string; number: number; function: AnyFunction; bigint: bigint; boolean: boolean; symbol: symbol; date: Date; array: any[]; map: Map; weakmap: WeakMap; set: Set; weakset: WeakSet; unknown: unknown; }; /** * Typeof that you deserve * @group Utility Functions */ declare function typeOf(value: unknown): TypeOf; type StringifyOptions = { /** * Exclude empty values, checking by `isEmpty` * @default true */ excludeEmpty?: boolean; /** * Exclude values when equals with defaults */ excludeDefaults?: Record; }; /** * Simple query stringy interface that supports encoding/decoding of `Array`, `Set`, `Map`, `Object`, `BigInt` * * @example * // encode * qs.stringify({ page: 1, limit: 10 }); // 'page=1&limit=10' * * // decode * const defaults = { page: 1, limit: 10 }; * const params = qs.parse('page=5&limit=abc', defaults); // { page: 5, limit: 10 } * * @group Utility Functions */ declare const qs: { toParams: typeof toParams; stringify: typeof stringify; stringifyValue: typeof stringifyValue; parse: typeof parse; parseValue: typeof parseValue; merge: typeof merge; }; /** * Merge first level values */ declare function merge(...values: Record[]): Record; /** * Simple function to transform object into query string (not standards) */ declare function stringify(obj: Record, options?: StringifyOptions): string; /** * Prepare search params object */ declare function toParams(obj: Record, options?: StringifyOptions): Record; /** * Parse query string as is without type casting */ declare function parse(value: string): Record; /** * Parse query string and use default object as type cast schema */ declare function parse>(value: string, defaults: Partial): T; /** * Parse query params and use default object as type cast schema */ declare function parse>(value: Record, defaults: T): Partial; /** * Stringify value to use as query parameter */ declare function stringifyValue(value: unknown): string; /** * Parse string query value as a type */ declare function parseValue(value: any, asType: T): TypeOfMap[T] | undefined; type RetryOnErrorConfig = { /** * The function to execute before retry attempt; Allows to update parameters for the main function by returning then in an array */ beforeRetryCallback?: (attempt: number, lastAttempt: boolean) => Promise; /** * Error validation function. If returns true, the main callback's considered ready to be executed again */ shouldRetryBasedOnError?: (error: unknown, attempt: number) => boolean; /** * Number of attempts to execute a function */ maxAttempts?: number; /** * Number of retries until the execution fails (initial + retries) * @deprecated use `maxAttempts` */ maxRetriesNumber?: number; /** * Delay multiply factor */ delayFactor?: number; /** * Delay min milliseconds */ delayMinMs?: number; /** * Delay max milliseconds */ delayMaxMs?: number; }; /** * Wraps a function with retry logic. * * @example * const fn = await retryOnError({ * maxRetriesNumber: 10, * delayFactor: 2, * delayMinMs: 1000, * delayMaxMs: 3000, * shouldRetryBasedOnError(error, attemptNumber) { * return error.code !== 'RECORD_EXISTS'; * } * }, async () => { * await db.transactions.insert(doc); * }); * * await fn(); * * @group Utility Functions */ declare function retryOnError({ beforeRetryCallback, shouldRetryBasedOnError, maxAttempts, maxRetriesNumber, delayFactor, delayMaxMs, delayMinMs }: RetryOnErrorConfig, fn: T): (...args: Parameters) => Promise>>; interface ThrottleOptions { /** * An optional AbortSignal to cancel the debounced function. */ signal?: AbortSignal; /** * An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both. * If `edges` includes "leading", the function will be invoked at the start of the delay period. * If `edges` includes "trailing", the function will be invoked at the end of the delay period. * If both "leading" and "trailing" are included, the function will be invoked at both the start and end of the delay period. * @default ["leading", "trailing"] */ edges?: Array<'leading' | 'trailing'>; } interface ThrottledFunction void> { (...args: Parameters): void; cancel: () => void; flush: () => void; } /** * Creates a throttled function that only invokes the provided function at most once * per every `throttleMs` milliseconds. Subsequent calls to the throttled function * within the wait time will not trigger the execution of the original function. * * @template F - The type of function. * @param {F} func - The function to throttle. * @param {number} throttleMs - The number of milliseconds to throttle executions to. * @returns {(...args: Parameters) => void} A new throttled function that accepts the same parameters as the original function. * * @example * const throttledFunction = throttle(() => { * console.log('Function executed'); * }, 1000); * * // Will log 'Function executed' immediately * throttledFunction(); * * // Will not log anything as it is within the throttle time * throttledFunction(); * * // After 1 second * setTimeout(() => { * throttledFunction(); // Will log 'Function executed' * }, 1000); * * @author es-toolkit * @group Utility Functions */ declare function throttle void>(func: F, throttleMs: number, { signal, edges }?: ThrottleOptions): ThrottledFunction; /** * Determines if the window object is available in the global scope * * @group Predicates */ declare const isClient: boolean; /** * Returns `true` when value is not `undefined` * @group Predicates */ declare const isDef: (val?: T) => val is T; /** * Checks if the given value is a `null` or `undefined` * @group Predicates */ declare function isNullOrUndefined(value: unknown): value is undefined | null; /** * Checks if the given value is a `bigint` * @group Predicates */ declare const isBigInt: (val: any) => val is bigint; /** * Checks if the given value is a `boolean` * @group Predicates */ declare const isBoolean: (val: any) => val is boolean; /** * Checks if the given value is a `function` * @group Predicates */ declare const isFunction: (val: any) => val is T; /** * Checks if the given value is a `number` * * @example * console.log(isNumber(123)); // true * console.log(isNumber('abc')); // false * console.log(isNumber(NaN)); // false * * @group Predicates */ declare const isNumber: (val: any) => val is number; /** * Checks if the given value is a `Infinity` number. * * @example * console.log(isInfinity(123)); // false * console.log(isNumber(Infinity)); // true * console.log(isNumber(-Infinity)); // true * * @group Predicates */ declare const isInfinity: (val: any) => val is number; /** * Checks if the given value is a `string` * @group Predicates */ declare const isString: (val: unknown) => val is string; /** * Checks if the given value is a `object` * @group Predicates */ declare const isObject: (val: any) => val is object; /** * Checks if the given value is a plain `object` * @group Predicates */ declare const isPlainObject: (val: any) => val is object; /** * Checks if the given value is valid `Date` * @group Predicates */ declare const isDate: (val: any) => val is Date; /** * Function that does nothing * @group Utility Functions */ declare const noop: () => void; /** * Checks if the given value is a `Error` * @group Predicates */ declare const isError: (val: any) => val is Error; /** * Checks if the given value is a `symbol` * @group Predicates */ declare const isSymbol: (val: any) => val is Symbol; /** * Checks if the given value is a `Set`. * @group Predicates */ declare const isSet: (val: any) => val is Set; /** * Checks if the given value is a `RegExp`. * @group Predicates */ declare const isRegExp: (val: any) => val is RegExp; /** * Checks if the given value is a `WeekSet`. * @group Predicates */ declare const isWeakSet: (val: any) => val is WeakSet; /** * Checks if the given value is a `Map`. * @group Predicates */ declare const isMap: (val: any) => val is Map; /** * Checks if the given value is a `WeakMap`. * @group Predicates */ declare const isWeakMap: (val: any) => val is WeakMap; /** * Checks if two values are equal, including support for `Date`, `RegExp`, and deep object comparison. * * @param {unknown} a - The first value to compare. * @param {unknown} b - The second value to compare. * @returns {boolean} `true` if the values are equal, otherwise `false`. * * @example * isEqual(1, 1); // true * isEqual({ a: 1 }, { a: 1 }); // true * isEqual(/abc/g, /abc/g); // true * isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true * isEqual([1, 2, 3], [1, 2, 3]); // true * * @group Predicates */ declare function isEqual(a: unknown, b: unknown): boolean; /** * Checks if a given value is empty. * * Support for `Array`, `Object`, `string` `Map`, `Set`. * * @example * isEmpty(); // true * isEmpty(null); // true * isEmpty(''); // true * isEmpty([]); // true * isEmpty({}); // true * isEmpty(new Map()); // true * isEmpty(new Set()); // true * isEmpty('hello'); // false * isEmpty([1, 2, 3]); // false * isEmpty({ a: 1 }); // false * isEmpty(new Map([['key', 'value']])); // false * isEmpty(new Set([1, 2, 3])); // false * * @group Predicates */ declare const isEmpty: (obj: any) => boolean; /** * Checks if the given value is a `Promise` * @group Predicates */ declare function isPromise(value: unknown): value is Promise; /** * Checks whether a value is a JavaScript primitive. * * JavaScript primitives include null, undefined, strings, numbers, booleans, symbols, and bigints. * @group Predicates */ declare const isPrimitive: (value: unknown) => value is Primitive; /** * Checks if a value is a TypedArray. * @param x The value to check. * @returns Returns true if `x` is a TypedArray, false otherwise. * * @example * const arr = new Uint8Array([1, 2, 3]); * isTypedArray(arr); // true * * const regularArray = [1, 2, 3]; * isTypedArray(regularArray); // false * * const buffer = new ArrayBuffer(16); * isTypedArray(buffer); // false * * @group Predicates */ declare function isTypedArray(x: unknown): x is Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | BigUint64Array | Int8Array | Int16Array | Int32Array | BigInt64Array | Float32Array | Float64Array; /** * Checks if the given value is a Buffer instance. * * This function tests whether the provided value is an instance of Buffer. * It returns `true` if the value is a Buffer, and `false` otherwise. * * This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Buffer`. * * @param x - The value to check if it is a Buffer. * @returns Returns `true` if `x` is a Buffer, else `false`. * * @example * const buffer = Buffer.from("test"); * console.log(isBuffer(buffer)); // true * * const notBuffer = "not a buffer"; * console.log(isBuffer(notBuffer)); // false * * @group Predicates */ declare const isBuffer: (value: unknown) => value is globalThis.Buffer; /** * Checks if the current environment is Node.js. * * This function checks for the existence of the `process.versions.node` property, * which only exists in Node.js environments. * * @returns {boolean} `true` if the current environment is Node.js, otherwise `false`. * * @example * if (isNode()) { * console.log('This is running in Node.js'); * const fs = import('node:fs'); * } * * @group Predicates */ declare function isNode(): boolean; type LogLevel = Exclude; /** * Set global log level. * @group Utility Functions */ declare const setLoggerLevel: (level: LogLevel) => void; /** * Set global log level. * @group Utility Functions */ declare const getLoggerLevel: () => LogLevel; /** * Create pretty simple `console.log` wrapper interface. * * @example * const log = logger('UserService'); * * log.info('Create user: %s', 'user_1'); // Create user: %s * * @group Utility Functions */ declare const logger: (...baseArgs: any[]) => Logger; /** * Check if bits are set in `number` bitmask * * @example * const scope = (1 << 1 | 1 << 2 | 1 << 3); * * checkBitmask(scope, 1 << 2); // true * checkBitmask(scope, 1 << 5); // false * * @group Numbers */ declare function checkBitmask(scope: number, flag: number): boolean; /** * Check if bits are set in `bigint` bitmask * * @example * const scope = (1n << 1n | 1n << 2n | 1n << 3n); * * checkBitmask(scope, 1n << 2n); // true * checkBitmask(scope, 1n << 5n); // false * * @group Numbers */ declare function checkBitmask(scope: bigint, flag: bigint): boolean; /** * Rounds the given value to a specified range. If the value is less than the minimum, * it returns the minimum. If the value is greater than the maximum, it returns the maximum. * If the value is within the range, it returns the original value. * * @param {number} num - The number to be clamped. * @param {number} min - The minimum value of the range. * @param {number} max - The maximum value of the range. * @returns {number} - The clamped value within the specified range. * * @example * const min = 5; * const max = 10; * * // Returns: 7 (within range) * clamp(7, min, max); * * // Returns: 10 (clamped to max) * clamp(15, min, max); * * // Returns: 5 (clamped to min) * clamp(3, min, max); * * @group Numbers */ declare const clamp: (num: number, min: number, max: number) => number; interface RandomizerOptions { min: number; max: number; pregenerateAmount: number; transform: (value: number) => number; } declare class Randomizer { private _pool; private _step; private _min; private _max; private _pregenerateAmount; private _transform; constructor({ min, max, pregenerateAmount, transform }: RandomizerOptions); /** * Returns the current step of the randomizer. * * @returns {number} The current step. */ getCurrentStep(): number; /** * Sets the current step of the randomizer. * * @param {number} value - The step to set. * @throws {Error} If the provided value is not a valid number or less than 0. */ setCurrentStep(value: number): void; /** * Retrieves a random number either from the current step or a specific step if provided. * * @param {number} [fromStep] - The step from which to retrieve the random number (optional). * @returns {number} The random number at the current or specified step. */ get(fromStep?: number): number; /** * Resets the current step to 0. */ resetStep(): void; /** * Resets the random number pool, clearing and repopulating it with new random values. */ resetPool(): void; private _rand; private _lookup; } /** * Creates a random number generator with step control and optional transformation. * Allows caching of generated numbers for efficiency, with optional pregeneration and transformation. * * @param {RandomizerOptions} options - Configuration for the randomizer. * @param {number} options.min - Minimum value for the random number. * @param {number} options.max - Maximum value for the random number. * @param {number} [options.pregenerateAmount=100] - Number of random numbers to pregenerate and cache. * @param {(value: number) => number} [options.transform] - A function to transform the generated random number. * @returns {Randomizer} - The randomizer object with step control and number generation. * * * @example * // Basic usage of the randomizer * const randomizer = createRandomizer({ * min: 1, * max: 10, * pregenerateAmount: 5 * }); * * // Get the random number at the current step * console.log(randomizer.get()); // e.g., returns 3 * * // Get the random number at a specific step * console.log(randomizer.get(2)); // e.g., returns 7 * * // Get the current step * console.log(randomizer.getCurrentStep()); // returns the current step (e.g., 1) * * // Set the current step to 3 * randomizer.setCurrentStep(3); * * // Get the random number at step 3 * console.log(randomizer.get()); // returns the value for step 3 * * @example * // Usage with a transformation function * const randomizerWithTransform = createRandomizer({ * min: 1, * max: 10, * pregenerateAmount: 5, * transform: (value) => value * 2 * }); * * // Get a transformed random number at the current step * console.log(randomizerWithTransform.get()); // e.g., returns 6 (original value 3 transformed by multiplying by 2) * * // Reset the step to 0 * randomizerWithTransform.resetStep(); * console.log(randomizerWithTransform.get()); // returns the random number at step 0 * * @group Numbers */ declare function createRandomizer({ min, max, pregenerateAmount, transform }: Partial): Randomizer; /** * A class that allows you to calculate the running mean (average) of a set of numbers. * It computes the average as new numbers are added and can also reset the progress. * * @example * // Basic usage to calculate running mean * const avg = findMean(); * avg.push(1, 2, 3); * console.log(avg.value); // Output: 2 (average of 1, 2, 3) * * @example * // Reset the calculation with an initial value * const avg = findMean(10); * avg.push(20); * console.log(avg.value); // Output: 15 (average of 10, 20) * console.log(avg.count); // Output: 2 (two values added) */ declare class FindMean { #private; constructor(initialValue?: number); /** * Resets the current progress of the mean calculation. * Optionally, you can pass an initial value to start the calculation. * * @param {number} [initialValue] - The initial value to start the mean calculation with. * @returns {FindMean} The current instance of the FindMean class for chaining. * * @example * const avg = findMean(); * avg.push(2, 4); * avg.reset(); * console.log(avg.value); // Output: 0 */ reset(initialValue?: number): FindMean; /** * Retrieves the current mean value (average). * * @returns {number} The current mean value. * * @example * const avg = findMean(); * avg.push(5, 10); * console.log(avg.value); // Output: 7.5 (average of 5, 10) */ get value(): number; /** * Retrieves the count of numbers added so far. * * @returns {number} The count of numbers in the set. * * @example * const avg = findMean(); * avg.push(10, 20); * console.log(avg.count); // Output: 2 */ get count(): number; /** * Adds values to the set and updates the running mean. * * @param {...number} values - The values to add to the set. * @returns {FindMean} The current instance of the FindMean class for chaining. * * @example * const avg = findMean(); * avg.push(1, 2, 3); * console.log(avg.value); // Output: 2 (average of 1, 2, 3) * console.log(avg.count); // Output: 3 */ push(...values: number[]): FindMean; } /** * Calculate the running mean (average) of a set of numbers. * * @param {number} [value] - An optional starting value for the mean calculation. * @returns {FindMean} A new instance of FindMean class to calculate running mean. * * @example * // Create a FindMean instance and add values to calculate the average * const avg = findMean(); * avg.push(3, 3, 3.3); * console.log(avg.value); // Output: 3.1 * console.log(avg.count); // Output: 3 * * @group Numbers */ declare function findMean(value?: number): FindMean; interface FormatNumber { thousands: string; decimal: string; } /** * Formats a number (or string representing a number) into a string with thousands separators and optional decimal points. * The function supports customizing the formatting style using the `FormatNumber` object. * * @param {number | string} value - The number or string to format. * If a string is passed, it is parsed to a number before formatting. * @param {FormatNumber} [format=defaultFormat] - The format settings for thousands and decimal separators. * By default, it uses the `{ thousands: ',', decimal: '.' }`. * * @returns {string} The formatted number string with appropriate thousands separators and decimal formatting. * * @example * // Format a number with default thousands separator * formatNumber(1500); * // Returns: '1,500' * * @example * // Format a number with a custom format (e.g., using a comma as the thousands separator) * formatNumber(1500.75, { thousands: ' ', decimal: '.' }); * // Returns: '1 500.75' * * @group Numbers */ declare function formatNumber(value: number | string, format?: FormatNumber): string; interface FormatMoney extends FormatNumber { symbol: string; symbolBefore?: boolean; } /** * Formats a given number (amount of money) as a currency string. * This function supports both integer and floating-point representations of money * and automatically applies the appropriate currency formatting for the specified currency code. * * @param {number} amount - The amount of money to format (in cents or as a floating-point value). * @param {string | FormatMoney} formatOrCode - The currency format or the currency code (e.g., 'USD'). * If the format is passed as a string, the function will look up the format for that currency code. * @param {boolean} [intMode=false] - When set to `true`, the amount is considered to be in integer form (i.e., cents). * The value will be divided by 100 to convert it to a decimal format. * * @returns {string} The formatted money string, including the currency symbol and the properly formatted number. * * @example * // Basic formatting with USD currency * formatMoney(1500, 'USD'); * // Returns: '$1,500' * * @example * // Formatting when the amount is in integer form (representing cents) * formatMoney(1599, 'USD', true); * // Returns: '$15.99' * * @group Numbers */ declare function formatMoney(amount: number, formatOrCode?: string | FormatMoney, intMode?: boolean): string; /** * Returns a random integer between min (inclusive) and max (inclusive). * The value is no lower than min (or the next integer greater than min * if min isn't an integer) and no greater than max (or the next integer * lower than max if max isn't an integer). * Using Math.round() will give you a non-uniform distribution! * * @example * getRandomInt(0, 100); // random int between 0 - 100 * * @group Numbers */ declare function getRandomInt(min: number, max: number): number; /** * Humanizes large numbers into a more readable format using suffixes like K, M, B, T (thousand, million, billion, trillion). * * @param {number | string} input - The number or string to humanize. * If the input is a string, it will be parsed into a number. * @param {number} [decimals=1] - The number of decimal places to display. Default is 1. * @returns {string} A humanized string representation of the number. * * @example * humanize(1000000); * // Returns: '1M' * * @example * humanize(1234567890); * // Returns: '1.2B' * * @example * humanize(9876543210, 2); * // Returns: '9.88B' * * @example * humanize(500); * // Returns: '500' * * @example * humanize('1000000'); * // Returns: '1M' * * @group Numbers */ declare function humanize(input: number | string, decimals?: number): string; /** * Parses all numbers from a given string and returns them as an array of numbers. * Supports dot decimals and ignores commas unless they appear as part of a number format. * Returns an empty array when the input is invalid or no numbers are found. * * @param {unknown} input - The input value to parse numbers from. * @returns {number[]} - An array of parsed numbers. Returns an empty array if no numbers are found. * * @example * parseAllNumbers("The temperature is -23.5°C and humidity is 60%."); * // Returns: [-23.5, 60] * * @example * parseAllNumbers("No numbers here!"); * // Returns: [] * * @example * parseAllNumbers(42); * // Returns: [42] * * @example * parseAllNumbers("1,234 and 56.78 are numbers"); * // Returns: [1.234, 56.78] * * @example * parseAllNumbers(["Invalid type"]); * // Returns: [] * * @group Numbers */ declare function parseAllNumbers(value: unknown): number[]; /** * Safely parses a percentage value and returns a number between 0 and 100. * It accepts both string and numeric input, automatically handling the '%' sign if present. * If the value is not a valid percentage, it returns 0. * * @param {unknown} value - The value to parse, which can be a string (e.g., '99%') or a number (e.g., 45). * @returns {number} A parsed percentage value, constrained between 0 and 100. * If the input is invalid or cannot be parsed, it returns 0. * * @example * parsePercentage('99%'); * // Returns: 99 * * @example * parsePercentage('150%'); * // Returns: 100 (clamped to the maximum allowed value) * * @example * parsePercentage('50.5%'); * // Returns: 50.5 * * @example * parsePercentage('abc'); * // Returns: 0 (invalid input) * * @example * parsePercentage(80); * // Returns: 80 (valid number input) * * @group Numbers */ declare function parsePercentage(value: unknown): number; /** * Calculates the specified percentage of a given value. * The result is the value multiplied by the percentage divided by 100. * Optionally rounds the result to a specified number of decimal places. * * @param {number} value - The value from which the percentage will be calculated. * @param {number} percent - The percentage to calculate from the value. * @param {number} [digits] - Optional. The number of decimal places to round the result to. If not provided, the result will not be rounded. * @returns {number} The calculated percentage of the value. If `digits` is provided, the result is rounded to the specified decimal places. * * @example * percentOf(200, 20); * // Returns: 40 (20% of 200) * * @example * percentOf(200, 20, 2); * // Returns: 40.00 (20% of 200 rounded to 2 decimal places) * * @example * percentOf(150, 15); * // Returns: 22.5 (15% of 150) * * @example * percentOf(1000, 10, 1); * // Returns: 100.0 (10% of 1000 rounded to 1 decimal place) * * @group Numbers */ declare function percentOf(value: number, percent: number, digits?: number): number; /** * Rounds a given number to a specified number of decimal places. * The rounding is done using a method that shifts the decimal point, rounds the number, and then shifts it back. * * @param {number} value - The number to be rounded. * @param {number} [digits=2] - The number of decimal places to round to. Defaults to 2 if not provided. * @returns {number} The rounded number with the specified number of decimal places. * * @example * round2digits(3.3333333, 1); * // Returns: 3.3 * * @example * round2digits(3.3333333, 2); * // Returns: 3.33 * * @example * round2digits(3.3333333, 3); * // Returns: 3.333 * * @example * round2digits(3.789, 0); * // Returns: 4 (rounded to the nearest integer) * * @group Numbers */ declare function round2digits(value: number, digits?: number): number; /** * Removes properties with empty values from an object. * * This function iterates over the object's keys and deletes any property whose value * is considered "empty" (e.g., `null`, `undefined`, `[]`, `{}`, `''`, `false`). * * ⚠️ **Mutates the original object**: The input object is directly modified, and properties * are removed from it. * * @param {Record} obj - The object to clean up, where empty fields will be removed. * @returns {Record} The cleaned object with empty fields removed. * * @example * const user = { id: 1, name: 'Andrew', roles: [], address: null }; * cleanEmpty(user); * * console.log(user); // Outputs: { id: 1, name: 'Andrew' } * * @example * const product = { name: 'Laptop', description: '', price: 1000, tags: [] }; * cleanEmpty(product); * * console.log(product); // Outputs: { name: 'Laptop', price: 1000 } * * @group Object */ declare function cleanEmpty(obj: Record): Record; /** * Removes all properties from the given object, including symbol keys. * * This function deletes all enumerable properties, both string and symbol keys, from the * input object. The object is directly mutated by this operation. * * ⚠️ **Mutates the original object**: The function modifies the input object in place. * * ⚠️ **Removes symbol keys**: Symbol-based keys are also deleted, unlike typical object * iteration methods. * * @param {Record} input - The object to clean up. After execution, it will be empty. * @returns {void} This function does not return a value, as it mutates the input object directly. * * @example * const user = { id: 1, name: 'Andrew', roles: [], [Symbol('unique')]: 'symbolValue' }; * cleanObject(user); * * console.log(user); // Outputs: {} * * @example * const settings = { theme: 'dark', [Symbol('private')]: 'secret' }; * cleanObject(settings); * * console.log(settings); // Outputs: {} * * @group Object */ declare const cleanObject: (input: Record) => void; /** * Performs a deep merge of the source object into the destination object. * * This function recursively copies properties from the source object to the destination object. * If a property is an object itself, it will recursively merge its properties. Otherwise, * the value will be directly assigned to the destination object. * * ⚠️ **Mutates the destination object**: The destination object is modified in place. * * @param {object} dest - The target object that will be modified with properties from the source. * @param {object} source - The source object whose properties will be copied to the destination. * @returns {void} This function does not return a value, as it mutates the destination object. * * @example * const user = { * id: 1, * name: 'Andrew', * data: { a: 1, b: 2 }, * }; * * deepAssign(user, { data: { c: 3 } }); * * console.log(user); * // Outputs: '{ id: 1, name: 'Andrew', data: { a: 1, b: 2, c: 3 } }' * * @example * const config = { theme: { dark: true }, version: '1.0' }; * const updates = { theme: { light: false }, version: '2.0' }; * * deepAssign(config, updates); * * console.log(config); * // Outputs: '{ theme: { dark: true, light: false }, version: '2.0' }' * * @group Object */ declare const deepAssign: (dest: object, source: object) => void; /** * Recursively clones the provided value, creating a deep copy. * * This function performs a deep clone of the provided value. Any nested objects, arrays, or other complex types will be cloned recursively, * ensuring that the original value and the cloned value are completely independent. * * @param {T} value - The value to recursively clone. Can be any type (object, array, primitive, etc.). * @returns {T} Returns a new deeply cloned instance of the original value. * * @example * const original = { name: 'Alice', details: { age: 25, country: 'Wonderland' } }; * const cloned = deepClone(original); * * cloned.details.age = 30; * console.log(original.details.age); // 25 * console.log(cloned.details.age); // 30 * * @example * const arr = [1, [2, 3], 4]; * const clonedArr = deepClone(arr); * clonedArr[1][0] = 99; * console.log(arr[1][0]); // 2 * console.log(clonedArr[1][0]); // 99 * * @group Object */ declare const deepClone: (value: T) => T; type WithCustomizer = (value: any, key: PropertyKey | undefined, obj: T, stack: Map) => any; type WithCustomizerFactory = () => WithCustomizer; type WithCustomizerValue = (WithCustomizer | WithCustomizerFactory) | Readonly<(WithCustomizer | WithCustomizerFactory)[]>; /** * Recursively clones the provided value with a customizer function that allows for transformation of certain values during the cloning process. * * This function deep clones the value while providing a way to customize the cloning behavior of certain properties or elements. * The `customizer` function will be called for each value being cloned, and if the customizer function returns a value other than `undefined`, * the original value will be replaced with the returned value. This allows for specific modifications to parts of the structure being cloned. * * @param {T} value - The value to recursively clone. Can be any type (object, array, primitive, etc.). * @param {WithCustomizerValue} customizer - A function to customize the cloning process. It receives the current value and key, and must return * either a modified value or `undefined` (to keep the original value). * * @returns {T} Returns a new deep clone of the original value, with customizations applied as per the `customizer` function. * * @example * const original = { name: 'Alice', age: 30, details: { country: 'Wonderland', city: 'London' } }; * * const customizer = (value, key) => { * if (key === 'city') return 'Paris'; // Customizing the 'city' field to 'Paris'. * }; * * const cloned = deepCloneWith(original, customizer); * console.log(cloned.details.city); // 'Paris' * console.log(original.details.city); // 'London' (original is unchanged) * * @example * const arr = [1, [2, 3], 4]; * * const customizer = (value) => { * if (Array.isArray(value)) return value.map(item => item * 2); // Doubling the numbers inside arrays. * }; * * const clonedArr = deepCloneWith(arr, customizer); * console.log(clonedArr); // [1, [4, 6], 4] * console.log(arr); // [1, [2, 3], 4] (original is unchanged) * * @group Object */ declare function deepCloneWith(value: T, customizer: WithCustomizerValue): T; declare function createDeepCloneWith(customizer: WithCustomizerValue): (value: T) => T; declare function isCustomizerFactory(value: unknown): value is WithCustomizerFactory; declare function createCustomizer(fn: WithCustomizer): WithCustomizer; declare function createCustomizerFactory(fn: (...args: any[]) => WithCustomizer): WithCustomizerFactory; interface SecureCustomizerOptions { /** * @default true */ normalizeError?: boolean; } /** * Creates a {@link WithCustomizerFactory} that redacts sensitive property values * and handles circular references when used with {@link deepCloneWith}. * * - **Primitive values** whose key matches one of `properties` are replaced with * `<** secure **>` (key comparison is not case-insensitive). * - **Circular references** are replaced with `<** circular **>`. * - **Error objects** are normalised to a plain `{ message, stack, name, cause }` * shape unless `normalizeError` is set to `false`. * * @param properties - Property keys to redact (case-insensitive for strings). * @param opts - Optional behaviour flags. * * @example * // Basic redaction * const customizer = createSecureCustomizer(['password', 'token']); * const result = deepCloneWith( * { user: 'alice', password: 'secret', token: 'abc123' }, * customizer, * ); * // → { user: 'alice', password: '<** secure **>', token: '<** secure **>' } * * @example * // Nested objects — redaction applies at any depth * const customizer = createSecureCustomizer(['apiKey']); * const result = deepCloneWith( * { service: { apiKey: 'key-xyz', url: 'https://api.example.com' } }, * customizer, * ); * // → { service: { apiKey: '<** secure **>', url: 'https://api.example.com' } } * * @example * // Error normalisation (on by default) * const customizer = createSecureCustomizer([]); * const result = deepCloneWith({ err: new Error('oops') }, customizer); * // → { err: { message: 'oops', name: 'Error', stack: '...', cause: undefined } } * * @example * // Disable Error normalisation * const customizer = createSecureCustomizer([], { normalizeError: false }); * const result = deepCloneWith({ err: new Error('oops') }, customizer); * // → { err: Error('oops') } — the Error instance is preserved * * @group Object */ declare function createSecureCustomizer(properties: PropertyKey[], opts?: SecureCustomizerOptions): WithCustomizerFactory; /** * Recursively assigns default properties. * @param object The destination object. * @param sources The source objects. * @return Returns object. * * @example * const obj = { name: 'Alice', age: 30 }; * const defaults = { name: 'Bob', age: 25, country: 'Wonderland' }; * * deepDefaults(obj, defaults); * console.log(obj); * // Output: { name: 'Alice', age: 30, country: 'Wonderland' } * // The 'name' and 'age' properties are not overwritten since they already exist. * * @example * const obj = { user: { name: 'Alice' } }; * const defaults = { user: { age: 25 } }; * * deepDefaults(obj, defaults); * console.log(obj); * // Output: { user: { name: 'Alice', age: 25 } } * // The 'age' property is added to 'user', while 'name' remains unchanged. * * @group Object */ declare const deepDefaults: (target: any, ...sources: any[]) => T; /** * Recursively freezes an object or array, making it immutable at all levels. * * This function is similar to `Object.freeze()`, but instead of freezing only the top-level * properties of an object, it recursively freezes every nested object or array, ensuring * that no properties or elements can be modified at any depth. * * **Important**: * - Once frozen, attempting to modify any property or element of the object will result in an error in strict mode. * - If a property of an object or an element of an array is itself an object, it will also be frozen. * * @param {T} value - The object or array to freeze deeply. * @returns {T} The frozen object or array, which is also deeply immutable. * * @example * const config = deepFreeze({ * db: { uri: '' }, * }); * * config.db.uri = 'test'; // Error: Cannot assign to read-only property 'uri' of object * * @example * const arr = deepFreeze([ { name: 'Alice' }, { name: 'Bob' } ]); * arr[0].name = 'Charlie'; // Error: Cannot assign to read-only property 'name' of object * * @group Object */ declare function deepFreeze(value: T): T; /** * Define not enumerable property in object. * * @example * const USER_SYM = Symbol(); * const user = { id: 1, name: 'Andrew' }; * * // define hidden marker * def(user, USER_SYM, true); * * console.log(user[USER_SYM] === true); // true * * @group Object */ declare const def: (obj: object, key: string | symbol, value: any, writable?: boolean) => void; /** * @example * const PERMISSIONS = { * USER_CREATE: 1 << 0, * USER_UPDATE: 1 << 1, * USER_DELETE: 1 << 2, * USER_LIST: 1 << 4, * } as const; * * const scope = PERMISSIONS.USER_CREATE | PERMISSIONS.USER_LIST; * * // { USER_CREATE: true, USER_UPDATE: false, USER_DELETE: false, USER_LIST: true } * const flags = flagsToMap(scope, PERMISSIONS); */ declare function flagsToMap(value: number, bitmaskMap: Record): Record; declare function flagsToMap(value: bigint, bitmaskMap: Record): Record; interface FlattenOptions { /** * Character to separate the flattened keys */ separator?: string; /** * Prefix to add to the flattened keys */ initialPrefix?: string; /** * Whether to include arrays in the flattened result */ withArrays?: boolean; /** * Custom function to check if a value is an object */ isObjectCompare?: (value: unknown) => boolean; } /** * Flattens a nested object into a single-level object, converting nested properties * into key-value pairs with keys representing the property path. * * By default, nested objects are flattened with an underscore (`_`) separator. * Arrays can also be flattened into indexed keys. A custom function can be provided * to determine if a value should be treated as an object. * * **Important**: * - Nested objects are flattened with keys joined by the `separator` (default: `_`). * - Arrays are flattened by their indices (e.g., `array[0]` becomes `array_0`). * - A custom `isObjectCompare` function can be provided to determine whether a value * should be treated as an object. * * @param {Record} obj - The object to flatten. * @param {FlattenOptions} options - Optional configuration for flattening behavior. * @param {string} [options.separator='_'] - Separator for flattening object keys (default is '_'). * @param {string} [options.initialPrefix=''] - Prefix to prepend to flattened keys (default is ''). * @param {boolean} [options.withArrays=true] - Whether to include arrays in the flattened result (default is true). * @param {(value: unknown) => boolean} [options.isObjectCompare=isObject] - Custom function to check if a value is an object. * @returns {Record} - The flattened object. * * @example * flatten({ * name: 'Andrew', * config: { * canReadPost: true, * canUpdatePost: true, * } * }); * // Result: * // { * // 'name': 'Andrew', * // 'config_canReadPost': true, * // 'config_canUpdatePost': true, * // } * * @example * flatten( * { user: { name: 'Jane', profile: { age: 30 } } }, * { separator: '-', initialPrefix: 'root-' } * ); * // Returns: * // { 'root-user-name': 'Jane', 'root-user-profile-age': 30 } * * @group Object * @author lukeed */ declare function flatten(obj: Record, { separator, initialPrefix, withArrays, isObjectCompare }?: FlattenOptions): Record; type GetFieldTypeOfArrayLikeByKey = K extends number ? T[K] : K extends `${infer N extends number}` ? T[N] : K extends keyof T ? T[K] : undefined; type GetFieldTypeOfStringByKey = K extends number ? T[K] : K extends `${infer N extends number}` ? T[N] : K extends keyof T ? T[K] : undefined; type GetFieldTypeOfNarrowedByKey = T extends unknown[] ? GetFieldTypeOfArrayLikeByKey : T extends string ? GetFieldTypeOfStringByKey : K extends keyof T ? T[K] : K extends number ? `${K}` extends keyof T ? T[`${K}`] : undefined : K extends `${infer N extends number}` ? N extends keyof T ? T[N] : undefined : undefined; type GetFieldTypeOfNarrowedByDotPath = P extends `${infer L}.${infer R}` ? GetFieldType, R, 'DotPath'> : GetFieldTypeOfNarrowedByKey; type GetFieldTypeOfNarrowedByLcKR = '' extends R ? GetFieldType, K, 'Key'> : R extends `.${infer Rc}` ? GetFieldType, K, 'Key'>, Rc> : GetFieldType, K, 'Key'>, R>; type GetFieldTypeOfNarrowedByLKR = '' extends L ? '' extends R ? GetFieldTypeOfNarrowedByKey : R extends `.${infer Rc}` ? GetFieldType, Rc> : GetFieldType, R> : L extends `${infer Lc}.` ? GetFieldTypeOfNarrowedByLcKR : GetFieldTypeOfNarrowedByLcKR; type GetFieldTypeOfNarrowed = XT extends 'Key' ? GetFieldTypeOfNarrowedByKey : XT extends 'DotPath' ? GetFieldTypeOfNarrowedByDotPath : X extends `${infer L}['${infer K}']${infer R}` ? GetFieldTypeOfNarrowedByLKR : X extends `${infer L}["${infer K}"]${infer R}` ? GetFieldTypeOfNarrowedByLKR : X extends `${infer L}[${infer K}]${infer R}` ? GetFieldTypeOfNarrowedByLKR : GetFieldTypeOfNarrowedByDotPath; type GetFieldTypeOfObject = Extract extends never ? GetFieldTypeOfNarrowed : GetFieldTypeOfNarrowed, X, XT> | GetFieldTypeOfNarrowed, X, XT>; type GetFieldTypeOfPrimitive = Extract extends never ? T extends never ? never : undefined : (Exclude extends never ? never : undefined) | GetFieldTypeOfNarrowed, X, XT>; type GetFieldType = Extract extends never ? GetFieldTypeOfPrimitive : GetFieldTypeOfPrimitive, X, XT> | GetFieldTypeOfObject, X, XT>; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. * * @template TObject * @template TKey * @param object - The object to query. * @param path - The path of the property to get. * @returns Returns the resolved value. * * @example * const object = { 'a': [{ 'b': { 'c': 3 } }] }; * get(object, 'a[0].b.c'); * // => 3 * * @group Object */ declare function get(object: TObject, path: TKey | [TKey]): TObject[TKey]; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. * * @template TObject * @template TKey * @param object - The object to query. * @param path - The path of the property to get. * @returns Returns the resolved value. * * @example * const object = { 'a': [{ 'b': { 'c': 3 } }] }; * get(object, 'a[0].b.c'); * // => 3 * * @group Object */ declare function get(object: TObject | null | undefined, path: TKey | [TKey]): TObject[TKey] | undefined; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. * * @template TObject * @template TKey * @template TDefault * @param object - The object to query. * @param path - The path of the property to get. * @param defaultValue - The value returned if the resolved value is undefined. * @returns Returns the resolved value. * * @example * const object = { 'a': [{ 'b': { 'c': 3 } }] }; * get(object, 'a[0].b.c', 'default'); * // => 3 * * @group Object */ declare function get(object: TObject | null | undefined, path: TKey | [TKey], defaultValue: TDefault): Exclude | TDefault; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. * * @template TObject * @template TKey1 * @template TKey2 * @param object - The object to query. * @param path - The path of the property to get. * @returns Returns the resolved value. * * @example * const object = { 'a': { 'b': 2 } }; * get(object, ['a', 'b']); * // => 2 * * @group Object */ declare function get(object: TObject, path: [TKey1, TKey2]): TObject[TKey1][TKey2]; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. * * @template TObject * @template TKey1 * @template TKey2 * @param object - The object to query. * @param path - The path of the property to get. * @returns Returns the resolved value. * * @example * const object = { 'a': { 'b': 2 } }; * get(object, ['a', 'b']); * // => 2 * * @group Object */ declare function get>(object: TObject | null | undefined, path: [TKey1, TKey2]): NonNullable[TKey2] | undefined; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. * * @template TObject * @template TKey1 * @template TKey2 * @template TDefault * @param object - The object to query. * @param path - The path of the property to get. * @param defaultValue - The value returned if the resolved value is undefined. * @returns Returns the resolved value. * * @example * const object = { 'a': { 'b': 2 } }; * get(object, ['a', 'b'], 'default'); * // => 2 * * @group Object */ declare function get, TDefault>(object: TObject | null | undefined, path: [TKey1, TKey2], defaultValue: TDefault): Exclude[TKey2], undefined> | TDefault; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. * * @template TObject * @template TKey1 * @template TKey2 * @template TKey3 * @param object - The object to query. * @param path - The path of the property to get. * @returns Returns the resolved value. * * @example * const object = { 'a': { 'b': { 'c': 3 } } }; * get(object, ['a', 'b', 'c']); * // => 3 * * @group Object */ declare function get(object: TObject, path: [TKey1, TKey2, TKey3]): TObject[TKey1][TKey2][TKey3]; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. * * @template TObject * @template TKey1 * @template TKey2 * @template TKey3 * @param object - The object to query. * @param path - The path of the property to get. * @returns Returns the resolved value. * * @example * const object = { 'a': { 'b': { 'c': 3 } } }; * get(object, ['a', 'b', 'c']); * // => 3 * * @group Object */ declare function get, TKey3 extends keyof NonNullable[TKey2]>>(object: TObject | null | undefined, path: [TKey1, TKey2, TKey3]): NonNullable[TKey2]>[TKey3] | undefined; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. * * @template TObject * @template TKey1 * @template TKey2 * @template TKey3 * @template TDefault * @param object - The object to query. * @param path - The path of the property to get. * @param defaultValue - The value returned if the resolved value is undefined. * @returns Returns the resolved value. * * @example * const object = { 'a': { 'b': { 'c': 3 } } }; * get(object, ['a', 'b', 'c'], 'default'); * // => 3 * * @group Object */ declare function get, TKey3 extends keyof NonNullable[TKey2]>, TDefault>(object: TObject | null | undefined, path: [TKey1, TKey2, TKey3], defaultValue: TDefault): Exclude[TKey2]>[TKey3], undefined> | TDefault; /** * Gets the value at path of object. * * @template TObject * @template TKey1 * @template TKey2 * @template TKey3 * @template TKey4 * @param object - The object to query. * @param path - The path of the property to get. * @returns Returns the resolved value. * * @example * const object = { 'a': { 'b': { 'c': { 'd': 4 } } } }; * get(object, ['a', 'b', 'c', 'd']); * // => 4 * * @group Object */ declare function get(object: TObject, path: [TKey1, TKey2, TKey3, TKey4]): TObject[TKey1][TKey2][TKey3][TKey4]; /** * Gets the value at path of object. If the resolved value is undefined, undefined is returned. * * @template TObject * @template TKey1 * @template TKey2 * @template TKey3 * @template TKey4 * @param object - The object to query. * @param path - The path of the property to get. * @returns Returns the resolved value. * * @example * const object = { 'a': { 'b': { 'c': { 'd': 4 } } } }; * get(object, ['a', 'b', 'c', 'd']); * // => 4 * * @group Object */ declare function get, TKey3 extends keyof NonNullable[TKey2]>, TKey4 extends keyof NonNullable[TKey2]>[TKey3]>>(object: TObject | null | undefined, path: [TKey1, TKey2, TKey3, TKey4]): NonNullable[TKey2]>[TKey3]>[TKey4] | undefined; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. * * @template TObject * @template TKey1 * @template TKey2 * @template TKey3 * @template TKey4 * @template TDefault * @param object - The object to query. * @param path - The path of the property to get. * @param defaultValue - The value returned if the resolved value is undefined. * @returns Returns the resolved value. * * @example * const object = { 'a': { 'b': { 'c': { 'd': 4 } } } }; * get(object, ['a', 'b', 'c', 'd'], 'default'); * // => 4 * * @group Object */ declare function get, TKey3 extends keyof NonNullable[TKey2]>, TKey4 extends keyof NonNullable[TKey2]>[TKey3]>, TDefault>(object: TObject | null | undefined, path: [TKey1, TKey2, TKey3, TKey4], defaultValue: TDefault): Exclude[TKey2]>[TKey3]>[TKey4], undefined> | TDefault; /** * Gets the value at path of object. * * @template T * @param object - The object to query. * @param path - The path of the property to get. * @returns Returns the resolved value. * * @example * const object = { 0: 'a', 1: 'b', 2: 'c' }; * get(object, 1); * // => 'b' * * @group Object */ declare function get(object: Record, path: number): T; /** * Gets the value at path of object. If the resolved value is undefined, undefined is returned. * * @template T * @param object - The object to query. * @param path - The path of the property to get. * @returns Returns the resolved value. * * @example * const object = { 0: 'a', 1: 'b', 2: 'c' }; * get(object, 1); * // => 'b' * * @group Object */ declare function get(object: Record | null | undefined, path: number): T | undefined; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. * * @template T * @template TDefault * @param object - The object to query. * @param path - The path of the property to get. * @param defaultValue - The value returned if the resolved value is undefined. * @returns Returns the resolved value. * * @example * const object = { 0: 'a', 1: 'b', 2: 'c' }; * get(object, 1, 'default'); * // => 'b' * * @group Object */ declare function get(object: Record | null | undefined, path: number, defaultValue: TDefault): T | TDefault; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place. * * @template TDefault * @param object - The object to query. * @param path - The path of the property to get. * @param defaultValue - The value returned if the resolved value is undefined. * @returns Returns the default value. * * @example * get(null, 'a.b.c', 'default'); * // => 'default' * * @group Object */ declare function get(object: null | undefined, path: Arrayable$1, defaultValue: TDefault): TDefault; /** * Gets the value at path of object. If the resolved value is undefined, undefined is returned. * * @param object - The object to query. * @param path - The path of the property to get. * @returns Returns undefined. * * @example * get(null, 'a.b.c'); * // => undefined * * @group Object */ declare function get(object: null | undefined, path: Arrayable$1): undefined; /** * Gets the value at path of object using type-safe path. * * @template TObject * @template TPath * @param data - The object to query. * @param path - The path of the property to get. * @returns Returns the resolved value. * * @example * const object = { a: { b: { c: 1 } } }; * get(object, 'a.b.c'); * // => 1 * * @group Object */ declare function get(data: TObject, path: TPath): string extends TPath ? any : GetFieldType; /** * Gets the value at path of object using type-safe path. If the resolved value is undefined, the defaultValue is returned. * * @template TObject * @template TPath * @template TDefault * @param data - The object to query. * @param path - The path of the property to get. * @param defaultValue - The value returned if the resolved value is undefined. * @returns Returns the resolved value. * * @example * const object = { a: { b: { c: 1 } } }; * get(object, 'a.b.d', 'default'); * // => 'default' * * @group Object */ declare function get>(data: TObject, path: TPath, defaultValue: TDefault): Exclude, null | undefined> | TDefault; /** * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned. * * @param object - The object to query. * @param path - The path of the property to get. * @param [defaultValue] - The value returned if the resolved value is undefined. * @returns Returns the resolved value. * * @example * const object = { a: { b: { c: 1 } } }; * get(object, 'a.b.c', 'default'); * // => 1 * * @group Object */ declare function get(object: any, path: Arrayable$1, defaultValue?: any): any; declare var nullTag: string; declare var undefinedTag: string; declare var regexpTag: string; declare var stringTag: string; declare var numberTag: string; declare var booleanTag: string; declare var argumentsTag: string; declare var symbolTag: string; declare var dateTag: string; declare var bigintTag: string; declare var mapTag: string; declare var setTag: string; declare var arrayTag: string; declare var functionTag: string; declare var arrayBufferTag: string; declare var objectTag: string; declare var weakmapTag: string; declare var weaksetTag: string; declare var errorTag: string; declare var dataViewTag: string; declare var uint8ArrayTag: string; declare var uint8ClampedArrayTag: string; declare var uint16ArrayTag: string; declare var uint32ArrayTag: string; declare var bigUint64ArrayTag: string; declare var int8ArrayTag: string; declare var int16ArrayTag: string; declare var int32ArrayTag: string; declare var bigInt64ArrayTag: string; declare var float32ArrayTag: string; declare var float64ArrayTag: string; /** * Get object tag of value * @group Object */ declare const getTag: (value: T) => string; /** * Returns true when provided keys exists in target object * * @example * const user = { id: 1, name: 'Andrew' }; * * has(user, ['roles']); // false * has(user, ['roles', 'name']); // false * has(user, ['name']); // true * * @group Object */ declare function has(value: any, keys: T[]): value is { [K in T]: any }; /** * Check if object has own property * * @group Object */ declare const hasOwn: (val: T, key: K) => key is K; /** * Creates a new object with specified keys omitted. * * This function takes an object and an array of keys, and returns a new object that * excludes the properties corresponding to the specified keys. * * @template T - The type of object. * @template K - The type of keys in object. * @param {T} obj - The object to omit keys from. * @param {K[]} keys - An array of keys to be omitted from the object. * @returns {Omit} A new object with the specified keys omitted. * * @example * const obj = { a: 1, b: 2, c: 3 }; * const result = omit(obj, ['b', 'c']); * // result will be { a: 1 } * * @group Object */ declare function omit, U extends keyof T>(obj: T, excludes: Readonly | Set | Array | Set>): Omit; /** * Pick object keys with excluding prefix keys * * @example * const record = { * id: 1, * canRead: true, * canWrite: true, * }; * * omitPrefixed(record, 'can'); // { id: 1 } * * @group Object */ declare function omitPrefixed(obj: Record, prefix: string): Record; /** * Creates a new object composed of the picked object properties. * * This function takes an object and an array of keys, and returns a new object that * includes only the properties corresponding to the specified keys. * * @template T - The type of object. * @template K - The type of keys in object. * @param {T} obj - The object to pick keys from. * @param {K[]} keys - An array of keys to be picked from the object. * @returns {Pick} A new object with the specified keys picked. * * @example * const obj = { a: 1, b: 2, c: 3 }; * const result = pick(obj, ['a', 'c']); * // result will be { a: 1, c: 3 } * * @group Object */ declare function pick, U extends keyof T>(obj: T | null | undefined, keys: Readonly | Set | Array | Set>): Pick; interface PrefixedValuesOptions { /** * Key prefix */ prefix: string; /** * Remove prefix from resulted object * @default false */ prefixTrim?: boolean; } /** * Pick prefixed keys in target object * * @example * const record = { * id: 1, * canRead: true, * canWrite: true, * }; * * // { canRead: true, canWrite: true } * pickPrefixed(record, 'can'); * * // { Read: true, Write: true } * pickPrefixed(record, { prefix: 'can', prefixTrim: true }); * * @group Object */ declare function pickPrefixed(obj: object, options: PrefixedValuesOptions | string): {}; /** * Sets the value at the specified path of the given object. If any part of the path does not exist, it will be created. * * @template T - The type of the object. * @param object - The object to modify. * @param path - The path of the property to set. * @param value - The value to set. * @returns The modified object. * * @example * // Set a value in a nested object * const obj = { a: { b: { c: 3 } } }; * set(obj, 'a.b.c', 4); * console.log(obj.a.b.c); // 4 * * @example * // Set a value in an array * const arr = [1, 2, 3]; * set(arr, 1, 4); * console.log(arr[1]); // 4 * * @example * // Create non-existent path and set value * const obj = {}; * set(obj, 'a.b.c', 4); * console.log(obj); // { a: { b: { c: 4 } } } * * @group Object */ declare function set(object: T, path: Arrayable$1, value: any): T; /** * Sets the value at the specified path of the given object. If any part of the path does not exist, it will be created. * * @template R - The return type. * @param object - The object to modify. * @param path - The path of the property to set. * @param value - The value to set. * @returns The modified object. * * @example * // Set a value in a nested object * const obj = { a: { b: { c: 3 } } }; * set(obj, 'a.b.c', 4); * console.log(obj.a.b.c); // 4 * * @example * // Set a value in an array * const arr = [1, 2, 3]; * set(arr, 1, 4); * console.log(arr[1]); // 4 * * @example * // Create non-existent path and set value * const obj = {}; * set(obj, 'a.b.c', 4); * console.log(obj); // { a: { b: { c: 4 } } } * * @group Object */ declare function set(object: object, path: Arrayable$1, value: any): R; /** * Converts object into Map * * @example * const map = toMap({ user1: 'Andrew', user2: 'John' }); * * map.get('user2'); // John * * @group Object */ declare const toMap: (obj: T) => Map; /** * Converts a flattened object back into a nested structure. * * Takes an object with dot-separated keys and converts it into a nested object, * where each dot-separated part of the key represents a deeper level in the object. * * @param {Object} obj - The object to unflatten. * @param {string} [separator='_'] - The separator used to split the keys into their nested form. Defaults to '_'. * @returns {Object} The unflattened object, with nested keys restored to their original structure. * * @example * const obj = { * 'name': 'Andrew', * 'config_canReadPost': true, * 'config_canUpdatePost': true, * }; * * unflatten(obj); * // Returns: * // { * // name: 'Andrew', * // config: { * // canReadPost: true, * // canUpdatePost: true * // }, * // } * * @example * const flattenedObj = { * 'user.firstName': 'John', * 'user.lastName': 'Doe', * 'address.city': 'New York' * }; * * unflatten(flattenedObj, '.'); * // Returns: * // { * // user: { * // firstName: 'John', * // lastName: 'Doe' * // }, * // address: { * // city: 'New York' * // } * // } * * @group Object * @author lukeed */ declare function unflatten(input: object, separator?: string): any; /** * Removes the property at the given path of the object. * * @param obj - The object to modify. * @param path - The path of the property to unset. * @returns Returns true if the property is deleted, else false. * * @example * const obj = { a: { b: { c: 42 } } }; * unset(obj, 'a.b.c'); // true * console.log(obj); // { a: { b: {} } } * * @example * const obj = { a: { b: { c: 42 } } }; * unset(obj, ['a', 'b', 'c']); // true * console.log(obj); // { a: { b: {} } } * * @group Object */ declare function unset(obj: any, path: Arrayable): boolean; /** * Updates the value at the specified path of the given object using an updater function and a customizer. * If any part of the path does not exist, it will be created. * * @template T - The type of the object. * @param object - The object to modify. * @param path - The path of the property to update. * @param updater - The function to produce the updated value. * @param customizer - The function to customize the update process. * @returns The modified object. * * @example * const object = { 'a': [{ 'b': { 'c': 3 } }] }; * updateWith(object, 'a[0].b.c', (n) => n * n); * // => { 'a': [{ 'b': { 'c': 9 } }] } * * @group Object */ declare function updateWith(object: T, path: Arrayable, updater: (oldValue: any) => any, customizer?: (value: any, key: string, object: T) => any): T; /** * Updates the value at the specified path of the given object using an updater function and a customizer. * If any part of the path does not exist, it will be created. * * @template T - The type of the object. * @template R - The type of the return value. * @param object - The object to modify. * @param path - The path of the property to update. * @param updater - The function to produce the updated value. * @param customizer - The function to customize the update process. * @returns The modified object. * * @example * const object = { 'a': [{ 'b': { 'c': 3 } }] }; * updateWith(object, 'a[0].b.c', (n) => n * n); * // => { 'a': [{ 'b': { 'c': 9 } }] } * * @group Object */ declare function updateWith(object: T, path: Arrayable, updater: (oldValue: any) => any, customizer?: (value: any, key: string, object: T) => any): R; /** * Asynchronously filters an array using an async predicate function. * * This function processes an array using an async function as the predicate, * allowing you to avoid blocking the event loop while iterating over large arrays. * It ensures that the iteration happens asynchronously with minimal impact on the event loop, * making it useful for processing large datasets or performing async operations on each element. * * @param array - The array to be filtered. * @param predicate - The async predicate function. * It takes three arguments: the current value, the index of the current value, and the full array. * It should return a boolean value or a promise that resolves to a boolean indicating whether the value should be kept in the result array. * * @returns {Promise} A promise that resolves to a new array containing the elements that satisfy the predicate. * * @example * const users = Array.from({ length: 100000 }).map((_, idx) => ({ * id: idx, * name: 'User: ' + (idx + 1) * })); * * async function first100Users() { * return await asyncFilter(users, (user) => user.id < 100); * } * * Promise.all([ * first100Users(), * otherUsefulTask(), * ]).then(console.log); * * @group Promise */ declare function asyncFilter(array: T[], predicate: (value: T, index: number, array: Array) => Promise | boolean, { concurrency }?: { concurrency?: number | undefined; }): Promise; /** * Asynchronously filters and maps an array in a single pass, with bounded * concurrency. * * The callback may be async and receives a `skip` sentinel as its second * argument. Return any mapped value (or a promise of one) to keep it, or return * `skip` to exclude the current element. Combining the filter and map avoids the * extra allocation and second traversal of chaining `.filter().map()`. * * Up to `concurrency` callbacks run at a time. Even though callbacks may settle * out of order, the resolved array preserves **strict source order** and * contains no gaps for skipped elements. Work is spread across microtasks so a * large input does not block the event loop. * * If any callback rejects (or throws), the returned promise rejects with that * error and no further elements are processed. * * @param array - The source array to iterate over. It is not mutated. * @param callbackfn - Called for each element with `(value, skip, index, array)`. * Return the mapped value (or a promise of it) to keep, or `skip` to drop the * element. * @param options - Options object. * @param options.concurrency - Maximum number of callbacks in flight at once. * Defaults to `1` (sequential); values below `1` are clamped to `1`. * @returns A promise resolving to a new array of the mapped values, in source * order, excluding any skipped elements. * * @example * ```ts * // Keep even numbers and double them, dropping the rest. * await asyncFilterMap([1, 2, 3, 4], (value, skip) => * value % 2 === 0 ? value * 2 : skip, * ); * // => [4, 8] * ``` * * @example * ```ts * // Fetch users concurrently, skipping the ones that don't exist. * const users = await asyncFilterMap( * ids, * async (id, skip) => { * const res = await fetch(`/users/${id}`); * return res.ok ? res.json() : skip; * }, * { concurrency: 5 }, * ); * ``` * * @group Promise */ declare function asyncFilterMap(array: T[], callbackfn: (value: T, skip: SpecialValue, index: number, array: T[]) => Awaitable, { concurrency }?: { concurrency?: number | undefined; }): Promise; /** * Asynchronously finds the first element in an array that satisfies the provided async predicate. * * This function iterates through an array and applies an asynchronous predicate to each element. * If the predicate resolves to a truthy value for any element, that element is returned immediately. * The function is designed to prevent blocking the event loop during iteration, making it suitable * for processing large arrays without impacting performance. * * @param array - The array to search through. * @param callbackfn - The asynchronous predicate function. * It takes three arguments: the current value, the index of the current value, and the full array. * The predicate function should return a boolean or a promise that resolves to a boolean indicating * whether the current value satisfies the condition. * * @returns {Promise} A promise that resolves to the first element that satisfies the predicate, or `undefined` if no element matches. * * @example * // Example of using asyncFind to find users by ID asynchronously * const users = Array.from({ length: 100000 }).map((_, idx) => ({ * id: idx, * name: 'User: ' + (idx + 1) * })); * * async function findById(userId: number) { * return await asyncFind(users, (user) => user.id === userId); * } * * Promise.all([ * findById(5000), * findById(6000), * ]).then(console.log); * * @group Promise */ declare function asyncFind(array: T[], callbackfn: (value: T, index: number, array: T[]) => Promise | unknown): Promise; /** * Asynchronously iterates over an array, executing the provided callback for each element with support for parallel processing. * * This function is similar to `Array.prototype.forEach()`, but it allows asynchronous operations in parallel for each array element. * It also prevents blocking the event loop while iterating through large arrays, improving performance for heavy tasks. * The function processes items in batches to manage concurrency and can be configured to process multiple items at the same time. * * **Note**: The callback function can return either a promise or a value. If it returns a promise, `asyncForEach` will wait for it to resolve before moving to the next iteration. * * @param array - The array to iterate over. * @param callbackfn - The async callback function to execute for each element. * This function takes three parameters: * - `value`: The current element of the array. * - `index`: The index of the current element in the array. * - `array`: The array that is being iterated over. * The function should either return a `void` or a `Promise` that resolves when the async operation is done. * * @param {Object} [options] - Optional settings to control the concurrency of the operation. * @param {number} [options.concurrency=1] - The number of items to process in parallel. Defaults to 1 (sequential processing). * * @returns {Promise} A promise that resolves when all elements have been processed. * * @example * async function task(taskName: string) { * const largeArray = Array.from({ length: 100000 }).map((_, idx) => idx); * * await asyncForEach(largeArray, (value) => { * if (value % 100 === 0) { * console.log(taskName, 'handle:', value); * } * }); * } * * Promise.all([ * task('task 1'), * task('task 2'), * ]); * * @group Promise */ declare function asyncForEach(array: T[], callbackfn: (value: T, index: number, array: Array) => Promise | void, { concurrency }?: { concurrency?: number | undefined; }): Promise; /** * An asynchronous queue implementation that can be iterated using an async iterator. * It allows items to be added (`put`) and consumed asynchronously, with the ability to signal when the queue is closed. * This class supports async iteration, enabling users to process items as they become available, and provides an end signal once the queue is closed. * * @example * const textStream = new AsyncIterableQueue(); * * const readTimer = setInterval(() => { * textStream.put('Hey ' + Math.random()); * }, 100); * * setTimeout(() => { * textStream.close(); * clearInterval(readTimer); * }); * * for await (const text of textStream) { * console.log('text part', { text }); * } * * @group Promise */ declare class AsyncIterableQueue implements AsyncIterable { private _queue; private _closed; private static readonly QUEUE_END_MARKER; constructor(); get closed(): boolean; put(item: T): void; close(): void; [Symbol.asyncIterator](): AsyncIterator; } /** * Asynchronously maps over an array, applying the provided callback function to each element, * with support for parallel processing of array elements. * * This function is similar to `arr.map()`, but allows asynchronous operations * for each array element, helping to avoid blocking the event loop when processing large arrays. * It processes the array elements in batches, providing support for concurrency, meaning multiple * elements can be processed in parallel. * * **Note**: The callback function can return either a value or a `Promise`. If a `Promise` is returned, * `asyncMap` will wait for it to resolve before moving on to the next iteration. * * @param array - The array to iterate over. * @param callbackfn - The async callback function to apply to each element. * This function takes three parameters: * - `value`: The current element of the array. * - `index`: The index of the current element in the array. * - `array`: The array being processed. * The callback should return either a transformed value (`U`) or a `Promise`. * * @param {Object} [options] - Optional configuration for controlling concurrency. * @param {number} [options.concurrency=1] - The number of items to process concurrently. Default is 1 (sequential processing). * * @returns {Promise} A promise that resolves to an array of transformed elements. * * @example * const users = Array.from({ length: 100 }).map((_, idx) => ({ * id: idx, * name: 'User: ' + (idx + 1) * })); * * async function withUserClients() { * return await asyncMap(users, async (user) => { * const clients = await db.clients.find({ user: user.id }); * * return { ...user, clients }; * }, { concurrency: 10 }); * } * * Promise.all([ * withUserClients(), * otherUsefulTask(), * ]).then(console.log); * * @group Promise */ declare function asyncMap(array: T[], callbackfn: (value: T, index: number, array: Array) => Promise | U, { concurrency }?: { concurrency?: number | undefined; }): Promise>; /** * A custom promise that supports cancellation. * Allows users to cancel the promise operation before it completes, avoiding unnecessary execution. * This class provides a mechanism to perform asynchronous tasks that can be stopped midway by calling the `cancel` method. * * @example * const task = new CancellablePromise(async (resolve, reject, onCancel) => { * let cancelled = false; * onCancel(() => { * cancelled = true; // Define the cancellation logic here * }); * * while (!cancelled) { * await delay(1000); // Simulate async work * console.log('handling task...'); * } * }); * * // Cancel the task after 5 seconds * setTimeout(() => task.cancel(), 5000); * * await task; // This will be cancelled before it completes * console.log('Task completed or cancelled'); * * @group Promise */ declare class CancellablePromise implements Promise { #private; constructor(executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void, onCancel: (cancelFn: () => void) => void) => void); get [Symbol.toStringTag](): string; get isCancelled(): boolean; get error(): Error | null; then(onfulfilled?: ((value: T) => TResult1 | Promise) | null, onrejected?: ((reason: any) => TResult2 | Promise) | null): Promise; catch(onrejected?: ((reason: any) => TResult | Promise) | null): Promise; finally(onfinally?: (() => void) | null): Promise; cancel(): void; static from(promise: Promise): CancellablePromise; } interface Defer { promise: Promise; resolve: (value: T) => void; reject: (value: any) => void; } /** * Old known defer :) * * @example * function loadModule() { * const q = defer(); * * setTimeout(() => q.resolve(), 5000); * * return q.promise; * } * * await loadModule(); * * @group Promise */ declare function defer(): Defer; /** * Returns a promise that resolves after the provided delay. * * If the delay is specified as `'tick'`, the promise resolves after the next event loop tick. * * If a numeric delay is provided, the promise resolves after the specified time in milliseconds. * * This is useful for introducing delays in asynchronous code, such as for throttling or rate-limiting, * or simply pausing execution between iterations. * * @param amount - The delay duration in milliseconds, or `'tick'` for a resolution after the next event loop tick. * @returns A promise that resolves after the specified delay. * * @example * let seconds = 0; * * // This will print numbers 1, 2, 3... every second * while (true) { * await delay(1000); * console.log(++seconds); * } * * @example * // This will wait until the next event loop tick before resolving * await delay('tick'); * * @group Promise */ declare function delay(amount?: 'tick' | number): Promise; /** * Executes the provided callback as soon as the event loop is idle. * This function allows you to run tasks at the earliest available opportunity * without blocking the main execution flow, making it ideal for tasks that can * be deferred until the browser is idle or the process is idle. * * It uses `requestIdleCallback` if available, otherwise it falls back to * `requestAnimationFrame`, `process.nextTick`, or `setTimeout` depending on the environment. * * @example * fastIdle(() => { * console.log('1'); * }); * * console.log('2'); * * // Output: * // 2 * // 1 * * @param callback - The callback function to be executed when the event loop is idle. * * @group Promise */ declare function fastIdle(callback: Fn$1): void; /** * Same as `fastIdle` but promisified * * @example * fastIdlePromise().then(() => { * console.log('1'); * }); * * console.log('2'); * * // 2 * // 1 * * @group Promise */ declare function fastIdlePromise(): Promise; type NoneToVoidFunction = () => void; /** * Stacks callbacks for `requestAnimationFrame` into a single execution call. * * This function allows multiple `fastRaf` calls to be batched into a single animation frame callback. * The callbacks are executed in the same frame, one after the other. Additionally, if `withTimeoutFallback` is true, * the callbacks will be executed after a fallback timeout if `requestAnimationFrame` is not available. * If called from within another RAF callback, the execution might be immediate. * * @example * // Callbacks will be executed in the same `requestAnimationFrame` cycle * fastRaf(() => console.log(1)); * fastRaf(() => console.log(2)); * * // Output: * // 1 * // 2 * * @param callback The callback function to be executed in the next `requestAnimationFrame`. * @param [withTimeoutFallback=false] Optional flag to execute callbacks after a fallback timeout if `requestAnimationFrame` is not available. * @group Promise */ declare function fastRaf(callback: NoneToVoidFunction, withTimeoutFallback?: boolean): void; declare function rafPromise(): Promise; /** * Creates a cooldown function that resolves after a specified number of executions (`amount`). * The cooldown can either occur on the `next` tick or after a specified delay. * * This is useful for controlling the rate of asynchronous operations, allowing you to pause * for a specified amount of time after a certain number of iterations in a loop. * * @example * // Create a cooldown function that waits 1 tick for every 10th execution * const cooldown = nextTickIteration(10); * * for (const item of array) { * await cooldown(); // Wait 1 tick for every 10th call * // Perform some async operation here * } * * @example * // Create a cooldown function with a 100ms delay after every 5 executions * const cooldownWithDelay = nextTickIteration(5, 100); * for (const item of array) { * await cooldownWithDelay(); // Wait 100ms after every 5th call * // Perform some async operation here * } * * @param amount The number of executions after which the cooldown should occur. * @param delay The delay type or amount. If 'tick', it uses the next idle tick. * If a number is provided, it specifies a delay in milliseconds. * @returns A function that, when called, returns a promise resolving after the specified cooldown period. * * @group Promise */ declare function nextTickIteration(amount: number, delay?: number | 'tick'): () => Promise; /** * A basic queue implementation with a limit and event-based synchronization. * * This class allows you to put items into a queue and retrieve them asynchronously. * If the queue exceeds a specified limit, the `put` operation will wait until an item is retrieved, * and similarly, the `get` operation will wait if there are no items available in the queue. * * @example * // Create a queue with a limit of 10 items * const sendQueue = new Queue(10); * * // Add items to the queue * sendQueue.put({ url: '/api/message.send', params: { text: 'hello' } }); * sendQueue.put({ url: '/api/message.send', params: { text: 'how are you?' } }); * * // Retrieve and process items from the queue asynchronously * while (true) { * const req = await sendQueue.get(); * http.post(req.url, { body: req.params }); * } * * @param limit - Optional maximum number of items the queue can hold. If not provided, the queue has no limit. * * @group Promise */ declare class Queue { #private; items: T[]; constructor(limit?: number); get(): Promise; put(item: T): Promise; } type SimpleEventMap = Record | SimpleDefaultEventMap; type SimpleDefaultEventMap = [never]; type Key = T extends SimpleDefaultEventMap ? string | symbol : K | keyof T; type Listener = T extends SimpleDefaultEventMap ? F : K extends keyof T ? T[K] extends unknown[] ? (...args: T[K]) => void : never : never; type Listener1 = Listener void>; type Args = T extends SimpleDefaultEventMap ? [...args: any[]] : K extends keyof T ? T[K] : never; /** * Simplified version on nodejs `EventEmitter` but platform agnostic * * @example * const emitter = new SimpleEventEmitter(); * * emitter.on('message', (data) => { * console.log('msg', data) * }); * * emitter.once('message', (data) => { * console.log('once msg', data) * }); * * emitter.emit('message', { text: 'Hello' }); * emitter.emit('message', { text: 'Hello 2' }); * * @group Promise */ declare class SimpleEventEmitter = SimpleDefaultEventMap> { #private; constructor(); static once(emitter: SimpleEventEmitter, eventName: string | symbol): Promise; emit(eventName: Key, ...args: Args): boolean; on(eventName: Key, listener: Listener1): this; once(eventName: Key, listener: Listener1): this; off(eventName: Key, listener: Listener1): this; removeAllListeners(eventName?: Key): this; } /** * Configuration options for creating a ResourcePool instance. * @template T The type of resource being pooled */ interface ResourcePoolOptions { /** Maximum number of resources that can exist in the pool */ poolSize: number; /** * Whether to automatically create resources when needed, up to poolSize limit. * If false, resources must be pre-created or acquired requests will queue. * @default false */ auto?: boolean; /** Factory function to create new resources */ createResource: () => Awaitable; /** Optional cleanup function called when destroying resources */ destroyResource?: (resource: T) => Awaitable; } type ResourcePoolEventMap = { error: [error: Error]; }; /** * A generic resource pool that manages the lifecycle of expensive resources. * * ResourcePool provides a way to: * - Limit the number of concurrent resources (e.g., database connections, file handles) * - Reuse resources to avoid creation/destruction overhead * - Queue requests when all resources are in use * - Automatically create resources on demand (when auto mode is enabled) * - Gracefully handle resource cleanup and pool destruction * * @template T The type of resource being pooled * * @example * ```typescript * // Database connection pool * const dbPool = new ResourcePool({ * poolSize: 10, * auto: true, * createResource: () => createDatabaseConnection(), * destroyResource: (conn) => conn.close() * }); * * // Acquire and use a connection * const conn = await dbPool.acquire(); * try { * const result = await conn.query('SELECT * FROM users'); * return result; * } finally { * dbPool.release(conn); * } * ``` * * @group Promise */ declare class ResourcePool extends SimpleEventEmitter { private readonly poolSize; private readonly auto; private readonly createResource; private readonly destroyResource?; private readonly state; /** * Creates a new ResourcePool instance. * * @param options Configuration options for the pool * * @example * ```typescript * const pool = new ResourcePool({ * poolSize: 5, * auto: true, * createResource: async () => new DatabaseConnection(), * destroyResource: async (conn) => conn.close() * }); * ``` */ constructor({ poolSize, auto, createResource, destroyResource }: ResourcePoolOptions); /** * Whether the pool is idle (no resources currently in use). * Useful for determining if it's safe to destroy the pool. */ get isIdle(): boolean; /** Number of resources currently available for acquisition */ get availableCount(): number; /** Number of resources currently in use */ get usedCount(): number; /** Maximum number of resources this pool can manage */ get size(): number; /** * Acquires a resource from the pool. * * This method will: * 1. Return an available resource immediately if one exists * 2. Create a new resource if auto mode is enabled and under the pool limit * 3. Queue the request and wait if no resources are available * * @returns Promise that resolves to an acquired resource * @throws Error if the pool is destroyed while waiting (when rejectAcquires is true) * * @example * ```typescript * const resource = await pool.acquire(); * try { * // Use the resource * await resource.doSomething(); * } finally { * pool.release(resource); // Always release in finally block * } * ``` */ acquire(): Promise; /** * Returns a resource to the pool, making it available for reuse. * * The resource will be made available to the next queued acquisition request, * or returned to the available pool if no requests are pending. * * @param resource The resource to return to the pool * * @example * ```typescript * const resource = await pool.acquire(); * try { * // Use resource... * } finally { * pool.release(resource); // Always release when done * } * ``` * * @remarks * - Safe to call multiple times with the same resource (idempotent) * - Only resources that were acquired from this pool should be released * - Triggers drain completion if this was the last resource in use */ release(resource: T): void; /** * Manually add a resource to the pool. * * @param resource The resource to return to the pool * * @throws Error if resource already exists in the pool. * @throws Error if size reached. */ add(resource: T): void; /** * Waits for all currently acquired resources to be released. * * This is useful for graceful shutdown scenarios where you want to ensure * all work is completed before destroying the pool. * * @returns Promise that resolves when all resources are returned to the pool * * @example * ```typescript * // Graceful shutdown * console.log('Waiting for all connections to be released...'); * await pool.drain(); * console.log('All connections released, safe to destroy pool'); * await pool.destroy(); * ``` * * @remarks * - Resolves immediately if no resources are currently in use * - Multiple drain calls can be made concurrently; they will all resolve together * - Does not prevent new acquisitions; use destroy() to prevent new usage */ drain(): Promise; /** * Destroys the pool and all its resources. * * This method will: * 1. Wait for all resources to be released (drain) * 2. Optionally reject any pending acquisition requests * 3. Call destroyResource() on all available resources * 4. Clean up internal state * * @param rejectAcquires Whether to reject pending acquire() requests with an error * If false, pending requests will remain queued indefinitely * @returns Promise that resolves when destruction is complete * * @example * ```typescript * // Graceful shutdown - let pending requests complete * await pool.destroy(false); * * // Immediate shutdown - reject pending requests * await pool.destroy(true); * ``` * * @remarks * - Safe to call multiple times; subsequent calls will wait for the first to complete * - The pool cannot be used after destruction * - Resources currently in use will not be force-destroyed; drain() is called first * - If destroyResource was not provided, resources are simply discarded */ destroy(rejectAcquires?: boolean): Promise; private tryGetAvailableResource; private isLimitReached; private tryCreateAutoResource; private enqueueAcquireRequest; private moveResourceToAvailable; private processNextAcquireRequest; private checkForDrainCompletion; private enqueueDestroyRequest; private rejectPendingAcquires; private destroyAllResources; private resetState; private resolveDestroyQueue; } declare const SCHEDULER_JOB_FLAGS: { readonly QUEUED: number; readonly ALLOW_RECURSE: number; readonly DISPOSED: number; }; declare namespace Scheduler { type Job = (() => T) & JobOptions; type JobOptions = { id?: number; /** * flags can technically be undefined, but it can still be used in bitwise * operations just like 0. */ flags?: number; jobName?: string; }; } /** * Creates a microtask scheduler that batches jobs and flushes them in * priority order on the next tick. * * Jobs are functions queued via {@link Scheduler.queueJob}. Each job may carry * an optional numeric `id` used to order the queue — lower `id` runs first, * and jobs without an `id` run last. Re-queueing the same job within an * active flush cycle is a no-op unless `SCHEDULER_JOB_FLAGS.ALLOW_RECURSE` * is set on the job. Use {@link Scheduler.queueJobWait} when you need to * await a job's result through a {@link CancellablePromise}, and the * `onJob` / `onJobStart` / `onJobComplete` hooks to observe lifecycle. * * @example * ```typescript * const scheduler = createScheduler(); * * const log = (msg: string) => () => console.log(msg); * * const first = log('first'); * first.id = 1; * const second = log('second'); * second.id = 2; * * scheduler.queueJob(second); * scheduler.queueJob(first); * * scheduler.nextTick().then(() => console.log('flushed')); * // → first * // → second * // → flushed * ``` * * @group Promise */ declare function createScheduler(): Scheduler; declare class Scheduler { protected queue: Scheduler.Job[]; protected flushIndex: number; protected resolvedPromise: Promise; protected currentFlushPromise: Promise | null; protected onJobCbs: ((job: Scheduler.JobOptions) => void)[]; protected onJobStartCbs: ((job: Scheduler.JobOptions) => void)[]; protected onJobCompleteCbs: ((job: Scheduler.JobOptions) => void)[]; constructor(); onJob(fn: (job: Scheduler.JobOptions) => void): void; onJobStart(fn: (job: Scheduler.JobOptions) => void): void; onJobComplete(fn: (job: Scheduler.JobOptions) => void): void; nextTick(fn?: () => void): Promise; queueJob(job: Scheduler.Job, opts?: Scheduler.JobOptions): void; queueJobWait(job: Scheduler.Job, opts?: Scheduler.JobOptions): CancellablePromise>; protected findInsertionIndex(id: number): number; protected flushJobs(): Promise; protected queueFlush(): void; } /** * Throws an error if the provided promise or callback is not resolved within the specified timeout period. * * This function can be used to ensure that an asynchronous operation does not take too long to complete. * If the operation exceeds the specified time limit, the provided `timeoutError` is thrown. * * @example * // Example usage: Throw an error if no response is received within 1 second * await timeout( * 1000, // Timeout duration in milliseconds * (signal) => { * const account = await http.get('/api/users/me'); * * if (signal.aborted) return; // If the timeout occurs, abort the operation * * const statistics = await http.get('/api/users/me/statistics'); * * return { ...account, statistics }; * }, * new Error('Request account timeout') // Custom error to throw on timeout * ); * * @param ms - The maximum time (in milliseconds) to wait for the promise or callback to resolve. * @param promiseOrCallback - The asynchronous operation to execute. This can either be: * - A `Promise` that will be awaited until completion, or * - A function that takes an `AbortSignal` and returns a `Promise` or a value. * @param timeoutError - The error that will be thrown if the timeout is reached before the promise or callback resolves. * (Defaults to `AppError(408)` if not provided). * @returns A `Promise` that resolves with the result of the provided `promiseOrCallback`, or rejects with the `timeoutError` if the timeout occurs. * * @throws {Error} - Throws the `timeoutError` if the operation exceeds the specified timeout. * * @group Promise */ declare function timeout(ms: number, promiseOrCallback: Promise | ((abortSignal: AbortSignal) => Awaitable), timeoutError?: any): Promise; type ToPromiseResult = T extends (() => Awaitable) ? X : T extends Promise ? X : T; /** * Wraps a value or a thunk in a `Promise`, always resolving on the next microtask. * * - If `value` is a function, it is called and its return value (sync or async) is awaited. * Synchronous throws are converted to rejections. * - Otherwise, `value` is resolved as-is. * * @param value - A plain value or a zero-argument function returning `Awaitable`. * @returns A `Promise` that resolves to the value or the function's result. * * @example * // Plain value * await toPromise(42); // → 42 * * @example * // Sync function * await toPromise(() => computeResult()); // → result * * @example * // Async function * await toPromise(() => fetch('/api/data').then(r => r.json())); * * @group Promise */ declare function toPromise(value: T): Promise>; type ResolverFn, T = any, A extends any[] = any[]> = (this: T, ...args: A) => R; type WithResolve, T = any, A extends any[] = any[]> = (this: T, ...args: A) => R; /** * A function that generates cache key based on the arguments. * * @param args - The original function arguments * @param computeKey - A helper function to stringify arguments into a cache key * @returns A cache key string if a variant should be used, or undefined to skip this variant */ type GetCacheKey = (args: any[], computeKey: (...args: any[]) => string) => string | null | undefined; /** * Wraps an async function to guarantee single execution for identical arguments. * Acts as a request deduplication mechanism - when multiple calls are made with the same * arguments before the first call completes, all calls wait for and receive the result * of the first execution. * * This is useful for preventing redundant async operations like duplicate API calls or * database queries that are triggered simultaneously. * * @template R - The Promise return type of the wrapped function * @template T - The `this` context type for the function * @template A - The argument types tuple for the function * * @param fn - The async function to wrap * @param getCacheKey - Optional array of functions to generate alternative cache keys. * Useful when different argument combinations should be treated as equivalent. * * @returns A wrapped version of the function with deduplication behavior * * @example Basic usage - deduplicating database queries * ```ts * const fetchUserById = withResolve((userId: number) => * db.users.findById(userId) * ); * * // Only produces 1 database query, both calls receive the same result * const [user1, user2] = await Promise.all([ * fetchUserById(100), * fetchUserById(100) * ]); * ``` * * @example With cache key variants * ```ts * const fetchUser = withResolve( * (id: number, options?: { fresh?: boolean }) => api.getUser(id, options), * [ * // Treat calls with/without options as equivalent if fresh is false/undefined * (args, computeKey) => { * const [id, options] = args; * if (options?.fresh) { * return null; * } * * return computeKey(id, {}); * } * ] * ); * * // Both calls deduplicated to single request * await Promise.all([ * fetchUser(1), * fetchUser(1, { fresh: false }) * ]); * ``` * * @remarks * - The cache is held only during the execution of the first call * - Once the promise resolves or rejects, the cache entry is cleared * - All waiting calls receive the same result (success or error) * - Works with both resolved and rejected promises * * @group Promise */ declare function withResolve, T = any, A extends any[] = any[]>(fn: ResolverFn, getCacheKey?: Arrayable): WithResolve; /** * Converts a string to camel case. * * Camel case is the naming convention in which the first word is written in lowercase and * each subsequent word begins with a capital letter, concatenated without any separator characters. * * @param {string} str - The string that is to be changed to camel case. * @returns {string} - The converted string to camel case. * * @example * const convertedStr1 = camelCase('camelCase') // returns 'camelCase' * const convertedStr2 = camelCase('some whitespace') // returns 'someWhitespace' * const convertedStr3 = camelCase('hyphen-text') // returns 'hyphenText' * const convertedStr4 = camelCase('HTTPRequest') // returns 'httpRequest' * const convertedStr5 = camelCase('Keep unicode 😅') // returns 'keepUnicode😅' * * @group Strings */ declare function camelCase(str: string): string; /** * Converts the first character of string to upper case and the remaining to lower case. * * @template T - Literal type of the string. * @param {T} str - The string to be converted to uppercase. * @returns {Capitalize} - The capitalized string. * * @example * const result = capitalize('fred') // returns 'Fred' * const result2 = capitalize('FRED') // returns 'Fred' * * @group Strings */ declare function capitalize(str: T): Capitalize; type Capitalize = T extends `${infer F}${infer R}` ? `${Uppercase}${Lowercase}` : T; /** * Converts a value to a string and appends a specified unit to it. * If the value is already a string, it returns it as is, and if the value is a number, * it appends the specified unit (defaults to 'px'). If the value is null, undefined, or an empty string, it returns `undefined`. * * @example * // Adding 'px' unit to a number * convertToUnit(10, 'px'); // '10px'; * * // Adding 'em' unit to a number * convertToUnit(5, 'em'); // '5em'; * * // Returning a string as is if it's not a number * convertToUnit('100%', 'px'); // '100%'; * * // Handling null, undefined, and empty string * convertToUnit(null); // undefined; * convertToUnit(''); // undefined; * * @param str - The value to convert, can be a number, string, null, or undefined. * @param unit - The unit to append to the value. Defaults to 'px'. * @returns The value with the unit appended, or `undefined` if the input is null, undefined, or an empty string. * * @group Strings */ declare function convertToUnit(str: string | number | null | undefined, unit?: string): string | undefined; /** * Sanitizes a string by escaping HTML syntax to prevent XSS (Cross-site scripting) attacks. * Converts special HTML characters like `<`, `>`, `&`, etc., into their corresponding HTML entities. * * @example * // Escaping HTML tags to prevent HTML injection * escapeHtml('Strong man.'); // '<b>Strong</b> man.' * * // Escaping other HTML special characters * escapeHtml(''); // '<script>alert("XSS")</script>' * * @param unsafe - The string to be sanitized (escaped). * @returns A sanitized string with HTML special characters replaced by their corresponding HTML entities. * * @group Strings */ declare function escapeHtml(unsafe: string): string; /** * Sanitizes a string by removing all non-numeric characters, leaving only digits. * Useful for extracting numeric values from strings, such as when you want to * extract a number from a string containing units or other non-numeric text. * * @example * // Extracts numeric values from a string with units * escapeNumeric('use 320px'); // '320' * * // Strips out non-numeric characters from a string * escapeNumeric('USD 1,000.50'); // '100050' * * // Returns undefined if no numeric characters are found * escapeNumeric('No numbers here!'); // undefined * * @param str - The input string to be sanitized. * @returns A string containing only the numeric characters, or `undefined` if no numbers are found. * * @group Strings */ declare function escapeNumeric(str: string): string | undefined; /** * Escapes special characters in a string to safely use it as a literal pattern in a regular expression. * This function ensures that any characters that would otherwise have a special meaning in a regex * (such as `*`, `+`, `?`, etc.) are properly escaped, allowing them to be used as normal characters * in the pattern. * * @example * // Escapes special characters in the string '[a|b]' * escapeRegExp('[a|b]'); // '\\[a\\|b\\]' * * @example * // Use the function to safely create a regex from user input * const searchTerms = 'Andrew L.'; * const searchReg = new RegExp(escapeRegExp(searchTerms), 'i'); * const searchResult = users.find(v => searchReg.test(v.name)); * * @param str - The string to escape for use in a regular expression. * @returns The input string with all special regex characters escaped. * * @group Strings */ declare function escapeRegExp(str: string): string; /** * Extracts the initials from a full name while ignoring titles or prefixes (e.g., Dr., Mr., Mrs.), * as well as any words starting with special characters (e.g., !, @, #). * Handles names with multiple words, ignores special characters, and ensures proper handling of Unicode characters. * * @param {string} fullName - The full name from which to extract initials. * @returns {string} - The extracted initials in uppercase, or an empty string if the input is invalid. * * @example * getInitials("John Doe"); * // Returns: "JD" * * @example * getInitials("Dr. Alice Wonderland"); * // Returns: "AW" * * @example * getInitials("José María de la Cruz"); * // Returns: "JC" * * @example * getInitials("Mr. Albert Einstein"); * // Returns: "AE" * * @example * getInitials("Invalid Name"); * // Returns: "IN" * * @example * getInitials(""); * // Returns: "" * * @group Strings */ declare function getInitials(fullName: string): string; declare function getWords(str?: string): string[]; /** * Checks if the provided URL string has a protocol prefix, such as `http://` or `https://`. * The function checks whether the URL starts with any of the specified protocols (defaults to HTTP and HTTPS). * * This can be useful for validating URLs or ensuring a URL has a valid protocol before using it in network requests. * * @example * hasProtocol('https://google.com'); // true * hasProtocol('http://google.com'); // true * hasProtocol('google.com'); // false * * @param url - The URL string to check. * @param protocols - An array of protocol prefixes to check against (defaults to `['http://', 'https://']`). * @returns `true` if the URL starts with one of the provided protocols, `false` otherwise. * * @group Strings */ declare function hasProtocol(url: string, protocols?: string[]): boolean; /** * Encodes a `Uint8Array` or a number array into a hexadecimal string. * Each byte of the array is converted to its corresponding two-character hex representation. * * This function is useful when you need to represent binary data as a string of hexadecimal characters. * * @example * console.log(hex(new Uint8Array([255]))); // 'ff' * console.log(hex([255, 0, 128])); // 'ff0080' * * @param value - The array to be converted, either a `Uint8Array` or a number array. * @returns A string of hexadecimal characters representing the array's byte values. * * @group Strings */ declare function hex(value: Uint8Array | number[]): string; /** * Checks if a given key is a deep key. * * A deep key is a string that contains a dot (.) or square brackets with a property accessor. * * @param {PropertyKey} key - The key to check. * @returns {boolean} - Returns true if the key is a deep key, otherwise false. * * Examples: * * isDeepKey('a.b') // true * isDeepKey('a[b]') // true * isDeepKey('a') // false * isDeepKey(123) // false * isDeepKey('a.b.c') // true * isDeepKey('a[b][c]') // true * isDeepKey('a.') // false * isDeepKey('.a') // false * isDeepKey('a[b') // false * isDeepKey('a]b]') // false * isDeepKey('a][b') // false * isDeepKey('') // false * isDeepKey('a[0]') // true * */ declare function isDeepKey(key: PropertyKey): boolean; /** * Returns true when value is property index * @group Strings */ declare function isIndex(value: PropertyKey, length?: number): boolean; /** * Checks if the provided text is a single emoji. * The function uses a regular expression to match the emoji and ensures that the entire string is a valid single emoji. * * @param {unknown} text - The input value to check. * @returns {boolean} - Returns `true` if the input is a single emoji, otherwise `false`. * * @example * isOneEmoji("😊"); // Returns: true * isOneEmoji("Hello 😊"); // Returns: false * isOneEmoji("😎"); // Returns: true * isOneEmoji("👨‍👩‍👧‍👦"); // Returns: true (family emoji with multiple characters) * isOneEmoji("not an emoji"); // Returns: false * * @group Strings */ declare function isOneEmoji(text: unknown): text is string; /** * Converts a two-letter ISO country code (e.g., 'US') to the corresponding flag emoji. * If the input is not a valid two-letter country code, it returns the original string. * * @param {string} iso - The two-letter ISO country code. * @returns {string} - The corresponding country flag emoji or the original input if it's invalid. * * @example * isoToFlagEmoji("US"); // Returns: 🇺🇸 * isoToFlagEmoji("GB"); // Returns: 🇬🇧 * isoToFlagEmoji("DE"); // Returns: 🇩🇪 * isoToFlagEmoji("xyz"); // Returns: "xyz" (invalid code) * * @group Strings */ declare function isoToFlagEmoji(iso: string): string; /** * Converts a string to kebab case. * * Kebab case is the naming convention in which each word is written in lowercase and separated by a dash (-) character. * * @param {string} str - The string that is to be changed to kebab case. * @returns {string} - The converted string to kebab case. * * @example * const convertedStr1 = kebabCase('camelCase') // returns 'camel-case' * const convertedStr2 = kebabCase('some whitespace') // returns 'some-whitespace' * const convertedStr3 = kebabCase('hyphen-text') // returns 'hyphen-text' * const convertedStr4 = kebabCase('HTTPRequest') // returns 'http-request' * * @group Strings */ declare function kebabCase(str: string): string; /** * Converts a string to lower case. * * Lower case is the naming convention in which each word is written in lowercase and separated by an space ( ) character. * * @param {string} str - The string that is to be changed to lower case. * @returns {string} - The converted string to lower case. * * @example * const convertedStr1 = lowerCase('camelCase') // returns 'camel case' * const convertedStr2 = lowerCase('some whitespace') // returns 'some whitespace' * const convertedStr3 = lowerCase('hyphen-text') // returns 'hyphen text' * const convertedStr4 = lowerCase('HTTPRequest') // returns 'http request' * * @group Strings */ declare const lowerCase: (str?: string) => string; /** * Masks part of the email address to provide a simple level of privacy. * The username part is partially masked with asterisks, while the domain remains intact. * * ⚠️ Returns an empty string if the provided value is invalid. * * @example * maskingEmail('andrew@gmail.com'); // 'a****w@gmail.com' * maskingEmail('user@domain.com'); // 'u***r@domain.com' * maskingEmail('invalidemail'); // '' * * @param value - The email address to be masked. * @returns The masked email address or an empty string if the value is invalid. * * @group Strings */ declare function maskingEmail(value: string): string; /** * Masks part of a phone number to provide a simple level of privacy. * The function replaces digits in a specified range with a given character. * Supports formatted phone numbers (e.g., `(000) 000-11-11`). * * ⚠️ Returns an empty string if the provided value is invalid. * * @example * maskingPhone('+18000551100'); // '+18XXXXX1100' * maskingPhone('+18000551100', 2, 4, '*'); // '+18*****1100' * maskingPhone('+1 800-055-1100'); // '+1 8XX-XXX-1100' * maskingPhone('+1234567890', 3, 5, 'X'); // '+1XXX567890' * * @param value - The phone number to be masked. * @param [fromPosition=2] - The starting position from left side where masking begins (default is 2). * @param [toPosition=4] - The position from right side where masking ends (default is 4). * @param [withChar='X'] - The character used to replace digits (default is 'X'). * @returns The masked phone number or an empty string if the value is invalid. * * @group Strings */ declare function maskingPhone(value: string, fromPosition?: number, toPosition?: number, withChar?: string): string; /** * Masks the middle characters of each word in the given string, leaving the first and last characters intact. * The characters in the middle of each word are replaced by a specified masking character (default is `*`). * * ⚠️ If the provided value is not a valid string, the function returns an empty string. * * **Note**: This function does not perform any validation or checks for non-alphabetic characters within words. * It simply masks all characters between the first and last character of each word. * * @param {string} value - The input string containing words to be masked. * @param {string} [withChar='*'] - The character used to replace the middle characters of each word. Default is `*`. * * @returns {string} The input string with middle characters of words masked, or an empty string if the input is invalid. * * @example * maskingWords('hello world'); // 'h**o w**d' * maskingWords('John Doe'); // 'J**n D**e' * maskingWords('a b c'); // '* * *' * * @group Strings */ declare function maskingWords(value: string, withChar?: string): string; /** * Useful when you need to generate almost secure object id in browser * * Based on [bson](https://github.com/mongodb/js-bson/blob/main/src/objectid.ts) * * @example * const userId = objectId(); // '67350af7885ba34010c83859' * * @group Strings */ declare function objectId(fromValue?: number | Date): string; /** * Generates a random string of the specified length using characters from a predefined set. * The characters used in the generated string include lowercase letters (a-z) and digits (0-9). * * @param {number} length - The length of the random string to generate. Must be a positive integer. * * @returns {string} A random string of the specified length, composed of characters from 'a-z' and '0-9'. * * @example * randomString(8); // e.g. 'a1b2c3d4' * randomString(12); // e.g. '3f6g7h8i9j0k' * randomString(5); // e.g. '1a2b3' * * @group Strings */ declare function randomString(length: number): string; /** * Converts a string to snake case. * * Snake case is the naming convention in which each word is written in lowercase and separated by an underscore (_) character. * * @param {string} str - The string that is to be changed to snake case. * @returns {string} - The converted string to snake case. * * @example * const convertedStr1 = snakeCase('camelCase') // returns 'camel_case' * const convertedStr2 = snakeCase('some whitespace') // returns 'some_whitespace' * const convertedStr3 = snakeCase('hyphen-text') // returns 'hyphen_text' * const convertedStr4 = snakeCase('HTTPRequest') // returns 'http_request' * * @group Strings */ declare const snakeCase: (str?: string) => string; /** * Formats a string by replacing format specifiers with values from the provided arguments. * It supports a variety of format types, including strings, numbers, and objects. * * ⚠️ This function mutates the `unusedArgs` array, which will contain any arguments * that were not used in the formatting process. * * @param line - The format string containing placeholders to be replaced by arguments. * Format specifiers are indicated by the `%` symbol, followed by a character indicating * the type of argument to insert (e.g., `%s` for string, `%d` for integer, `%f` for float). * @param args - The array of arguments to replace the format specifiers in the string. * The function will iterate over the arguments and substitute them into the format string * in the order they appear. * @param [unusedArgs=[]] - The array that will collect any unused arguments * that were not needed for formatting. This array is mutated by the function. * * @returns {string} The formatted string with placeholders replaced by corresponding arguments. * * @example * const unusedArgs: any[] = []; * * console.log(sprintf('Hello %s', ['World', 'Great'], unusedArgs)); * // Output: 'Hello World' * console.log(unusedArgs); * // Output: ['Great'] * * @example * console.log(sprintf('I have %d apples and %f.5 liters of water.', [5, 3.2], unusedArgs)); * // Output: 'I have 5 apples and 3.2 liters of water.' * console.log(unusedArgs); * // Output: [] * * @group Strings */ declare function sprintf(line: string, args: any[], unusedArgs?: any[]): string; /** * Converts the first character of each word in a string to uppercase and the remaining characters to lowercase. * * Start case is the naming convention in which each word is written with an initial capital letter. * @param {string} str - The string to convert. * @returns {string} The converted string. * * @example * const result1 = startCase('hello world'); // result will be 'Hello World' * const result2 = startCase('HELLO WORLD'); // result will be 'Hello World' * const result3 = startCase('hello-world'); // result will be 'Hello World' * const result4 = startCase('hello_world'); // result will be 'Hello World' * * @group Strings */ declare const startCase: (value?: string) => string; /** * Replaces placeholders in the input string with values from the provided object. * The placeholders are denoted by `{{ key }}` syntax, where `key` is a property name in the object. * The function optionally allows a custom method to handle how the values are retrieved from the object. * * @param {string} str - The string with placeholders to be replaced. Placeholders are in the form of `{{key}}`. * @param {T} obj - The object whose properties will be used to replace the placeholders in the string. * @param method - An optional custom method * to retrieve values from the object. The default method retrieves * the values by accessing the object property directly using the `key`. * * @returns {string} The string with placeholders replaced by the corresponding values from the object. * * @example * const context = { name: 'Andrew', age: 30 }; * console.log(strAssign('Hey {{ name }}! You are {{ age }} years old.', context)); * // Output: 'Hey Andrew! You are 30 years old.' * * @example * // Using a custom method * const context2 = { firstName: 'Andrew', lastName: 'L.' }; * const customMethod = (obj, key) => { * if (key === 'name') { * return obj.firstName + ' ' + obj.lastName; * } * return obj[key]; * }; * console.log(strAssign('Hello {{ name }}!', context2, customMethod)); * // Output: 'Hello Andrew L.!' * * @group Strings */ declare function strAssign(str: string, obj: T, method?: (obj: T, key: string) => any): string; declare var textEncoder: TextEncoder; declare var textDecoder: TextDecoder; /** * Converts `value` to a string key if it's not a string or symbol. * * @param {*} value The value to inspect. * @group Strings */ declare function toKey(value: any): string | symbol; /** * Converts a deep key string into an array of path segments. * * This function takes a string representing a deep key (e.g., 'a.b.c' or 'a[b][c]') and breaks it down into an array of strings, each representing a segment of the path. * * @param deepKey - The deep key string to convert. * @returns An array of strings, each representing a segment of the path. * * Examples: * * toPath('a.b.c') // Returns ['a', 'b', 'c'] * toPath('a[b][c]') // Returns ['a', 'b', 'c'] * toPath('.a.b.c') // Returns ['', 'a', 'b', 'c'] * toPath('a["b.c"].d') // Returns ['a', 'b.c', 'd'] * toPath('') // Returns [] * toPath('.a[b].c.d[e]["f.g"].h') // Returns ['', 'a', 'b', 'c', 'd', 'e', 'f.g', 'h'] * * @group Strings */ declare function toPath(deepKey: any): string[]; /** * Converts `value` to a string. * * An empty string is returned for `null` and `undefined` values. * The sign of `-0` is preserved. * * @param value - The value to convert. * @returns Returns the converted string. * * @example * toString(null) // returns '' * toString(undefined) // returns '' * toString(-0) // returns '-0' * toString([1, 2, -0]) // returns '1,2,-0' * toString([Symbol('a'), Symbol('b')]) // returns 'Symbol(a),Symbol(b)' * * @group Strings */ declare function toString(value?: any): string; /** * Truncates a string to the specified maximum length while preserving whole words * and appends ellipsis (`...`) if the string exceeds the maximum length. * Ensures that truncation does not occur if the difference is insignificant * (less than 5% of the original string length). * * @param {string} str - The input string to truncate. * @param {number} maxLength - The maximum allowed length for the string. * @param {number} insignificantThreshold - The insignificance threshold as a fraction of the original string length (default is 5%) * @returns {string} - The truncated string with ellipsis if applicable. * * * @example * // Basic truncation * truncate("This is a test string for truncation.", 20); * // Returns: "This is a test..." * * @example * // No truncation needed as the string length is within the limit * truncate("Short string", 20); * // Returns: "Short string" * * @example * // No truncation because the difference is insignificant * truncate("This string has an insignificant truncation.", 40); * // Returns: "This string has an insignificant truncation." * * @example * // Handles strings with no spaces gracefully * truncate("ThisStringHasNoSpacesButIsVeryLong", 10); * // Returns: "ThisString..." * * @group Strings */ declare function truncate(value: string, maxLength?: number, insignificantThreshold?: number): string; declare function removeVS16s(rawEmoji: string): string; declare const _default: RegExp; /** * Truncates the input string to the specified maximum length and appends an ellipsis (`...`) * if the string exceeds the maximum length. If the string is shorter than or equal to the * maximum length, it is returned unchanged. * * Unlike the `truncate` function, the result can be truncated in the middle of a word * * @param {string} value - The input string to truncate. * @param {number} maxLength - The maximum allowed length for the string (default is 30). * @returns {string} - The truncated string with ellipsis (`...`) if necessary. * * @example * wrapText("This is a long string", 10); // Returns: "This is a..." * wrapText("Short text", 20); // Returns: "Short text" * wrapText("Another long string example", 15); // Returns: "Another long..." * * @group Strings */ declare function wrapText(value: string, maxLength?: number): string; /** * Transform value to error object * @group Errors */ declare function toError(value: T, unknownMessage?: string): T extends Error ? T : Error; export { type AnyBrand, type AnyFunction, AppError, AppErrorOptions, type ArgumentsType, type Arrayable, AssertionError, AsyncIterableQueue, type Awaitable, Base64ToBytesOptions, BaseX, BitPack, BitUnpack, type Brand, type BrandTypeOf, BytesToBase64Options, CancellablePromise, CatchErrorResult, type Color, ColorChannels, ColorParser, type Data, type DateObject, DateObjectInput, DebouncedFunction, type DeepPartial, type DeepReadonly, Defer, instance as EJSON, EJSON as EJSONInstance, EJSONStream, EJSONStreamOptions, EJSONStreamOptionsWithPayload, type EJSONType, EnvParser, type ExecResult, type ExecResultToSkip, type ExecResultToSuccess, type ExecSkip, type ExecSkipData, type ExecSkipExtract, type ExecSuccess, type ExecSuccessData, type ExecSuccessExtract, FindMean, FixedMap, FixedWeakMap, type Fn$1 as Fn, FormatMoney, FormatNumber, type FunctionArgs, type GenericObject, type IfAny, type IsAny, type LiteralUnion, LogLevel, type Logger, LruCache, type Nothing, type OverwriteWith, type Prettify, type Primitive, type PromisifyFn, Queue, RandomizerOptions, ResourcePool, ResourcePoolEventMap, ResourcePoolOptions, RetryOnErrorConfig, SCHEDULER_JOB_FLAGS, Scheduler, SecureCustomizerOptions, type SelectOptionItem, type SelectOptions, SimpleDefaultEventMap, SimpleEventEmitter, SimpleEventMap, SortedArray, SortedArrayCompareFn, type SpecialValue, _default as TWEMOJI_REGEX, type ThemeConfig, ThrottledFunction, TimeBucket, TimeBucketOptions, type TimeObject, TimeObjectInput, TimeSpan, type TimeSpanUnit, type TimeString, type TimeValue, TimestampMsInput, TypeOf, TypeOfMap, type ValuesOfObject, WithCache, WithCacheBucketBatchOptions, WithCacheBucketOptions, WithCacheFixedOptions, WithCacheLruOptions, WithCacheOptions, WithCachePointer, WithCacheResult, WithCacheStorage, WithCode, WithCustomizer, WithCustomizerFactory, WithCustomizerValue, WrrItem, alpha, argumentsTag, arrayBufferTag, arrayTag, arrayable, assert_d_exports as assert, asyncFilter, asyncFilterMap, asyncFind, asyncForEach, asyncMap, avg, avgCircular, base62, base62Fast, base64, base64ToBytes, base64url, basex, bigInt64ArrayTag, bigIntBytes, bigIntFromBytes, bigUint64ArrayTag, bigintTag, bitPack, bitUnpack, blendColors, booleanTag, buildCssColor, bytesToBase64, cache, cacheBucket, cacheFixed, cacheLRU, camelCase, capitalize, captureStackTrace, catchError, channelsToHSL, channelsToHex, channelsToRGB, checkBitmask, chunk, chunkSeries, clamp, cleanEmpty, cleanObject, colorToChannels, compareBytes, concatenateBytes, constant, contrastRatio, convertToUnit, crc32, createCustomizer, createCustomizerFactory, createDateObject, createDeepCloneWith, createEJSON, createEJSONStream, createEnvParser, createFunction, createRandomizer, createScheduler, createSecureCustomizer, createTimeObject, createTimeSpan, createWithCache, cssVariable, dataViewTag, dateInDays, dateInSeconds, dateTag, debounce, deepAssign, deepClone, deepCloneWith, deepDefaults, deepFreeze, def, defer, delay, difference, dropCache, env, errorTag, escapeHtml, escapeNumeric, escapeRegExp, fastIdle, fastIdlePromise, fastRaf, filterMap, findMean, flagsToMap, flatten, float32ArrayTag, float64ArrayTag, formatMoney, formatNumber, functionTag, get, getFileExtension, getFileName, getInitials, getLoggerLevel, getMostSpecificPaths, getRandomInt, getRandomTime, getTag, getWords, groupBy, has, hasOwn, hasProtocol, hex, hexToChannels, hmToSeconds, hslToChannels, humanFileSize, humanize, identity, int16ArrayTag, int32ArrayTag, int8ArrayTag, interpolateColor, intersection, intersectionBy, isBigInt, isBoolean, isBuffer, isCached, isClient, isColorChannels, isCustomizerFactory, isDate, isDateObject, isDeepKey, isDef, isEmpty, isEqual, isError, isFunction, isIndex, isInfinity, isMap, isNode, isNullOrUndefined, isNumber, isObject, isOneEmoji, isPlainObject, isPrimitive, isPromise, isRegExp, isSet, isSkip, isString, isSuccess, isSymbol, isTimeObject, isTimeString, isTimeValue, isTypedArray, isValidWeekDay, isWeakMap, isWeakSet, isWithCache, isoToFlagEmoji, kebabCase, keyBy, logger, lowerCase, luminance, mapTag, maskingEmail, maskingPhone, maskingWords, negate, nextTickIteration, noop, nullTag, numberTag, objectId, objectTag, omit, omitPrefixed, orderBy, parseAllNumbers, parseAlpha, parsePercentage, percentOf, pick, pickPrefixed, qs, rafPromise, randomString, regexpTag, removeVS16s, retryOnError, rgbToChannels, rleDecode, rleEncode, round2digits, secondsToHm, set, setLoggerLevel, setTag, shuffle, snakeCase, sprintf, startCase, strAssign, stringTag, stringifyExecResult, sum, symbolTag, textDecoder, textEncoder, throttle, timeFromMinutes, timeStringify, timeToMinutes, timeout, timestamp, timestampMs, timestampToDate, tintedTextColor, toError, toKey, toMap, toPath, toPromise, toString, truncate, typeOf, uint16ArrayTag, uint16ToUint8, uint32ArrayTag, uint32ToUint8, uint8ArrayTag, uint8ClampedArrayTag, uint8ToUint16, uint8ToUint32, undefinedTag, unflatten, union, uniq, uniqBy, unset, updateWith, weakmapTag, weaksetTag, weeksInYear, weightedRoundRobin, withCache, withCacheBucket, withCacheBucketBatch, withCacheFixed, withCacheLRU, withDeepClone, withPointerCache, withResolve, wrapText }; //# sourceMappingURL=index.d.mts.map