@ztimson/utils 0.10.1 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,66 @@
1
+ export declare function addUnique<T>(array: T[], el: T): T[];
2
+ export declare function arrayDiff(a: any[], b: any[]): any[];
3
+ /**
4
+ * Provides a shorthand for sorting arrays of complex objects by a string property
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * let arr = [{a: 'Apple', b: 123}, {a: 'Carrot', b: 789}, {a: 'banana', b: 456}];
9
+ * arr.sort(caseInsensitiveSort('a'));
10
+ * ```
11
+ *
12
+ * @param {string} prop - Name of property to use, supports dot notation
13
+ * @returns {(a, b) => (number)} - Function to handle sort (Meant to be passed to Array.prototype.sort or used in sortFn)
14
+ */
15
+ export declare function caseInsensitiveSort(prop: string): (a: any, b: any) => number;
16
+ /**
17
+ * Recursively flatten nested arrays
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const arr = [
22
+ * {label: null, url: '/'},
23
+ * {label: 'Model Admin', url: '/model-admin'},
24
+ * [
25
+ * {label: 'Elements', url: '/model-admin/elements'},
26
+ * {label: 'Example', url: null}
27
+ * ]
28
+ * ];
29
+ *
30
+ * console.log(flattenArr(arr));
31
+ * // Output:
32
+ * [
33
+ * {label: null, url: '/'},
34
+ * {label: 'Model Admin', url: '/model-admin'},
35
+ * {label: 'Elements', url: '/model-admin/elements'},
36
+ * {label: 'Example', url: null}
37
+ * ]
38
+ * ```
39
+ *
40
+ * @param {any[]} arr - n-dimensional array
41
+ * @param {any[]} result - Internal use only -- Keeps track of recursion
42
+ * @returns {any[]} - Flattened array
43
+ */
44
+ export declare function flattenArr(arr: any[], result?: any[]): any[];
45
+ /**
46
+ * Provides a shorthand for sorting arrays of complex objects
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * let arr = [{a: {b: 2}}, {a: {b: 3}}, {a: {b: 1}}];
51
+ * arr.sort(sortByProp('a.b'));
52
+ * ```
53
+ *
54
+ * @param {string} prop - Name of property to use, supports dot notation
55
+ * @param {boolean} reverse - Reverse the order of the sort
56
+ * @returns {(a, b) => (number)} - Function to handle sort (Meant to be passed to Array.prototype.sort)
57
+ */
58
+ export declare function sortByProp(prop: string, reverse?: boolean): (a: any, b: any) => number;
59
+ export declare function findByProp(prop: string, value: any): (v: any) => boolean;
60
+ export declare function makeUnique(arr: any[]): any[];
61
+ /**
62
+ * Make sure value is an array, if it isn't wrap it in one.
63
+ * @param {T[] | T} value Value that should be an array
64
+ * @returns {T[]} Value in an array
65
+ */
66
+ export declare function makeArray<T>(value: T | T[]): T[];
package/dist/aset.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ export declare class ASet<T> extends Array {
2
+ get size(): number;
3
+ constructor(elements?: T[]);
4
+ add(el: T): void;
5
+ delete(el: T): void;
6
+ difference(set: ASet<T>): ASet<T>;
7
+ has(el: T): boolean;
8
+ intersection(set: ASet<T>): ASet<T>;
9
+ isDisjointFrom(set: ASet<T>): boolean;
10
+ isSubsetOf(set: ASet<T>): boolean;
11
+ isSuperset(set: ASet<T>): boolean;
12
+ symmetricDifference(set: ASet<T>): ASet<any>;
13
+ union(set: ASet<T> | Array<T>): ASet<any>;
14
+ }
@@ -0,0 +1 @@
1
+ export declare function download(href: any, name: string): void;
@@ -0,0 +1,18 @@
1
+ export type Listener = (...args: any[]) => any;
2
+ export type TypedEvents = {
3
+ [k in string | symbol]: Listener;
4
+ } & {
5
+ '*': (event: string, ...args: any[]) => any;
6
+ };
7
+ export declare class TypedEmitter<T extends TypedEvents = TypedEvents> {
8
+ private static listeners;
9
+ private listeners;
10
+ static emit(event: any, ...args: any[]): void;
11
+ static off(event: any, listener: Listener): void;
12
+ static on(event: any, listener: Listener): () => void;
13
+ static once(event: any, listener?: Listener): Promise<any>;
14
+ emit<K extends keyof T>(event: K, ...args: Parameters<T[K]>): void;
15
+ off<K extends keyof T = string>(event: K, listener: T[K]): void;
16
+ on<K extends keyof T = string>(event: K, listener: T[K]): () => void;
17
+ once<K extends keyof T = string>(event: K, listener?: T[K]): Promise<any>;
18
+ }
@@ -0,0 +1,35 @@
1
+ export declare class CustomError extends Error {
2
+ static code: number;
3
+ private _code?;
4
+ get code(): number;
5
+ set code(c: number);
6
+ constructor(message?: string, code?: number);
7
+ static from(err: Error): CustomError;
8
+ static instanceof(err: Error): boolean;
9
+ toString(): string;
10
+ }
11
+ export declare class BadRequestError extends CustomError {
12
+ static code: number;
13
+ constructor(message?: string);
14
+ static instanceof(err: Error): boolean;
15
+ }
16
+ export declare class UnauthorizedError extends CustomError {
17
+ static code: number;
18
+ constructor(message?: string);
19
+ static instanceof(err: Error): boolean;
20
+ }
21
+ export declare class ForbiddenError extends CustomError {
22
+ static code: number;
23
+ constructor(message?: string);
24
+ static instanceof(err: Error): boolean;
25
+ }
26
+ export declare class NotFoundError extends CustomError {
27
+ static code: number;
28
+ constructor(message?: string);
29
+ static instanceof(err: Error): boolean;
30
+ }
31
+ export declare class InternalServerError extends CustomError {
32
+ static code: number;
33
+ constructor(message?: string);
34
+ static instanceof(err: Error): boolean;
35
+ }
@@ -0,0 +1,13 @@
1
+ export * from './array';
2
+ export * from './aset';
3
+ export * from './download';
4
+ export * from './emitter';
5
+ export * from './errors';
6
+ export * from './logger';
7
+ export * from './math';
8
+ export * from './misc';
9
+ export * from './objects';
10
+ export * from './promise-progress';
11
+ export * from './string';
12
+ export * from './time';
13
+ export * from './xhr';
@@ -0,0 +1,65 @@
1
+ import { TypedEmitter, TypedEvents } from './emitter';
2
+ export declare const CliEffects: {
3
+ CLEAR: string;
4
+ BRIGHT: string;
5
+ DIM: string;
6
+ UNDERSCORE: string;
7
+ BLINK: string;
8
+ REVERSE: string;
9
+ HIDDEN: string;
10
+ };
11
+ export declare const CliForeground: {
12
+ BLACK: string;
13
+ RED: string;
14
+ GREEN: string;
15
+ YELLOW: string;
16
+ BLUE: string;
17
+ MAGENTA: string;
18
+ CYAN: string;
19
+ LIGHT_GREY: string;
20
+ GREY: string;
21
+ LIGHT_RED: string;
22
+ LIGHT_GREEN: string;
23
+ LIGHT_YELLOW: string;
24
+ LIGHT_BLUE: string;
25
+ LIGHT_MAGENTA: string;
26
+ LIGHT_CYAN: string;
27
+ WHITE: string;
28
+ };
29
+ export declare const CliBackground: {
30
+ BLACK: string;
31
+ RED: string;
32
+ GREEN: string;
33
+ YELLOW: string;
34
+ BLUE: string;
35
+ MAGENTA: string;
36
+ CYAN: string;
37
+ WHITE: string;
38
+ GREY: string;
39
+ };
40
+ export declare enum LOG_LEVEL {
41
+ ERROR = 0,
42
+ WARN = 1,
43
+ INFO = 2,
44
+ LOG = 3,
45
+ DEBUG = 4
46
+ }
47
+ export type LoggerEvents = TypedEvents & {
48
+ 'ERROR': (...args: any[]) => any;
49
+ 'WARN': (...args: any[]) => any;
50
+ 'INFO': (...args: any[]) => any;
51
+ 'LOG': (...args: any[]) => any;
52
+ 'DEBUG': (...args: any[]) => any;
53
+ };
54
+ export declare class Logger extends TypedEmitter<LoggerEvents> {
55
+ readonly namespace?: string | undefined;
56
+ static LOG_LEVEL: LOG_LEVEL;
57
+ constructor(namespace?: string | undefined);
58
+ private pad;
59
+ private format;
60
+ debug(...args: string[]): void;
61
+ log(...args: string[]): void;
62
+ info(...args: string[]): void;
63
+ warn(...args: string[]): void;
64
+ error(...args: string[]): void;
65
+ }
package/dist/math.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Convert decimal number to fraction
3
+ *
4
+ * @example
5
+ * ```js
6
+ * dec2Frac(1.25) // Outputs: "1 1/4"
7
+ * ```
8
+ *
9
+ * @param {number} num Number to convert
10
+ * @return {string} Fraction with remainder
11
+ */
12
+ export declare function dec2Frac(num: number): string;
13
+ /**
14
+ * Convert fraction to decimal number
15
+ *
16
+ * @example
17
+ * ```js
18
+ * fracToDec('1 1/4') // Outputs: 1.25
19
+ * ```
20
+ *
21
+ * @param {string} frac Fraction to convert
22
+ * @return {number} Faction as a decimal
23
+ */
24
+ export declare function fracToDec(frac: string): number;
package/dist/misc.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Convert data into a form encoded format.
3
+ *
4
+ * @param {any} data - data to convert
5
+ * @returns {string} - Ecodeded form data
6
+ */
7
+ export declare function formEncode(data: any): string;
8
+ /**
9
+ * Get profile image from Gravatar
10
+ *
11
+ * @param {string} email Account email address
12
+ * @param {string} def Default image, can be a link or '404', see: https://docs.gravatar.com/general/images/
13
+ * @returns {string} Gravatar URL
14
+ */
15
+ export declare function gravatar(email: string, def?: string): string;
16
+ /** Parts of a URL */
17
+ export type ParsedUrl = {
18
+ protocol?: string;
19
+ subdomain?: string;
20
+ domain: string;
21
+ host: string;
22
+ port?: number;
23
+ path?: string;
24
+ query?: {
25
+ [name: string]: string;
26
+ };
27
+ fragment?: string;
28
+ };
29
+ /**
30
+ *
31
+ * @param {string} url
32
+ * @returns {RegExpExecArray}
33
+ */
34
+ export declare function urlParser(url: string): ParsedUrl;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Removes any null values from an object in-place
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * let test = {a: 0, b: false, c: null, d: 'abc'}
7
+ * console.log(clean(test)); // Output: {a: 0, b: false, d: 'abc'}
8
+ * ```
9
+ *
10
+ * @param {T} obj Object reference that will be cleaned
11
+ * @param undefinedOnly Ignore null values
12
+ * @returns {Partial<T>} Cleaned object
13
+ */
14
+ export declare function clean<T>(obj: T, undefinedOnly?: boolean): Partial<T>;
15
+ /**
16
+ * Create a deep copy of an object (vs. a shallow copy of references)
17
+ *
18
+ * Should be replaced by `structuredClone` once released.
19
+ *
20
+ * @param {T} value Object to copy
21
+ * @returns {T} Type
22
+ */
23
+ export declare function deepCopy<T>(value: T): T;
24
+ /**
25
+ * Get/set a property of an object using dot notation
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * // Get a value
30
+ * const name = dotNotation<string>(person, 'firstName');
31
+ * const familyCarMake = dotNotation(family, 'cars[0].make');
32
+ * // Set a value
33
+ * dotNotation(family, 'cars[0].make', 'toyota');
34
+ * ```
35
+ *
36
+ * @type T Return type
37
+ * @param {Object} obj source object to search
38
+ * @param {string} prop property name (Dot notation & indexing allowed)
39
+ * @param {any} set Set object property to value, omit to fetch value instead
40
+ * @return {T} property value
41
+ */
42
+ export declare function dotNotation<T>(obj: any, prop: string, set: T): T;
43
+ export declare function dotNotation<T>(obj: any, prop: string): T | undefined;
44
+ /**
45
+ * Recursively flatten a nested object, while maintaining key structure.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * const car = {honda: {model: "Civic"}};
50
+ * console.log(flattenObj(car)); //Output {honda.model: "Civic"}
51
+ * ```
52
+ *
53
+ * @param obj - Object to flatten
54
+ * @param parent - Recursively check if key is a parent key or not
55
+ * @param result - Result
56
+ * @returns {object} - Flattened object
57
+ */
58
+ export declare function flattenObj(obj: any, parent?: any, result?: any): any;
59
+ /**
60
+ * Check that an object has the following values
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * const test = {a: 2, b: 2};
65
+ * includes(test, {a: 1}); // true
66
+ * includes(test, {b: 1, c: 3}); // false
67
+ * ```
68
+ *
69
+ * @param target Object to search
70
+ * @param values Criteria to check against
71
+ * @param allowMissing Only check the keys that are available on the target
72
+ * @returns {boolean} Does target include all the values
73
+ */
74
+ export declare function includes(target: any, values: any, allowMissing?: boolean): boolean;
75
+ /**
76
+ * Deep check if two objects are equal
77
+ *
78
+ * @param {any} a - first item to compare
79
+ * @param {any} b - second item to compare
80
+ * @returns {boolean} True if they match
81
+ */
82
+ export declare function isEqual(a: any, b: any): boolean;
83
+ export declare function mixin(target: any, constructors: any[]): void;
84
+ export declare function sanitizedJSON(obj: any, space?: number): any;
@@ -0,0 +1,9 @@
1
+ export type ProgressCallback = (progress: number) => any;
2
+ export declare class PromiseProgress<T> extends Promise<T> {
3
+ private listeners;
4
+ private _progress;
5
+ get progress(): number;
6
+ set progress(p: number);
7
+ constructor(executor: (resolve: (value: T) => any, reject: (reason: any) => void, progress: (progress: number) => any) => void);
8
+ onProgress(callback: ProgressCallback): this;
9
+ }
@@ -0,0 +1,72 @@
1
+ export declare function countChars(text: string, pattern: RegExp): number;
2
+ export declare function createHex(length: number): string;
3
+ export declare function formatPhoneNumber(number: string): string;
4
+ /**
5
+ * Insert a string into another string at a given position
6
+ *
7
+ * @example
8
+ * ```
9
+ * console.log(insertAt('Hello world!', ' glorious', 5);
10
+ * // Output: Hello glorious world!
11
+ * ```
12
+ *
13
+ * @param {string} target - Parent string you want to modify
14
+ * @param {string} str - Value that will be injected to parent
15
+ * @param {number} index - Position to inject string at
16
+ * @returns {string} - New string
17
+ */
18
+ export declare function insertAt(target: string, str: string, index: number): String;
19
+ export declare function pad(text: any, length: number, char: string, start?: boolean): any;
20
+ /**
21
+ * Generate a string of random characters.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const random = randomString();
26
+ * const randomByte = randomString(8, "01")
27
+ * ```
28
+ *
29
+ * @param {number} length - length of generated string
30
+ * @param {string} pool - character pool to generate string from
31
+ * @return {string} generated string
32
+ */
33
+ export declare function randomString(length: number, pool?: string): string;
34
+ /**
35
+ * Generate a random string with fine control over letters, numbers & symbols
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * const randomLetter = randomString(1, true);
40
+ * const randomChar = randomString(1, true, true, true);
41
+ * ```
42
+ *
43
+ * @param {number} length - length of generated string
44
+ * @param {boolean} letters - Add letters to pool
45
+ * @param {boolean} numbers - Add numbers to pool
46
+ * @param {boolean} symbols - Add symbols to pool
47
+ * @return {string} generated string
48
+ */
49
+ export declare function randomStringBuilder(length: number, letters?: boolean, numbers?: boolean, symbols?: boolean): string;
50
+ /**
51
+ * Find all substrings that match a given pattern.
52
+ *
53
+ * Roughly based on `String.prototype.matchAll`.
54
+ *
55
+ * @param {string} value - String to search.
56
+ * @param {RegExp | string} regex - Regular expression to match.
57
+ * @return {RegExpExecArray[]} Found matches.
58
+ */
59
+ export declare function matchAll(value: string, regex: RegExp | string): RegExpExecArray[];
60
+ /**
61
+ * Create MD5 hash using native javascript
62
+ * @param d String to hash
63
+ * @returns {string} Hashed string
64
+ */
65
+ export declare function md5(d: string): string;
66
+ /**
67
+ * Check if email is valid
68
+ *
69
+ * @param {string} email - Target
70
+ * @returns {boolean} - Follows format
71
+ */
72
+ export declare function validateEmail(email: string): boolean;
package/dist/time.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Calculate the number of milliseconds until date/time
3
+ *
4
+ * @param {Date | number} date - Target
5
+ * @returns {number} - Number of milliseconds until target
6
+ */
7
+ export declare function timeUntil(date: Date | number): number;
8
+ /**
9
+ * Use in conjunction with `await` to pause an async script
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * async () => {
14
+ * ...
15
+ * await sleep(1000) // Pause for 1 second
16
+ * ...
17
+ * }
18
+ * ```
19
+ *
20
+ * @param {number} ms - Time to pause for in milliseconds
21
+ * @returns {Promise<unknown>} - Resolves promise when it's time to resume
22
+ */
23
+ export declare function sleep(ms: number): Promise<unknown>;
24
+ export declare function formatDate(date: Date | number | string): string;
package/dist/utils.cjs ADDED
@@ -0,0 +1,2 @@
1
+ (function(c,d){typeof exports=="object"&&typeof module<"u"?d(exports):typeof define=="function"&&define.amd?define(["exports"],d):(c=typeof globalThis<"u"?globalThis:c||self,d(c.utils={}))})(this,function(c){"use strict";var bt=Object.defineProperty;var Rt=(c,d,p)=>d in c?bt(c,d,{enumerable:!0,configurable:!0,writable:!0,value:p}):c[d]=p;var u=(c,d,p)=>(Rt(c,typeof d!="symbol"?d+"":d,p),p);function d(n,e=!1){if(n==null)throw new Error("Cannot clean a NULL value");return Array.isArray(n)?n=n.filter(t=>t!=null):Object.entries(n).forEach(([t,r])=>{(e&&r===void 0||!e&&r==null)&&delete n[t]}),n}function p(n){return JSON.parse(JSON.stringify(n))}function O(n,e,t){if(!(n==null||!e))return e.split(/[.[\]]/g).filter(r=>r.length).reduce((r,o,i,s)=>{if((o[0]=='"'||o[0]=="'")&&(o=o.slice(1,-1)),!(r!=null&&r.hasOwnProperty(o))){if(t==null)return;r[o]={}}return t!==void 0&&i==s.length-1?r[o]=t:r[o]},n)}function v(n,e,t={}){if(typeof n=="object"&&!Array.isArray(n)){for(const r of Object.keys(n)){const o=e?e+"."+r:r;typeof n[r]=="object"?v(n[r],o,t):t[o]=n[r]}return t}}function T(n,e,t=!1){if(n==null)return t;if(Array.isArray(e))return e.findIndex((o,i)=>!T(n[i],e[i],t))==-1;const r=typeof e;return r!=typeof n?!1:r=="object"?Object.keys(e).find(o=>!T(n[o],e[o],t))==null:r=="function"?n.toString()==e.toString():n==e}function A(n,e){const t=typeof n,r=typeof e;return t!="object"||n==null||r!="object"||e==null?t=="function"&&r=="function"?n.toString()==e.toString():n===e:Object.keys(n).length!=Object.keys(e).length?!1:Object.keys(n).every(i=>A(n[i],e[i]))}function z(n,e){e.forEach(t=>{Object.getOwnPropertyNames(t.prototype).forEach(r=>{Object.defineProperty(n.prototype,r,Object.getOwnPropertyDescriptor(t.prototype,r)||Object.create(null))})})}function J(n,e){let t=[];return JSON.parse(JSON.stringify(n,(r,o)=>{if(typeof o=="object"&&o!==null){if(t.includes(o))return;t.push(o)}return o},e))}function V(n,e){return n.indexOf(e)===-1&&n.push(e),n}function K(n,e){return Y([...n.filter(t=>!e.includes(r=>A(t,r))),...e.filter(t=>!n.includes(r=>A(t,r)))])}function Z(n){return function(e,t){const r=O(e,n),o=O(t,n);return typeof r!="string"||typeof o!="string"?1:r.toLowerCase().localeCompare(o.toLowerCase())}}function H(n,e=[]){return n.forEach(t=>Array.isArray(t)?H(t,e):e.push(t)),e}function Q(n,e=!1){return function(t,r){const o=O(t,n),i=O(r,n);return typeof o=="number"&&typeof i=="number"?(e?-1:1)*(o-i):o>i?e?-1:1:o<i?e?1:-1:0}}function X(n,e){return t=>A(t[n],e)}function Y(n){for(let e=n.length-1;e>=0;e--)n.slice(0,e).find(t=>A(t,n[e]))&&n.splice(e,1);return n}function _(n){return Array.isArray(n)?n:[n]}class S extends Array{get size(){return this.length}constructor(e=[]){super(),e!=null&&e.forEach&&e.forEach(t=>this.add(t))}add(e){this.has(e)||this.push(e)}delete(e){const t=this.indexOf(e);t!=-1&&this.slice(t,1)}difference(e){return new S(this.reduce((t,r)=>(e.has(r)||t.push(r),t),[]))}has(e){return this.indexOf(e)!=-1}intersection(e){return new S(this.reduce((t,r)=>(e.has(r)&&t.push(r),t),[]))}isDisjointFrom(e){return this.intersection(e).size==0}isSubsetOf(e){return this.findIndex(t=>!e.has(t))==-1}isSuperset(e){return e.findIndex(t=>!this.has(t))==-1}symmetricDifference(e){return new S([...this.difference(e),...e.difference(this)])}union(e){return new S([...this,...e])}}function tt(n,e){const t=document.createElement("a");t.href=n,t.download=e,document.body.appendChild(t),t.click(),document.body.removeChild(t)}class L{constructor(){u(this,"listeners",{})}static emit(e,...t){(this.listeners["*"]||[]).forEach(r=>r(e,...t)),(this.listeners[e.toString()]||[]).forEach(r=>r(...t))}static off(e,t){const r=e.toString();this.listeners[r]=(this.listeners[r]||[]).filter(o=>o===t)}static on(e,t){var o;const r=e.toString();return this.listeners[r]||(this.listeners[r]=[]),(o=this.listeners[r])==null||o.push(t),()=>this.off(e,t)}static once(e,t){return new Promise(r=>{const o=this.on(e,(...i)=>{r(i.length==1?i[0]:i),t&&t(...i),o()})})}emit(e,...t){(this.listeners["*"]||[]).forEach(r=>r(e,...t)),(this.listeners[e]||[]).forEach(r=>r(...t))}off(e,t){this.listeners[e]=(this.listeners[e]||[]).filter(r=>r===t)}on(e,t){var r;return this.listeners[e]||(this.listeners[e]=[]),(r=this.listeners[e])==null||r.push(t),()=>this.off(e,t)}once(e,t){return new Promise(r=>{const o=this.on(e,(...i)=>{r(i.length==1?i[0]:i),t&&t(...i),o()})})}}u(L,"listeners",{});class w extends Error{constructor(t,r){super(t);u(this,"_code");r!=null&&(this._code=r)}get code(){return this._code||this.constructor.code}set code(t){this._code=t}static from(t){const r=Number(t.statusCode)??Number(t.code),o=new this(t.message||t.toString());return Object.assign(o,{stack:t.stack,...t,code:r??void 0})}static instanceof(t){return t.constructor.code!=null}toString(){return this.message||super.toString()}}u(w,"code",500);class I extends w{constructor(e="Bad Request"){super(e)}static instanceof(e){return e.constructor.code==this.code}}u(I,"code",400);class D extends w{constructor(e="Unauthorized"){super(e)}static instanceof(e){return e.constructor.code==this.code}}u(D,"code",401);class $ extends w{constructor(e="Forbidden"){super(e)}static instanceof(e){return e.constructor.code==this.code}}u($,"code",403);class k extends w{constructor(e="Not Found"){super(e)}static instanceof(e){return e.constructor.code==this.code}}u(k,"code",404);class P extends w{constructor(e="Internal Server Error"){super(e)}static instanceof(e){return e.constructor.code==this.code}}u(P,"code",500);const C={CLEAR:"\x1B[0m",BRIGHT:"\x1B[1m",DIM:"\x1B[2m",UNDERSCORE:"\x1B[4m",BLINK:"\x1B[5m",REVERSE:"\x1B[7m",HIDDEN:"\x1B[8m"},N={BLACK:"\x1B[30m",RED:"\x1B[31m",GREEN:"\x1B[32m",YELLOW:"\x1B[33m",BLUE:"\x1B[34m",MAGENTA:"\x1B[35m",CYAN:"\x1B[36m",LIGHT_GREY:"\x1B[37m",GREY:"\x1B[90m",LIGHT_RED:"\x1B[91m",LIGHT_GREEN:"\x1B[92m",LIGHT_YELLOW:"\x1B[93m",LIGHT_BLUE:"\x1B[94m",LIGHT_MAGENTA:"\x1B[95m",LIGHT_CYAN:"\x1B[96m",WHITE:"\x1B[97m"},et={BLACK:"\x1B[40m",RED:"\x1B[41m",GREEN:"\x1B[42m",YELLOW:"\x1B[43m",BLUE:"\x1B[44m",MAGENTA:"\x1B[45m",CYAN:"\x1B[46m",WHITE:"\x1B[47m",GREY:"\x1B[100m"};var W=(n=>(n[n.ERROR=0]="ERROR",n[n.WARN=1]="WARN",n[n.INFO=2]="INFO",n[n.LOG=3]="LOG",n[n.DEBUG=4]="DEBUG",n))(W||{});const g=class g extends L{constructor(e){super(),this.namespace=e}pad(e,t,r,o=!1){const i=e.toString(),s=t-i.length;if(s<=0)return i;const y=Array(~~(s/r.length)).fill(r).join("");return o?i+y:y+i}format(...e){const t=new Date;return`${`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()} ${this.pad(t.getHours().toString(),2,"0")}:${this.pad(t.getMinutes().toString(),2,"0")}:${this.pad(t.getSeconds().toString(),2,"0")}.${this.pad(t.getMilliseconds().toString(),3,"0",!0)}`}${this.namespace?` [${this.namespace}]`:""} ${e.join(" ")}`}debug(...e){if(g.LOG_LEVEL<4)return;const t=this.format(...e);g.emit(4,t),console.debug(N.LIGHT_GREY+t+C.CLEAR)}log(...e){if(g.LOG_LEVEL<3)return;const t=this.format(...e);g.emit(3,t),console.log(C.CLEAR+t)}info(...e){if(g.LOG_LEVEL<2)return;const t=this.format(...e);g.emit(2,t),console.info(N.BLUE+t+C.CLEAR)}warn(...e){if(g.LOG_LEVEL<1)return;const t=this.format(...e);g.emit(1,t),console.warn(N.YELLOW+t+C.CLEAR)}error(...e){if(g.LOG_LEVEL<0)return;const t=this.format(...e);g.emit(0,t),console.error(N.RED+t+C.CLEAR)}};u(g,"LOG_LEVEL",4);let G=g;function nt(n){const e=(y,m)=>m<1e-7?y:e(m,~~(y%m)),t=n.toString().length-2;let r=Math.pow(10,t),o=n*r;const i=e(o,r);o=~~(o/i),r=~~(r/i);const s=~~(o/r);return o-=s*r,`${s?s+" ":""}${~~o}/${~~r}`}function rt(n){let e=n.split(" ");const t=e.length==2?Number(e[0]):0;return e=e.pop().split("/"),t+Number(e[0])/Number(e[1])}function ot(n,e){return n.length-n.replaceAll(e,"").length}function it(n){return Array(n).fill(null).map(()=>Math.round(Math.random()*15).toString(16)).join("")}const j="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",U="0123456789",M="~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/",st=j+U+M;function ct(n){const e=/(\+?1)?.*?(\d{3}).*?(\d{3}).*?(\d{4})/g.exec(n);if(!e)throw new Error(`Number cannot be parsed: ${n}`);return`${e[1]??""} (${e[2]}) ${e[3]}-${e[4]}`.trim()}function ut(n,e,t){return`${n.slice(0,t)}${e}${n.slice(t+1)}`}function at(n,e,t,r=!0){const o=n.toString(),i=e-o.length;if(i<=0)return o;const s=Array(~~(i/t.length)).fill(t).join("");return r?s+o:o+s}function lt(n,e=st){return Array(n).fill(null).map(()=>{const t=~~(Math.random()*e.length);return e[t]}).join("")}function ht(n,e=!1,t=!1,r=!1){if(!e&&!t&&!r)throw new Error("Must enable at least one: letters, numbers, symbols");return Array(n).fill(null).map(()=>{let o;do{const i=~~(Math.random()*3);e&&i==0?o=j[~~(Math.random()*j.length)]:t&&i==1?o=U[~~(Math.random()*U.length)]:r&&i==2&&(o=M[~~(Math.random()*M.length)])}while(!o);return o}).join("")}function ft(n,e){if(typeof e=="string"&&(e=new RegExp(e,"g")),!e.global)throw new TypeError("Regular expression must be global.");let t=[],r;for(;(r=e.exec(n))!==null;)t.push(r);return t}function x(n){var e=dt(yt(Et(gt(n),8*n.length)));return e.toLowerCase()}function dt(n){for(var e,t="0123456789ABCDEF",r="",o=0;o<n.length;o++)e=n.charCodeAt(o),r+=t.charAt(e>>>4&15)+t.charAt(15&e);return r}function gt(n){for(var e=Array(n.length>>2),t=0;t<e.length;t++)e[t]=0;for(t=0;t<8*n.length;t+=8)e[t>>5]|=(255&n.charCodeAt(t/8))<<t%32;return e}function yt(n){for(var e="",t=0;t<32*n.length;t+=8)e+=String.fromCharCode(n[t>>5]>>>t%32&255);return e}function Et(n,e){n[e>>5]|=128<<e%32,n[14+(e+64>>>9<<4)]=e;for(var t=1732584193,r=-271733879,o=-1732584194,i=271733878,s=0;s<n.length;s+=16){var y=t,m=r,F=o,q=i;r=f(r=f(r=f(r=f(r=h(r=h(r=h(r=h(r=l(r=l(r=l(r=l(r=a(r=a(r=a(r=a(r,o=a(o,i=a(i,t=a(t,r,o,i,n[s+0],7,-680876936),r,o,n[s+1],12,-389564586),t,r,n[s+2],17,606105819),i,t,n[s+3],22,-1044525330),o=a(o,i=a(i,t=a(t,r,o,i,n[s+4],7,-176418897),r,o,n[s+5],12,1200080426),t,r,n[s+6],17,-1473231341),i,t,n[s+7],22,-45705983),o=a(o,i=a(i,t=a(t,r,o,i,n[s+8],7,1770035416),r,o,n[s+9],12,-1958414417),t,r,n[s+10],17,-42063),i,t,n[s+11],22,-1990404162),o=a(o,i=a(i,t=a(t,r,o,i,n[s+12],7,1804603682),r,o,n[s+13],12,-40341101),t,r,n[s+14],17,-1502002290),i,t,n[s+15],22,1236535329),o=l(o,i=l(i,t=l(t,r,o,i,n[s+1],5,-165796510),r,o,n[s+6],9,-1069501632),t,r,n[s+11],14,643717713),i,t,n[s+0],20,-373897302),o=l(o,i=l(i,t=l(t,r,o,i,n[s+5],5,-701558691),r,o,n[s+10],9,38016083),t,r,n[s+15],14,-660478335),i,t,n[s+4],20,-405537848),o=l(o,i=l(i,t=l(t,r,o,i,n[s+9],5,568446438),r,o,n[s+14],9,-1019803690),t,r,n[s+3],14,-187363961),i,t,n[s+8],20,1163531501),o=l(o,i=l(i,t=l(t,r,o,i,n[s+13],5,-1444681467),r,o,n[s+2],9,-51403784),t,r,n[s+7],14,1735328473),i,t,n[s+12],20,-1926607734),o=h(o,i=h(i,t=h(t,r,o,i,n[s+5],4,-378558),r,o,n[s+8],11,-2022574463),t,r,n[s+11],16,1839030562),i,t,n[s+14],23,-35309556),o=h(o,i=h(i,t=h(t,r,o,i,n[s+1],4,-1530992060),r,o,n[s+4],11,1272893353),t,r,n[s+7],16,-155497632),i,t,n[s+10],23,-1094730640),o=h(o,i=h(i,t=h(t,r,o,i,n[s+13],4,681279174),r,o,n[s+0],11,-358537222),t,r,n[s+3],16,-722521979),i,t,n[s+6],23,76029189),o=h(o,i=h(i,t=h(t,r,o,i,n[s+9],4,-640364487),r,o,n[s+12],11,-421815835),t,r,n[s+15],16,530742520),i,t,n[s+2],23,-995338651),o=f(o,i=f(i,t=f(t,r,o,i,n[s+0],6,-198630844),r,o,n[s+7],10,1126891415),t,r,n[s+14],15,-1416354905),i,t,n[s+5],21,-57434055),o=f(o,i=f(i,t=f(t,r,o,i,n[s+12],6,1700485571),r,o,n[s+3],10,-1894986606),t,r,n[s+10],15,-1051523),i,t,n[s+1],21,-2054922799),o=f(o,i=f(i,t=f(t,r,o,i,n[s+8],6,1873313359),r,o,n[s+15],10,-30611744),t,r,n[s+6],15,-1560198380),i,t,n[s+13],21,1309151649),o=f(o,i=f(i,t=f(t,r,o,i,n[s+4],6,-145523070),r,o,n[s+11],10,-1120210379),t,r,n[s+2],15,718787259),i,t,n[s+9],21,-343485551),t=B(t,y),r=B(r,m),o=B(o,F),i=B(i,q)}return Array(t,r,o,i)}function b(n,e,t,r,o,i){return B(mt(B(B(e,n),B(r,i)),o),t)}function a(n,e,t,r,o,i,s){return b(e&t|~e&r,n,e,o,i,s)}function l(n,e,t,r,o,i,s){return b(e&r|t&~r,n,e,o,i,s)}function h(n,e,t,r,o,i,s){return b(e^t^r,n,e,o,i,s)}function f(n,e,t,r,o,i,s){return b(t^(e|~r),n,e,o,i,s)}function B(n,e){var t=(65535&n)+(65535&e);return(n>>16)+(e>>16)+(t>>16)<<16|65535&t}function mt(n,e){return n<<e|n>>>32-e}function wt(n){return/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(n)}function Bt(n){return Object.entries(n).map(([e,t])=>encodeURIComponent(e)+"="+encodeURIComponent(t)).join("&")}function pt(n,e="mp"){return n?`https://www.gravatar.com/avatar/${x(n)}?d=${e}`:""}function At(n){const e=new RegExp("(?:(?<protocol>[\\w\\d]+)\\:\\/\\/)?(?:(?<user>.+)\\@)?(?<host>(?<domain>[^:\\/\\?#@\\n]+)(?:\\:(?<port>\\d*))?)(?<path>\\/.*?)?(?:\\?(?<query>.*?))?(?:#(?<fragment>.*?))?$","gm").exec(n),t=(e==null?void 0:e.groups)??{},r=t.domain.split(".");if(t.port!=null&&(t.port=Number(t.port)),r.length>2&&(t.domain=r.splice(-2,2).join("."),t.subdomain=r.join(".")),t.query){const o=t.query.split("&"),i={};o.forEach(s=>{const[y,m]=s.split("=");i[y]=m}),t.query=i}return t}class St extends Promise{constructor(t){super((r,o)=>t(i=>r(i),i=>o(i),i=>this.progress=i));u(this,"listeners",[]);u(this,"_progress",0)}get progress(){return this._progress}set progress(t){t!=this._progress&&(this._progress=t,this.listeners.forEach(r=>r(t)))}onProgress(t){return this.listeners.push(t),this}}function Ct(n){return(n instanceof Date?n.getTime():n)-new Date().getTime()}function Ot(n){return new Promise(e=>setTimeout(e,n))}function Nt(n){const e=n instanceof Date?n:new Date(n);return new Intl.DateTimeFormat("en-us",{weekday:"long",month:"short",day:"numeric",hour:"numeric",minute:"numeric",hour12:!0}).format(e)}const E=class E{constructor(e={}){u(this,"interceptors",{});u(this,"headers",{});this.opts=e,this.headers=e.headers||{},e.interceptors&&e.interceptors.forEach(t=>E.addInterceptor(t))}static addInterceptor(e){const t=Object.keys(E.interceptors).length.toString();return E.interceptors[t]=e,()=>{E.interceptors[t]=null}}addInterceptor(e){const t=Object.keys(this.interceptors).length.toString();return this.interceptors[t]=e,()=>{this.interceptors[t]=null}}async request(e={}){var o,i;if(!this.opts.url&&!e.url)throw new Error("URL needs to be set");const t=((o=e.url)!=null&&o.startsWith("http")?e.url:(this.opts.url||"")+(e.url||"")).replace(/([^:]\/)\/+/g,"$1"),r=d({"Content-Type":e.body&&!(e.body instanceof FormData)?"application/json":void 0,...E.headers,...this.headers,...e.headers});return fetch(t,{headers:r,method:e.method||(e.body?"POST":"GET"),body:(i=r["Content-Type"])!=null&&i.startsWith("application/json")&&e.body?JSON.stringify(e.body):e.body}).then(async s=>{var y,m;for(let F of[...Object.values(E.interceptors),...Object.values(this.interceptors)])await new Promise(q=>F(s,()=>q()));if(!s.ok)throw new Error(s.statusText);return!e.skipConverting&&((y=s.headers.get("Content-Type"))!=null&&y.startsWith("application/json"))?await s.json():!e.skipConverting&&((m=s.headers.get("Content-Type"))!=null&&m.startsWith("text/plain"))?await s.text():s})}};u(E,"interceptors",{}),u(E,"headers",{});let R=E;R.addInterceptor((n,e)=>{const t=r=>{var o,i;return((o=r.error)==null?void 0:o.message)||((i=r.reason)==null?void 0:i.message)||r.message||r.statusText||r.toString()};if(n.status==200)return e();throw n.status==400?new I(t(n)):n.status==401?new D(t(n)):n.status==403?new $(t(n)):n.status==404?new k(t(n)):n.status==500?new P(t(n)):new w(t(n),n.status)}),c.ASet=S,c.BadRequestError=I,c.CliBackground=et,c.CliEffects=C,c.CliForeground=N,c.CustomError=w,c.ForbiddenError=$,c.InternalServerError=P,c.LOG_LEVEL=W,c.Logger=G,c.NotFoundError=k,c.PromiseProgress=St,c.TypedEmitter=L,c.UnauthorizedError=D,c.XHR=R,c.addUnique=V,c.arrayDiff=K,c.caseInsensitiveSort=Z,c.clean=d,c.countChars=ot,c.createHex=it,c.dec2Frac=nt,c.deepCopy=p,c.dotNotation=O,c.download=tt,c.findByProp=X,c.flattenArr=H,c.flattenObj=v,c.formEncode=Bt,c.formatDate=Nt,c.formatPhoneNumber=ct,c.fracToDec=rt,c.gravatar=pt,c.includes=T,c.insertAt=ut,c.isEqual=A,c.makeArray=_,c.makeUnique=Y,c.matchAll=ft,c.md5=x,c.mixin=z,c.pad=at,c.randomString=lt,c.randomStringBuilder=ht,c.sanitizedJSON=J,c.sleep=Ot,c.sortByProp=Q,c.timeUntil=Ct,c.urlParser=At,c.validateEmail=wt,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
2
+ //# sourceMappingURL=utils.cjs.map