@techmely/utils
Version:
Collection of helpful JavaScript / TypeScript utils
735 lines (535 loc) • 33.2 kB
TypeScript
import * as _techmely_types from '@techmely/types';
import { StringEnum, ComputeRange, CamelToSnakeNested, NodeEnv, NullList, EntityId, UnDef, Entity, MergeDeep, Records } from '@techmely/types';
export { isStream } from './isStream/index.js';
import 'node:stream';
type RopeSequenceCallback<T> = (elt: T, index: number) => boolean | VoidFunction;
declare class RopeSequence<T> {
static empty: RopeSequence<any>;
values: any;
static from<T>(values: readonly T[] | RopeSequence<T>): RopeSequence<T>;
leafAppend(other: Leaf<T>): RopeSequence<T> | Leaf<T> | undefined;
leafPrepend(other: any): RopeSequence<T> | Leaf<T> | undefined;
sliceInner(from: number, to: number): Leaf<any>;
getInner(index: number): T | undefined;
forEachInner(f: RopeSequenceCallback<T>, from: any, to: any, start: any): void;
forEachInvertedInner(f: RopeSequenceCallback<T>, from: any, to: any, start: any): void;
append(other: RopeSequence<T> | Leaf<T> | readonly T[]): RopeSequence<T> | Leaf<T>;
prepend(other: RopeSequence<T> | readonly T[]): RopeSequence<T> | Leaf<T>;
appendInner(other: Leaf<T>): Append<T> | Leaf<T>;
slice(from?: number, to?: number): RopeSequence<T> | Leaf<T>;
get(i: number): T | undefined;
forEach(f: (elt: T, index: number) => boolean | VoidFunction, from?: number, to?: number): void;
map<U>(f: RopeSequenceCallback<U>, from?: number, to?: number): U[];
set length(v: number);
get length(): number;
}
declare const GOOD_LEAF_SIZE = 200;
declare class Leaf<T = any> extends RopeSequence<T> {
values: any;
constructor(values: any);
flatten(): any;
sliceInner(from: number, to: number): Leaf<any>;
getInner(i: number): any;
forEachInner(f: RopeSequenceCallback<T>, from: number, to: number, start: number): false | undefined;
forEachInvertedInner(f: RopeSequenceCallback<T>, from: number, to: number, start: number): false | undefined;
leafAppend(other: Leaf<T>): Leaf<any> | undefined;
leafPrepend(other: Leaf<T>): Leaf<any> | undefined;
set length(v: number);
get length(): number;
get depth(): number;
}
declare class Append<T = any> extends RopeSequence<T> {
left: Leaf<T>;
right: Leaf<T>;
depth: number;
constructor(left: Leaf<T>, right: Leaf<T>);
flatten(): any;
getInner(i: number): T | undefined;
forEachInner(f: RopeSequenceCallback<T>, from: number, to: number, start: number): false | undefined;
forEachInvertedInner(f: RopeSequenceCallback<T>, from: number, to: number, start: number): false | undefined;
sliceInner(from: number, to: number): any;
leafAppend(other: Leaf<T>): Append<any> | undefined;
leafPrepend(other: Leaf<T>): Append<any> | undefined;
appendInner(other: Leaf<T>): any;
}
declare function $<K extends keyof HTMLElementTagNameMap>(tag: StringEnum<K>, _targer?: Element): HTMLElementTagNameMap[K] | null;
declare function $$<K extends keyof HTMLElementTagNameMap>(tag: StringEnum<K>, _targer?: Element): NodeListOf<HTMLElementTagNameMap[K]> | null;
declare function alphaHex(hex: string, alpha: ComputeRange<MAXIMUM_ALLOWED_BOUNDARY$1>[number]): string;
type MAXIMUM_ALLOWED_BOUNDARY$1 = 101;
declare function createCachedImport<T>(name: string, imp: () => Promise<T>): () => T | Promise<T>;
declare function cacheStringFunction<T extends (str: string) => string>(fn: T): T;
declare function calculateFrequencies<T = any>(arr: T[]): {};
declare function calculateScrollPercentage(): number;
type MaybeReturnType<T> = T extends (...args: any) => any ? ReturnType<T> : T;
declare function callOrReturn<T>(value: T, context?: any, ...props: any[]): MaybeReturnType<T>;
declare const camel2snake: (str: string) => string;
declare function camel2SnakeObject<T extends Object>(obj: T): CamelToSnakeNested<T>;
declare const camelize: (str: string) => string;
declare const cancelIdleCallback: ((handle: number) => void) & typeof globalThis.cancelIdleCallback;
declare const capitalizeFirst: (value: string) => string;
declare function chromeVersion(): number;
declare function chunk<T>(array: readonly T[], size?: number): T[][];
declare function clamp(n: number, min: number, max: number): number;
type ResponseTime = {
seconds: number;
milliseconds: number;
nanoseconds: number | bigint;
};
declare function convertHrTime(hrtime: bigint): ResponseTime;
interface CookieSerializeOptions {
domain?: string;
encode?(value: string): string;
expires?: Date;
httpOnly?: boolean;
maxAge?: number;
path?: string;
priority?: "Low" | "Medium" | "High";
sameSite?: true | false | "lax" | "strict" | "none";
secure?: boolean;
}
interface CookieParseOptions {
decode?(value: string): string;
}
declare function parseCookie(str: string, options?: CookieParseOptions): Record<string, string>;
declare function serializeCookie(name: string, value: string, options?: CookieSerializeOptions): string;
declare const listenCookieChange: (callback: ({ oldCookie, newCookie }: any) => void, interval?: number) => void;
declare class CookieService {
nodeEnv: NodeEnv;
env: string;
domain: string;
tokenName: string;
constructor(nodeEnv: NodeEnv, env: string, cookieDomain: string);
get(name: string, options?: CookieParseOptions): string | undefined;
set(key: string, value: string, options?: CookieSerializeOptions): void;
setToken(token: string): void;
getToken(): string | undefined;
clearToken(): void;
}
declare function createElement(tag: StringEnum<keyof HTMLElementTagNameMap> | HTMLElement, ...children: any[]): HTMLElement;
interface CreateStyleTagOptions extends Record<string, any> {
id: string;
}
declare function createStyleTag(style: string, options: CreateStyleTagOptions): HTMLStyleElement;
declare function cutString(value: string, limit: number): string | undefined;
declare function debounce<Func extends (...args: any[]) => void>(func: Func, delay: number, immediate?: boolean): Func;
type DelayOptions$1 = {
signal?: AbortController["signal"] | null;
};
declare function delaySignal(ms: number, { signal }: DelayOptions$1): Promise<void>;
declare function deleteProps(obj: Record<string, any>, propOrProps: string | string[]): Record<string, any>;
declare function downloadByData(data: BlobPart, filename: string, mime?: string, bom?: BlobPart): void;
type EventType = string | symbol;
type Handler<T = unknown> = (event: T) => void;
type WildcardHandler<T = Record<string, unknown>> = (type: keyof T, event: T[keyof T]) => void;
type EventHandlerList<T = unknown> = Handler<T>[];
type WildCardEventHandlerList<T = Record<string, unknown>> = WildcardHandler<T>[];
type EventHandlerMap<Events extends Record<EventType, unknown>> = Map<keyof Events | "*", EventHandlerList<Events[keyof Events]> | WildCardEventHandlerList<Events>>;
interface Emitter<Events extends Record<EventType, unknown>> {
events: EventHandlerMap<Events>;
on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;
on(type: "*", handler: WildcardHandler<Events>): void;
off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void;
off(type: "*", handler: WildcardHandler<Events>): void;
emit<Key extends keyof Events>(type: Key, event: Events[Key]): void;
emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;
}
declare function emitter<Events extends Record<EventType, unknown>>(all?: EventHandlerMap<Events>): Emitter<Events>;
type EnvObject = Record<string, string | undefined>;
declare function envShims(): EnvObject;
declare function escapeRegExp(val: string): string;
declare function filterArrays<A, B>(arr1: A[], arr2: B[], filterCondition: (a: A, b: B) => boolean): A[];
declare function findDuplicates<T = any>(items: T[]): T[];
declare function findFirstDefined<T>(...args: (T | undefined)[]): (T & ({} | null)) | undefined;
declare function findLastIndex<T>(array: T[], predicate: (value: T, index: number, obj: T[]) => boolean): number;
declare function firstUniqueArr(array: (string | number)[]): string | number | undefined;
declare function firstUniqueChar(value: string): string | undefined;
declare function flattenObject(obj: Record<string, any>, prefix?: string, result?: Record<string, any>): Record<string, any>;
interface FormatBytesOptions {
numberOfDecimals: number;
}
declare const formatBytes: (bytes: number, options?: Partial<FormatBytesOptions>) => string;
declare function formatLot10Volume(volume: NullList<EntityId>, precision?: number, defaultValue?: UnDef<EntityId>): EntityId;
declare function formatNumber(num: NullList<EntityId>, precision?: number, defaultValue?: UnDef<EntityId>): EntityId;
declare function freezeMainThread(duration: number): void;
declare function fromStringToPrimitives(value: any): any;
declare function requestFullscreen(mode?: boolean, el?: string): void;
declare function generateSample<T>(arr: T[], count: number): T[];
declare function get(from: any, selector: string): any;
declare function getQuarter(d?: Date): number;
declare function getRandomInt(min: number, max: number): number;
declare function getRandomIntInclusive(min: number, max: number): number;
declare function getRandomString(length: number, alphanumeric?: "a" | "n"): string;
declare function getStrokeRadius(size: number, thinning: number, easing: (t: number) => number, pressure?: number): number;
declare const getEnvVar: <T extends string>(variableName: string, defaultValue?: any) => any;
declare function groupBy<K, V>(list: V[], keyGetter: (input: V) => K): Map<K, V[]>;
declare function hasDuplicates<T = any>(arr: T[]): boolean;
declare function haveSameElement<T1, T2>(arr1: T1[], arr2: T2[]): boolean;
declare const hyphenate: (str: string) => string;
declare function intToBuffer(integer: number | bigint): Buffer;
declare function intToHex(integer: number | bigint): string;
declare function invariant(condition: any, message?: string | (() => string)): asserts condition;
declare function invariant(condition: any, exception?: any): asserts condition;
declare function isAndroid(): boolean;
declare function isAppleDevice(): boolean;
declare function isArray<T = unknown>(val: any): val is T[];
declare function isBase64(base: string): boolean;
declare function isBoolean(val: any): val is boolean;
declare const botPatterns: string[];
declare const botFullPattern = " daum[ /]| deusu/| yadirectfetcher|(?:^| )site|(?:^|[^g])news|(?<! (?:channel/|google/))google(?!(app|/google| pixel))|(?<! cu)bot(?:[^\\w]|_|$)|(?<! ya(?:yandex)?)search|(?<!(?:lib))http|(?<![hg]m)score|@[a-z]|\\(at\\)[a-z]|\\[at\\][a-z]|^12345|^<|^[\\w \\.\\-\\(?:\\):]+(?:/v?\\d+(\\.\\d+)?(?:\\.\\d{1,10})?)?(?:,|$)|^[^ ]{50,}$|^active|^ad muncher|^amaya|^anglesharp/|^avsdevicesdk/|^bidtellect/|^biglotron|^bot|^btwebclient/|^clamav[ /]|^client/|^cobweb/|^coccoc|^custom|^ddg[_-]android|^discourse|^dispatch/\\d|^downcast/|^duckduckgo|^facebook|^fdm[ /]\\d|^getright/|^gozilla/|^hatena|^hobbit|^hotzonu|^hwcdn/|^jeode/|^jetty/|^jigsaw|^linkdex|^metauri|^microsoft bits|^movabletype|^mozilla/\\d\\.\\d \\(compatible;?\\)$|^mozilla/\\d\\.\\d \\w*$|^navermailapp|^netsurf|^nuclei|^offline explorer|^php|^postman|^postrank|^python|^rank|^read|^reed|^rest|^serf|^snapchat|^space bison|^svn|^swcd |^taringa|^thumbor/|^tumblr/|^user-agent:|^valid|^venus/fedoraplanet|^w3c|^webbandit/|^webcopier|^wget|^whatsapp|^xenu link sleuth|^yahoo|^yandex|^zdm/\\d|^zoom marketplace/|^{{.*}}$|adbeat\\.com|appinsights|archive|ask jeeves/teoma|bit\\.ly/|bluecoat drtr|browsex|burpcollaborator|capture|catch|check|chrome-lighthouse|chromeframe|classifier|cloud|crawl|cryptoapi|dareboost|datanyze|dataprovider|dejaclick|dmbrowser|download|evc-batch/|feed|firephp|freesafeip|gomezagent|headless|httrack|hubspot marketing grader|hydra|ibisbrowser|images|inspect|iplabel|ips-agent|java(?!;)|library|mail\\.ru/|manager|monitor|neustar wpm|nutch|offbyone|optimize|pageburst|parser|perl|phantom|pingdom|powermarks|preview|proxy|ptst[ /]\\d|reader|reputation|resolver|retriever|rexx;|rigor|robot|rss|scan|scrape|server|sogou|sparkler/|speedcurve|spider|splash|statuscake|stumbleupon\\.com|supercleaner|synapse|synthetic|torrent|trace|transcoder|twingly recon|url|virtuoso|wappalyzer|webglance|webkit2png|whatcms/|wordpress|zgrab";
declare const botRegPattern: RegExp;
declare function isBotNaive(userAgent?: string | null): boolean;
declare function isBot(userAgent?: string | null): boolean;
declare function createIsBot(customPattern: RegExp): (userAgent?: string | null) => boolean;
declare function createIsBotFromList(list: string[]): (userAgent?: string | null) => boolean;
declare function isBotMatch(userAgent?: string | null): string | null;
declare function isBotMatches(userAgent?: string | null): string[];
declare function isBotPattern(userAgent?: string | null): string | null;
declare function isBotPatterns(userAgent?: string | null): string[];
declare function isBrowser(): boolean;
declare function isChrome(): boolean;
declare global {
interface Window {
chrome: any;
}
}
declare function isIOSChrome(): false | RegExpMatchArray | null;
declare function isCrawler(): boolean;
declare function isDate(val: unknown): val is Date;
declare function isDeepEqual(obj1: any, obj2: any): boolean;
declare function isDefined<T = any>(val?: T): val is T;
declare function isDistinctArray<T = any>(arr: T[]): boolean;
declare function isEdgeBrowser(): boolean;
declare function isEmpties(...args: any[]): boolean;
declare function isEmpty<T = unknown>(val: T): boolean;
type EmptyArray<T> = readonly [T, ...ReadonlyArray<T>];
declare function isEmptyArr<T>(array: ReadonlyArray<T> | undefined): array is EmptyArray<T>;
declare function isFunction(val: any): val is Function;
declare function isGecko(): boolean;
declare const hexColor: RegExp;
declare function isHex(hex: string): boolean;
declare function isIOS(): boolean;
declare function isISOString(val: string): boolean;
declare function isISOStringWithTimezone(val: string): boolean;
declare function isKeyOf<T extends object>(obj: T, k: keyof any): k is keyof T;
declare function isLinux(): boolean;
declare function isMacOS(): boolean;
declare function isMobile(): boolean | undefined;
declare function isNodeProd(): boolean;
declare function isNodeTest(): boolean;
declare function isNotEmpties(...args: any[]): boolean;
declare function isNotEmpty<T = unknown>(val: T): boolean;
declare function isNotNull<T>(v: T | null): v is Exclude<T, null>;
declare function isNotNullish<T>(v: T | null | undefined): v is NonNullable<T>;
declare function isNullOrUndefined(value: unknown): value is undefined | null;
declare function isNumber(val: any): val is number;
declare function isObject(val: unknown): val is Record<string, any>;
declare function isOpera(): boolean;
declare global {
interface Window {
opr: any;
}
}
declare function isPlainObject(value: any): boolean;
declare function getTag(value: any): string;
declare function isPngImage(buffer: Buffer | Uint8Array): boolean;
declare function isPrefersReducedMotion(): boolean | undefined;
type Primitives = {
value: string | number | boolean | Date | null;
};
declare function isPrimitive(value: unknown): value is Primitives;
declare function isPromise<T = any>(val: unknown): val is Promise<T>;
declare function isRegExp(value: any): value is RegExp;
declare function isSafari(): boolean;
declare function isSameDay(date1?: Date, date2?: Date): boolean;
declare function isSameMonth(date1?: Date, date2?: Date): boolean;
declare function isServer(): boolean;
declare function isSet(val: unknown): val is Set<any>;
declare function isSlowConnection(): boolean | undefined;
declare global {
interface Navigator {
connection: {
downlink: number;
saveData: boolean;
effectiveType: string;
rtt: number;
onchange?: (data: any) => void;
};
}
}
declare function isString(val: unknown): val is string;
declare function isSupportsAbortController(): boolean;
declare function isSupportsFormData(): boolean;
declare function isSupportsRequestStreams(): boolean;
declare function isSupportsResponseStreams(): boolean;
interface JsonLdProps {
type?: string;
scriptId?: string;
[key: string]: any;
}
type JsonLdProvider = {
type?: "Organization" | "Person";
name: string;
url?: string;
};
type JsonLdArticleAuthor = {
name: string;
type?: string;
url?: string;
};
interface NewsArticleJsonLd extends JsonLdProps {
scriptId?: string;
url: string;
title: string;
images: ReadonlyArray<string>;
section: string;
keywords?: string;
dateCreated?: string;
datePublished: string;
dateModified?: string;
authorName: string | string[];
description: string;
body: string;
publisherName: string;
publisherLogo: string;
}
declare function getNewsArticleJsonLd({ scriptId, type, keyOverride, url, title, images, section, dateCreated, datePublished, dateModified, authorName, publisherName, publisherLogo, body, ...rest }: NewsArticleJsonLd): string;
type JsonLdBlogPostingProps = {
canonical: string;
title: string;
description: string;
thumbnail: string;
datePublished: string;
dateModified: string;
author: string | string[] | JsonLdArticleAuthor | JsonLdArticleAuthor[];
publisher: {
name?: string;
logo?: string;
};
image?: string;
};
declare function getBlogAuthorJsonLd(props: JsonLdBlogPostingProps): string;
interface ItemListElementsJsonLd {
item: string;
name: string;
position: number;
}
declare function setItemListElementsJson(items: ItemListElementsJsonLd[]): {
"@type": string;
position: number;
item: {
"@id": string;
name: string;
};
}[] | undefined;
declare function getBreadcrumbJsonLd(items: ItemListElementsJsonLd[]): string;
declare function getCourseJsonLd(name: string, provider: JsonLdProvider, props?: any): string;
declare function setAuthorJsonLd(author: string | string[] | JsonLdArticleAuthor | JsonLdArticleAuthor[]): {
"@type": string;
name: string;
url?: undefined;
} | {
"@type": string;
name: string;
url: string | undefined;
} | ({
"@type": string;
name: string;
url?: undefined;
} | {
"@type": string;
name: string;
url: string | undefined;
})[];
declare function setPublisherJsonLd(name?: string, logo?: string): {
"@type": string;
name: string | undefined;
logo: {
"@type": string;
url: string | undefined;
};
} | undefined;
declare function setProvider(provider: JsonLdProvider): {
"@type": "Organization" | "Person";
name: string;
sameAs: string | undefined;
} | undefined;
declare function toJsonLd(type: string, jsonLd: any): string;
declare function isSymbol(val: unknown): val is symbol;
declare function isToday(date: Date): boolean;
declare function isUndefined<T = any>(val?: T): val is T;
declare function isWebkit(): boolean;
declare function isWindows(): boolean;
declare function kebabize(value: string): string;
declare function lerp(y1: number, y2: number, mu: number): number;
declare function listify<O extends Record<string, any>, T = any>(obj: O, mapFn: (key: string, value: Entity) => any): T[];
declare const MIME_TYPES: Record<string, string>;
declare function lookupMineType(extention: string): string | undefined;
declare function mapObject<K extends string, V = any, NK = K, NV = V>(obj: Record<K, V>, fn: (key: K, value: V) => [NK, NV] | undefined): Record<K, V>;
declare function mask(cc: number | string, num?: number, mask?: string): string;
declare function mergeDeep<T extends Record<string, any>, S extends Record<string, any>>(target: T, ...sources: S[]): MergeDeep<T, S>;
declare function minMax(value?: number, min?: number, max?: number): number;
declare class MutexLock {
#private;
lock(): PromiseLike<() => void>;
dispatch<T>(fn: () => PromiseLike<T>): Promise<T>;
}
declare function nextEvent(element: HTMLElement, eventName: string): Promise<unknown>;
declare function nextFrame(): Promise<number>;
declare function nextIdle(): typeof setTimeout | Promise<IdleDeadline>;
declare const noop: () => void;
declare function normalize<T>(array: T[], key: keyof T): Record<typeof key, T>;
declare function checkBoundaryPrecision(num: number): void;
declare function enableBoundaryCheckingPrecision(flag?: boolean): void;
declare function createOperationPrecision(operation: (n1: EntityId, n2: EntityId) => number): (...nums: EntityId[]) => number;
declare function digitLengthPrecision(num: EntityId): number;
declare const dividePrecision: (...nums: _techmely_types.EntityId[]) => number;
declare function float2FixedPrecision(num: EntityId): number;
declare const minusPrecision: (...nums: _techmely_types.EntityId[]) => number;
declare const plusPrecision: (...nums: _techmely_types.EntityId[]) => number;
declare function roundPrecision(num: EntityId, decimal: number): number;
declare function stripPrecision(num: EntityId, precision?: number): number;
declare const timesPrecision: (...nums: _techmely_types.EntityId[]) => number;
declare function objectEntries<T extends object>(obj: T): [keyof T, T[keyof T]][];
declare function objectKeys<T extends object>(obj: T): Array<keyof T>;
declare function onClickOutside(element: HTMLElement, callback: CallableFunction): void;
declare function onScrollStop(callback: CallableFunction, timeout?: number): void;
type OrderMapContent<T = any> = string | T;
type MapLike<T = any> = Record<string, T> | OrderedMap<T>;
declare class OrderedMap<T = any> {
#private;
content: OrderMapContent<T>[];
private constructor();
static from<T>(value: MapLike<T>): OrderedMap<T>;
get size(): number;
get(key: OrderMapContent): OrderMapContent<T> | undefined;
update(key: string, value: T, newKey?: string): OrderedMap<T>;
remove(key: OrderMapContent): OrderedMap<T>;
addToStart(key: OrderMapContent, value: T): OrderedMap<T>;
addToEnd(key: OrderMapContent, value: T): OrderedMap<T>;
addBefore(place: string, key: OrderMapContent, value: T): OrderedMap<T>;
forEach(fn: (key: OrderMapContent, value: OrderMapContent) => any): void;
prepend(map: MapLike<T>): OrderedMap<T>;
append(map: MapLike<T>): OrderedMap<T>;
subtract(map: MapLike<T>): OrderedMap<T>;
toObject(): Record<string, T>;
}
declare function parseQueryString(url: string): Record<string, string>;
declare function partition<T = any>(arr: T[], fn: (val: T, index: number, arr: T[]) => boolean): IterableIterator<any>;
declare const pascalToKebabCase: (p: string) => string;
declare function ranking<T = any>(arr: T[], compFn: (a: T, b: T) => boolean): number[];
declare function removeWhitespace(value: string): string;
declare const runAsync: (fn: () => void) => Promise<unknown>;
declare function scrollToTop(): void;
interface Semaphore {
acquire(): Promise<void>;
release(): void;
size(): number;
}
declare const getSemaphore: (key?: any, concurrency?: number) => Semaphore;
declare function stringifyQueryObject(queryParameters: Record<string, unknown>): string;
declare function throttle<F extends (...args: any[]) => void>(func: F, limit: number): F;
declare function toISOStringTimezone(date: Date): string;
declare function toNumber(value: string): number | string;
declare function truncate(str: string, limit: number, text?: string): string;
declare function useObserverElement(): (element: Element, callback: IntersectionObserverCallback) => () => void;
declare function webkitVersion(): number;
declare class PCancelable<ValueType> extends Promise<ValueType> {
#private;
static fn<ReturnType>(userFn: (onCancel: OnCancelFunction) => PromiseLike<ReturnType>): () => PCancelable<ReturnType>;
static fn<Agument1Type, ReturnType>(userFn: (argument1: Agument1Type, onCancel: OnCancelFunction) => PromiseLike<ReturnType>): (argument1: Agument1Type) => PCancelable<ReturnType>;
static fn<Agument1Type, Agument2Type, ReturnType>(userFn: (argument1: Agument1Type, argument2: Agument2Type, onCancel: OnCancelFunction) => PromiseLike<ReturnType>): (argument1: Agument1Type, argument2: Agument2Type) => PCancelable<ReturnType>;
static fn<Agument1Type, Agument2Type, Agument3Type, ReturnType>(userFn: (argument1: Agument1Type, argument2: Agument2Type, argument3: Agument3Type, onCancel: OnCancelFunction) => PromiseLike<ReturnType>): (argument1: Agument1Type, argument2: Agument2Type, argument3: Agument3Type) => PCancelable<ReturnType>;
static fn<Agument1Type, Agument2Type, Agument3Type, Agument4Type, ReturnType>(userFn: (argument1: Agument1Type, argument2: Agument2Type, argument3: Agument3Type, argument4: Agument4Type, onCancel: OnCancelFunction) => PromiseLike<ReturnType>): (argument1: Agument1Type, argument2: Agument2Type, argument3: Agument3Type, argument4: Agument4Type) => PCancelable<ReturnType>;
static fn<Agument1Type, Agument2Type, Agument3Type, Agument4Type, Agument5Type, ReturnType>(userFn: (argument1: Agument1Type, argument2: Agument2Type, argument3: Agument3Type, argument4: Agument4Type, argument5: Agument5Type, onCancel: OnCancelFunction) => PromiseLike<ReturnType>): (argument1: Agument1Type, argument2: Agument2Type, argument3: Agument3Type, argument4: Agument4Type, argument5: Agument5Type) => PCancelable<ReturnType>;
static fn<ReturnType>(userFn: (_arguments: unknown[]) => PromiseLike<ReturnType>): (_arguments: unknown[]) => PCancelable<ReturnType>;
constructor(executor: Executor<ValueType>);
then(onFulfilled: any, onRejected: any): Promise<ValueType>;
catch(onRejected: any): Promise<ValueType>;
finally(onFinally: any): Promise<ValueType>;
cancel(reason: any): void;
get isCanceled(): boolean;
}
interface OnCancelFunction {
(cancelHandler: () => void): void;
shouldReject: boolean;
}
type Executor<T> = (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: unknown) => void, onCancel: OnCancelFunction) => void;
declare class PDefer {
placeholder: string;
}
declare function delay<T = any>(milliseconds: number, options?: DelayOptions<T>): Promise<T>;
declare function createDelay<T = any>(milliseconds: number, { value, signal }?: DelayOptions<T>): Promise<T>;
declare function rangeDelay<T>(minimum: number, maximum: number, options?: DelayOptions<T>): Promise<T>;
declare function clearDelay(promise: Promise<unknown>): void;
type DelayOptions<T> = {
value?: T;
signal?: AbortSignal;
};
declare class PQueue {
placeholder: string;
}
declare class PTimeOut {
placeholder: string;
}
type MAXIMUM_ALLOWED_BOUNDARY = 101;
declare function percentToHex(percent: ComputeRange<MAXIMUM_ALLOWED_BOUNDARY>[number]): string;
declare function pick(state: Records, paths: string | string[]): Records;
interface Process extends Partial<Omit<typeof globalThis.process, "versions">> {
env: EnvObject;
versions: Record<string, string>;
}
declare const globProcess: Process;
declare const emailRegex: RegExp;
declare const isValidEmail: (email: string) => boolean;
declare const vietnamPhoneRegex: RegExp;
declare const isValidVnPhone: (phone: string) => boolean;
declare const urlRegex: RegExp;
declare const isValidUrl: (path: string) => boolean;
declare const multilineCommentsRegex: RegExp;
declare const singlelineCommentsRegex: RegExp;
declare const escapedSpaceCharactersRegex: RegExp;
declare function remove<T>(arr: T[], el: T): void;
declare function removeEmptyObj(obj: any): {
[k: string]: unknown;
};
declare function removeUndefObj<T extends Record<string, unknown>>(obj: T): T;
declare const requestIdleCallback: ((callback: IdleRequestCallback, options?: IdleRequestOptions) => number) & typeof globalThis.requestIdleCallback;
declare function shuffle<T>(array: T[]): T[];
declare function singleton<Value>(name: string, valueFactory: () => Value): Value;
declare global {
var __singletons: Record<string, unknown>;
}
declare function sleep(ms: number): Promise<void>;
declare function slugify(text: string): string;
declare const snake2camel: (str: string) => string;
declare enum SortDirection {
ASC = "ASC",
DESC = "DESC"
}
declare function sortByDate<T>(a: T, b: T, key: keyof T, direction?: SortDirection): 0 | 1 | -1;
type SortOptions = {
locale?: string;
shouldIgnoreZero?: boolean;
};
declare function sortData(a: unknown, b: unknown, direction?: SortDirection | null, options?: SortOptions): number;
declare function stopAnimations(el: HTMLElement): Promise<unknown[]>;
declare function suffixAmPm(h: number): string;
declare function sum(...args: number[] | number[][]): number;
declare function take<T>(array: readonly T[], limit: number): T[];
declare function timeSpan(): {
(): number;
toRounded(): number;
toSeconds(): number;
toNanoseconds(): bigint;
};
declare function toBoolean(val: boolean | string | undefined): boolean;
declare function toPointsArray<T extends number[], K extends {
x: number;
y: number;
pressure?: number;
}>(points: (T | K)[]): number[][];
declare function toggleClass(dom: HTMLElement, cls: string, on?: boolean): void;
declare function transitionEnd(element: HTMLElement): Promise<unknown>;
declare function unique<T>(array: readonly T[]): T[];
declare function uniqueObj<T>(items: readonly T[], uniqueKey: keyof T): T[];
export { $, $$, type CookieParseOptions, type CookieSerializeOptions, CookieService, type DelayOptions, type Emitter, type EnvObject, type EventHandlerList, type EventHandlerMap, type EventType, GOOD_LEAF_SIZE, type Handler, type ItemListElementsJsonLd, type JsonLdArticleAuthor, type JsonLdBlogPostingProps, type JsonLdProps, type JsonLdProvider, MIME_TYPES, type MapLike, type MaybeReturnType, MutexLock, type OnCancelFunction, OrderedMap, PCancelable, PDefer, PQueue, PTimeOut, type Primitives, type Process, type ResponseTime, RopeSequence, type RopeSequenceCallback, SortDirection, type WildCardEventHandlerList, type WildcardHandler, alphaHex, botFullPattern, botPatterns, botRegPattern, cacheStringFunction, calculateFrequencies, calculateScrollPercentage, callOrReturn, camel2SnakeObject, camel2snake, camelize, cancelIdleCallback, capitalizeFirst, checkBoundaryPrecision, chromeVersion, chunk, clamp, clearDelay, convertHrTime, createCachedImport, createDelay, createElement, createIsBot, createIsBotFromList, createOperationPrecision, createStyleTag, cutString, debounce, delay, delaySignal, deleteProps, digitLengthPrecision, dividePrecision, downloadByData, emailRegex, emitter, enableBoundaryCheckingPrecision, envShims, escapeRegExp, escapedSpaceCharactersRegex, filterArrays, findDuplicates, findFirstDefined, findLastIndex, firstUniqueArr, firstUniqueChar, flattenObject, float2FixedPrecision, formatBytes, formatLot10Volume, formatNumber, freezeMainThread, fromStringToPrimitives, generateSample, get, getBlogAuthorJsonLd, getBreadcrumbJsonLd, getCourseJsonLd, getEnvVar, getNewsArticleJsonLd, getQuarter, getRandomInt, getRandomIntInclusive, getRandomString, getSemaphore, getStrokeRadius, getTag, globProcess, groupBy, hasDuplicates, haveSameElement, hexColor, hyphenate, intToBuffer, intToHex, invariant, isAndroid, isAppleDevice, isArray, isBase64, isBoolean, isBot, isBotMatch, isBotMatches, isBotNaive, isBotPattern, isBotPatterns, isBrowser, isChrome, isCrawler, isDate, isDeepEqual, isDefined, isDistinctArray, isEdgeBrowser, isEmpties, isEmpty, isEmptyArr, isFunction, isGecko, isHex, isIOS, isIOSChrome, isISOString, isISOStringWithTimezone, isKeyOf, isLinux, isMacOS, isMobile, isNodeProd, isNodeTest, isNotEmpties, isNotEmpty, isNotNull, isNotNullish, isNullOrUndefined, isNumber, isObject, isOpera, isPlainObject, isPngImage, isPrefersReducedMotion, isPrimitive, isPromise, isRegExp, isSafari, isSameDay, isSameMonth, isServer, isSet, isSlowConnection, isString, isSupportsAbortController, isSupportsFormData, isSupportsRequestStreams, isSupportsResponseStreams, isSymbol, isToday, isUndefined, isValidEmail, isValidUrl, isValidVnPhone, isWebkit, isWindows, kebabize, lerp, listenCookieChange, listify, lookupMineType, mapObject, mask, mergeDeep, minMax, minusPrecision, multilineCommentsRegex, nextEvent, nextFrame, nextIdle, noop, normalize, objectEntries, objectKeys, onClickOutside, onScrollStop, parseCookie, parseQueryString, partition, pascalToKebabCase, percentToHex, pick, plusPrecision, rangeDelay, ranking, remove, removeEmptyObj, removeUndefObj, removeWhitespace, requestFullscreen, requestIdleCallback, roundPrecision, runAsync, scrollToTop, serializeCookie, setAuthorJsonLd, setItemListElementsJson, setProvider, setPublisherJsonLd, shuffle, singlelineCommentsRegex, singleton, sleep, slugify, snake2camel, sortByDate, sortData, stopAnimations, stringifyQueryObject, stripPrecision, suffixAmPm, sum, take, throttle, timeSpan, timesPrecision, toBoolean, toISOStringTimezone, toJsonLd, toNumber, toPointsArray, toggleClass, transitionEnd, truncate, unique, uniqueObj, urlRegex, useObserverElement, vietnamPhoneRegex, webkitVersion };