web-utils-kit 1.0.16 → 1.1.1
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.
- package/README.md +49 -1
- package/dist/index.d.ts +4 -6
- package/dist/index.js +1 -1
- package/dist/shared/errors.d.ts +3 -3
- package/dist/shared/errors.js +1 -1
- package/dist/shared/types.d.ts +8 -2
- package/dist/transformers/consts.d.ts +12 -5
- package/dist/transformers/consts.js +1 -1
- package/dist/transformers/index.d.ts +61 -39
- package/dist/transformers/index.js +1 -1
- package/dist/transformers/types.d.ts +20 -11
- package/dist/transformers/utils.d.ts +23 -11
- package/dist/transformers/utils.js +1 -1
- package/dist/transformers/validations.d.ts +32 -11
- package/dist/transformers/validations.js +1 -1
- package/dist/utils/index.d.ts +46 -47
- package/dist/utils/index.js +1 -1
- package/dist/utils/transformers.d.ts +6 -7
- package/dist/utils/transformers.js +1 -1
- package/dist/utils/types.d.ts +2 -3
- package/dist/utils/utils.d.ts +5 -6
- package/dist/utils/utils.js +1 -1
- package/dist/utils/validations.d.ts +4 -5
- package/dist/utils/validations.js +1 -1
- package/dist/validations/index.d.ts +67 -67
- package/dist/validations/index.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -60,10 +60,12 @@ await res.json();
|
|
|
60
60
|
```typescript
|
|
61
61
|
import { isStringValid } from 'web-utils-kit';
|
|
62
62
|
|
|
63
|
-
isStringValid(''); // true
|
|
63
|
+
isStringValid('Hello world!'); // true
|
|
64
64
|
isStringValid('', 1, 5); // false
|
|
65
65
|
isStringValid('abcde', 1, 5); // true
|
|
66
66
|
isStringValid('abcdef', 1, 5); // false
|
|
67
|
+
isStringValid(' '); // false
|
|
68
|
+
isStringValid(' ', undefined, undefined, false); // true
|
|
67
69
|
```
|
|
68
70
|
<br/>
|
|
69
71
|
</details>
|
|
@@ -496,6 +498,21 @@ await res.json();
|
|
|
496
498
|
<br/>
|
|
497
499
|
</details>
|
|
498
500
|
|
|
501
|
+
<details>
|
|
502
|
+
<summary><code>toMS</code></summary>
|
|
503
|
+
<br/>
|
|
504
|
+
|
|
505
|
+
Converts a time string into milliseconds. The time string should be in the format of `"{value} {unit}"`, where the **value** is a number and the **unit** can be milliseconds, seconds, minutes, hours, days, weeks, months, or years. For example: `"2 days"`, `"5 minutes"`, `"2 hours"`.
|
|
506
|
+
|
|
507
|
+
```typescript
|
|
508
|
+
import { toMS } from 'web-utils-kit';
|
|
509
|
+
|
|
510
|
+
toMS('53 years'); // 1672552800000
|
|
511
|
+
toMS('53 days'); // 4579200000
|
|
512
|
+
```
|
|
513
|
+
<br/>
|
|
514
|
+
</details>
|
|
515
|
+
|
|
499
516
|
<details>
|
|
500
517
|
<summary><code>stringifyJSON</code></summary>
|
|
501
518
|
<br/>
|
|
@@ -940,6 +957,37 @@ await res.json();
|
|
|
940
957
|
<br/>
|
|
941
958
|
</details>
|
|
942
959
|
|
|
960
|
+
<details>
|
|
961
|
+
<summary><code>ITimeString</code></summary>
|
|
962
|
+
<br/>
|
|
963
|
+
|
|
964
|
+
A duration string composed of a numeric value followed by a supported time unit, with or without a space.
|
|
965
|
+
|
|
966
|
+
```typescript
|
|
967
|
+
type IYears = 'years' | 'year';
|
|
968
|
+
type IMonths = 'months' | 'month';
|
|
969
|
+
type IWeeks = 'weeks' | 'week';
|
|
970
|
+
type IDays = 'days' | 'day';
|
|
971
|
+
type IHours = 'hours' | 'hour';
|
|
972
|
+
type IMinutes = 'minutes' | 'minute';
|
|
973
|
+
type ISeconds = 'seconds' | 'second';
|
|
974
|
+
type IMilliseconds = 'milliseconds' | 'millisecond';
|
|
975
|
+
|
|
976
|
+
export type IUnit =
|
|
977
|
+
| IYears
|
|
978
|
+
| IMonths
|
|
979
|
+
| IWeeks
|
|
980
|
+
| IDays
|
|
981
|
+
| IHours
|
|
982
|
+
| IMinutes
|
|
983
|
+
| ISeconds
|
|
984
|
+
| IMilliseconds;
|
|
985
|
+
|
|
986
|
+
export type ITimeString = `${number} ${IUnit}`;
|
|
987
|
+
```
|
|
988
|
+
<br/>
|
|
989
|
+
</details>
|
|
990
|
+
|
|
943
991
|
<br/>
|
|
944
992
|
|
|
945
993
|
## Built With
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import { IUUIDVersion } from './shared/types.js';
|
|
1
|
+
import type { IJSONValue, IUUIDVersion } from './shared/types.js';
|
|
2
2
|
import { isStringValid, isNumberValid, isIntegerValid, isTimestampValid, isObjectValid, isArrayValid, isEmailValid, isSlugValid, isPasswordValid, isOTPSecretValid, isOTPTokenValid, isJWTValid, isAuthorizationHeaderValid, isSemverValid, isURLValid, isUUIDValid } from './validations/index.js';
|
|
3
|
-
import { INumberFormatConfig, IDateTemplate } from './transformers/
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
import { generateUUID, generateRandomString, generateRandomFloat, generateRandomInteger, generateSequence, sortPrimitives, sortRecords, shuffleArray, pickProps, omitProps, filterByQuery, delay, retryAsyncFunction } from './utils/index.js';
|
|
7
|
-
export { type IUUIDVersion, isStringValid, isNumberValid, isIntegerValid, isTimestampValid, isObjectValid, isArrayValid, isEmailValid, isSlugValid, isPasswordValid, isOTPSecretValid, isOTPTokenValid, isJWTValid, isAuthorizationHeaderValid, isSemverValid, isURLValid, isUUIDValid, type INumberFormatConfig, type IDateTemplate, prettifyNumber, prettifyDate, prettifyFileSize, prettifyBadgeCount, capitalizeFirst, toTitleCase, toSlug, truncateText, maskMiddle, applySubstitutions, stringifyJSON, stringifyJSONDeterministically, parseJSON, createDeepClone, pruneJSON, type ISortDirection, type IFilterByQueryOptions, generateUUID, generateRandomString, generateRandomFloat, generateRandomInteger, generateSequence, sortPrimitives, sortRecords, shuffleArray, pickProps, omitProps, filterByQuery, delay, retryAsyncFunction, };
|
|
3
|
+
import { type INumberFormatConfig, type IDateTemplate, type ITimeString, prettifyNumber, prettifyDate, prettifyFileSize, prettifyBadgeCount, capitalizeFirst, toTitleCase, toSlug, truncateText, maskMiddle, applySubstitutions, toMS, stringifyJSON, stringifyJSONDeterministically, parseJSON, createDeepClone, pruneJSON } from './transformers/index.js';
|
|
4
|
+
import { type ISortDirection, type IFilterByQueryOptions, generateUUID, generateRandomString, generateRandomFloat, generateRandomInteger, generateSequence, sortPrimitives, sortRecords, shuffleArray, pickProps, omitProps, filterByQuery, delay, retryAsyncFunction } from './utils/index.js';
|
|
5
|
+
export { type IJSONValue, type IUUIDVersion, isStringValid, isNumberValid, isIntegerValid, isTimestampValid, isObjectValid, isArrayValid, isEmailValid, isSlugValid, isPasswordValid, isOTPSecretValid, isOTPTokenValid, isJWTValid, isAuthorizationHeaderValid, isSemverValid, isURLValid, isUUIDValid, type INumberFormatConfig, type IDateTemplate, type ITimeString, prettifyNumber, prettifyDate, prettifyFileSize, prettifyBadgeCount, capitalizeFirst, toTitleCase, toSlug, truncateText, maskMiddle, applySubstitutions, toMS, stringifyJSON, stringifyJSONDeterministically, parseJSON, createDeepClone, pruneJSON, type ISortDirection, type IFilterByQueryOptions, generateUUID, generateRandomString, generateRandomFloat, generateRandomInteger, generateSequence, sortPrimitives, sortRecords, shuffleArray, pickProps, omitProps, filterByQuery, delay, retryAsyncFunction, };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isStringValid,isNumberValid,isIntegerValid,isTimestampValid,isObjectValid,isArrayValid,isEmailValid,isSlugValid,isPasswordValid,isOTPSecretValid,isOTPTokenValid,isJWTValid,isAuthorizationHeaderValid,isSemverValid,isURLValid,isUUIDValid}from"./validations/index.js";import{prettifyNumber,prettifyDate,prettifyFileSize,prettifyBadgeCount,capitalizeFirst,toTitleCase,toSlug,truncateText,maskMiddle,applySubstitutions,stringifyJSON,stringifyJSONDeterministically,parseJSON,createDeepClone,pruneJSON}from"./transformers/index.js";import{generateUUID,generateRandomString,generateRandomFloat,generateRandomInteger,generateSequence,sortPrimitives,sortRecords,shuffleArray,pickProps,omitProps,filterByQuery,delay,retryAsyncFunction}from"./utils/index.js";export{isStringValid,isNumberValid,isIntegerValid,isTimestampValid,isObjectValid,isArrayValid,isEmailValid,isSlugValid,isPasswordValid,isOTPSecretValid,isOTPTokenValid,isJWTValid,isAuthorizationHeaderValid,isSemverValid,isURLValid,isUUIDValid,prettifyNumber,prettifyDate,prettifyFileSize,prettifyBadgeCount,capitalizeFirst,toTitleCase,toSlug,truncateText,maskMiddle,applySubstitutions,stringifyJSON,stringifyJSONDeterministically,parseJSON,createDeepClone,pruneJSON,generateUUID,generateRandomString,generateRandomFloat,generateRandomInteger,generateSequence,sortPrimitives,sortRecords,shuffleArray,pickProps,omitProps,filterByQuery,delay,retryAsyncFunction};
|
|
1
|
+
import{isStringValid,isNumberValid,isIntegerValid,isTimestampValid,isObjectValid,isArrayValid,isEmailValid,isSlugValid,isPasswordValid,isOTPSecretValid,isOTPTokenValid,isJWTValid,isAuthorizationHeaderValid,isSemverValid,isURLValid,isUUIDValid}from"./validations/index.js";import{prettifyNumber,prettifyDate,prettifyFileSize,prettifyBadgeCount,capitalizeFirst,toTitleCase,toSlug,truncateText,maskMiddle,applySubstitutions,toMS,stringifyJSON,stringifyJSONDeterministically,parseJSON,createDeepClone,pruneJSON}from"./transformers/index.js";import{generateUUID,generateRandomString,generateRandomFloat,generateRandomInteger,generateSequence,sortPrimitives,sortRecords,shuffleArray,pickProps,omitProps,filterByQuery,delay,retryAsyncFunction}from"./utils/index.js";export{isStringValid,isNumberValid,isIntegerValid,isTimestampValid,isObjectValid,isArrayValid,isEmailValid,isSlugValid,isPasswordValid,isOTPSecretValid,isOTPTokenValid,isJWTValid,isAuthorizationHeaderValid,isSemverValid,isURLValid,isUUIDValid,prettifyNumber,prettifyDate,prettifyFileSize,prettifyBadgeCount,capitalizeFirst,toTitleCase,toSlug,truncateText,maskMiddle,applySubstitutions,toMS,stringifyJSON,stringifyJSONDeterministically,parseJSON,createDeepClone,pruneJSON,generateUUID,generateRandomString,generateRandomFloat,generateRandomInteger,generateSequence,sortPrimitives,sortRecords,shuffleArray,pickProps,omitProps,filterByQuery,delay,retryAsyncFunction};
|
package/dist/shared/errors.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
type IErrorCode = 'MIXED_OR_UNSUPPORTED_DATA_TYPES' | 'UNSUPPORTED_DATA_TYPE' | 'INVALID_OR_EMPTY_ARRAY' | 'INVALID_OR_EMPTY_OBJECT' | 'UNABLE_TO_SERIALIZE_JSON' | 'UNABLE_TO_DESERIALIZE_JSON' | 'UNABLE_TO_CREATE_DEEP_CLONE' | 'INVALID_BATCH_SIZE';
|
|
2
|
-
declare const ERRORS: {
|
|
1
|
+
type IErrorCode = 'MIXED_OR_UNSUPPORTED_DATA_TYPES' | 'UNSUPPORTED_DATA_TYPE' | 'INVALID_OR_EMPTY_ARRAY' | 'INVALID_OR_EMPTY_OBJECT' | 'UNABLE_TO_SERIALIZE_JSON' | 'UNABLE_TO_DESERIALIZE_JSON' | 'UNABLE_TO_CREATE_DEEP_CLONE' | 'INVALID_BATCH_SIZE' | 'UNABLE_TO_SLUGIFY_STRING' | 'INVALID_TIME_STRING';
|
|
2
|
+
export declare const ERRORS: {
|
|
3
3
|
[key in IErrorCode]: IErrorCode;
|
|
4
4
|
};
|
|
5
|
-
export {
|
|
5
|
+
export {};
|
package/dist/shared/errors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const ERRORS={MIXED_OR_UNSUPPORTED_DATA_TYPES:"MIXED_OR_UNSUPPORTED_DATA_TYPES",UNSUPPORTED_DATA_TYPE:"UNSUPPORTED_DATA_TYPE",INVALID_OR_EMPTY_ARRAY:"INVALID_OR_EMPTY_ARRAY",INVALID_OR_EMPTY_OBJECT:"INVALID_OR_EMPTY_OBJECT",UNABLE_TO_SERIALIZE_JSON:"UNABLE_TO_SERIALIZE_JSON",UNABLE_TO_DESERIALIZE_JSON:"UNABLE_TO_DESERIALIZE_JSON",UNABLE_TO_CREATE_DEEP_CLONE:"UNABLE_TO_CREATE_DEEP_CLONE",INVALID_BATCH_SIZE:"INVALID_BATCH_SIZE"};
|
|
1
|
+
export const ERRORS={MIXED_OR_UNSUPPORTED_DATA_TYPES:"MIXED_OR_UNSUPPORTED_DATA_TYPES",UNSUPPORTED_DATA_TYPE:"UNSUPPORTED_DATA_TYPE",INVALID_OR_EMPTY_ARRAY:"INVALID_OR_EMPTY_ARRAY",INVALID_OR_EMPTY_OBJECT:"INVALID_OR_EMPTY_OBJECT",UNABLE_TO_SERIALIZE_JSON:"UNABLE_TO_SERIALIZE_JSON",UNABLE_TO_DESERIALIZE_JSON:"UNABLE_TO_DESERIALIZE_JSON",UNABLE_TO_CREATE_DEEP_CLONE:"UNABLE_TO_CREATE_DEEP_CLONE",INVALID_BATCH_SIZE:"INVALID_BATCH_SIZE",UNABLE_TO_SLUGIFY_STRING:"UNABLE_TO_SLUGIFY_STRING",INVALID_TIME_STRING:"INVALID_TIME_STRING"};
|
package/dist/shared/types.d.ts
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON Value
|
|
3
|
+
* A value that can be represented in JSON format.
|
|
4
|
+
*/
|
|
5
|
+
export type IJSONValue = string | number | boolean | null | IJSONValue[] | {
|
|
6
|
+
[key: string]: IJSONValue;
|
|
7
|
+
};
|
|
1
8
|
/**
|
|
2
9
|
* UUID Version
|
|
3
10
|
* The UUID versions supported by this library.
|
|
4
11
|
*/
|
|
5
|
-
type IUUIDVersion = 4 | 7;
|
|
6
|
-
export type { IUUIDVersion };
|
|
12
|
+
export type IUUIDVersion = 4 | 7;
|
|
@@ -1,5 +1,12 @@
|
|
|
1
|
-
import { IDateTemplateConfigs } from './types.js';
|
|
2
|
-
declare const FILE_SIZE_THRESHOLD: number;
|
|
3
|
-
declare const FILE_SIZE_UNITS: string[];
|
|
4
|
-
declare const DATE_TEMPLATE_CONFIGS: IDateTemplateConfigs;
|
|
5
|
-
export
|
|
1
|
+
import { IDateTemplateConfigs, IUnit } from './types.js';
|
|
2
|
+
export declare const FILE_SIZE_THRESHOLD: number;
|
|
3
|
+
export declare const FILE_SIZE_UNITS: string[];
|
|
4
|
+
export declare const DATE_TEMPLATE_CONFIGS: IDateTemplateConfigs;
|
|
5
|
+
export declare const TIME_STRING_UNITS: IUnit[];
|
|
6
|
+
export declare const ONE_SECOND_IN_MILLISECONDS = 1000;
|
|
7
|
+
export declare const ONE_MINUTE_IN_MILLISECONDS: number;
|
|
8
|
+
export declare const ONE_HOUR_IN_MILLISECONDS: number;
|
|
9
|
+
export declare const ONE_DAY_IN_MILLISECONDS: number;
|
|
10
|
+
export declare const ONE_WEEK_IN_MILLISECONDS: number;
|
|
11
|
+
export declare const ONE_YEAR_IN_MILLISECONDS: number;
|
|
12
|
+
export declare const ONE_MONTH_IN_MILLISECONDS: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const FILE_SIZE_THRESHOLD=1024
|
|
1
|
+
export const FILE_SIZE_THRESHOLD=1024;export const FILE_SIZE_UNITS=["kB","MB","GB","TB","PB","EB","ZB","YB"];export const DATE_TEMPLATE_CONFIGS={"date-short":{day:"2-digit",month:"2-digit",year:"numeric"},"date-medium":{day:"numeric",month:"long",year:"numeric"},"date-long":{weekday:"long",day:"numeric",month:"long",year:"numeric"},"time-short":{hour:"2-digit",minute:"2-digit"},"time-medium":{hour:"2-digit",minute:"2-digit",second:"2-digit"},"datetime-short":{day:"numeric",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"},"datetime-medium":{day:"numeric",month:"long",year:"numeric",hour:"2-digit",minute:"2-digit"},"datetime-long":{weekday:"long",day:"numeric",month:"long",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}};export const TIME_STRING_UNITS=["seconds","second","minutes","minute","hours","hour","days","day","weeks","week","months","month","years","year"];export const ONE_SECOND_IN_MILLISECONDS=1e3;export const ONE_MINUTE_IN_MILLISECONDS=6e4;export const ONE_HOUR_IN_MILLISECONDS=36e5;export const ONE_DAY_IN_MILLISECONDS=864e5;export const ONE_WEEK_IN_MILLISECONDS=6048e5;export const ONE_YEAR_IN_MILLISECONDS=315576e5;export const ONE_MONTH_IN_MILLISECONDS=26298e5;
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { IJSONValue } from '../shared/types.js';
|
|
2
|
+
import { IDateTemplate, INumberFormatConfig, ITimeString } from './types.js';
|
|
2
3
|
/**
|
|
3
4
|
* Formats a numeric value based on the user's default language.
|
|
4
|
-
* @param value
|
|
5
|
-
* @param configuration?
|
|
6
|
-
* @returns string
|
|
5
|
+
* @param value The number to be formatted.
|
|
6
|
+
* @param configuration? An optional configuration object.
|
|
7
|
+
* @returns A string representing the formatted number.
|
|
7
8
|
*/
|
|
8
9
|
declare const prettifyNumber: (value: number, configuration?: Partial<INumberFormatConfig>) => string;
|
|
9
10
|
/**
|
|
@@ -16,58 +17,66 @@ declare const prettifyNumber: (value: number, configuration?: Partial<INumberFor
|
|
|
16
17
|
* - datetime-short: 12/5/2024, 12:05 PM
|
|
17
18
|
* - datetime-medium: December 5, 2024 at 12:05 PM
|
|
18
19
|
* - datetime-long: Thursday, December 5, 2024 at 12:05:20 PM
|
|
19
|
-
* @param value
|
|
20
|
-
* @param template
|
|
21
|
-
* @returns string
|
|
20
|
+
* @param value The date value to be formatted. It can be a Date object, a timestamp, or a date string.
|
|
21
|
+
* @param template The template to use for formatting the date.
|
|
22
|
+
* @returns A string representing the formatted date.
|
|
22
23
|
*/
|
|
23
24
|
declare const prettifyDate: (value: Date | number | string, template: IDateTemplate) => string;
|
|
24
25
|
/**
|
|
25
26
|
* Formats a bytes value into a human readable format.
|
|
26
|
-
* @param value
|
|
27
|
-
* @param decimalPlaces
|
|
28
|
-
* @
|
|
27
|
+
* @param value The bytes value to be formatted.
|
|
28
|
+
* @param decimalPlaces The number of decimal places to include. Defaults to 2.
|
|
29
|
+
* @returns A string representing the formatted file size.
|
|
29
30
|
*/
|
|
30
31
|
declare const prettifyFileSize: (value: number, decimalPlaces?: number) => string;
|
|
31
32
|
/**
|
|
32
33
|
* Formats the number that will be inserted in a badge so it doesn't take too much space. If the
|
|
33
34
|
* current count is 0, it returns undefined as the badge shouldn't be displayed.
|
|
34
|
-
* @param count
|
|
35
|
-
* @param maxValue
|
|
36
|
-
* @returns string
|
|
35
|
+
* @param count The current count to be displayed in the badge.
|
|
36
|
+
* @param maxValue The maximum value to display before showing a "+" sign. Defaults to 9.
|
|
37
|
+
* @returns A string representing the formatted badge count or undefined if the count is 0.
|
|
37
38
|
*/
|
|
38
39
|
declare const prettifyBadgeCount: (value: number, maxValue?: number) => string | undefined;
|
|
39
40
|
/**
|
|
40
41
|
* Capitalizes the first letter of a string and returns the new value.
|
|
41
|
-
* @param val
|
|
42
|
-
* @returns string
|
|
42
|
+
* @param val The string value to capitalize.
|
|
43
|
+
* @returns A string with the first letter capitalized.
|
|
43
44
|
*/
|
|
44
45
|
declare const capitalizeFirst: (value: string) => string;
|
|
45
46
|
/**
|
|
46
47
|
* Converts a string value into Title Case.
|
|
47
|
-
* @param value
|
|
48
|
-
* @returns string
|
|
48
|
+
* @param value The string value to convert.
|
|
49
|
+
* @returns A string converted to Title Case.
|
|
49
50
|
*/
|
|
50
51
|
declare const toTitleCase: (value: string) => string;
|
|
51
52
|
/**
|
|
52
|
-
* Converts a string value into a slug
|
|
53
|
-
*
|
|
54
|
-
*
|
|
53
|
+
* Converts a string value into a slug, meeting the following requirements:
|
|
54
|
+
* - lowercase
|
|
55
|
+
* - removes accents/diacritics
|
|
56
|
+
* - replaces spaces and separators with "-"
|
|
57
|
+
* - removes invalid URL characters
|
|
58
|
+
* - collapses repeated "-"
|
|
59
|
+
* - trims leading/trailing "-"
|
|
60
|
+
* @param value The string value to convert.
|
|
61
|
+
* @returns A string converted to a slug.
|
|
62
|
+
* @throws
|
|
63
|
+
* - UNABLE_TO_SLUGIFY_STRING: if the resulting slug is empty after processing the input string
|
|
55
64
|
*/
|
|
56
65
|
declare const toSlug: (value: string) => string;
|
|
57
66
|
/**
|
|
58
67
|
* Truncates a string to a specified length and appends an ellipsis if it exceeds that length.
|
|
59
|
-
* @param text
|
|
60
|
-
* @param maxLength
|
|
61
|
-
* @returns string
|
|
68
|
+
* @param text The string value to truncate.
|
|
69
|
+
* @param maxLength The maximum length of the string before truncation.
|
|
70
|
+
* @returns A string truncated to the specified length with an ellipsis if necessary.
|
|
62
71
|
*/
|
|
63
72
|
declare const truncateText: (text: string, maxLength: number) => string;
|
|
64
73
|
/**
|
|
65
74
|
* Masks the middle of a string, keeping a specified number of visible characters at the start and
|
|
66
75
|
* end.
|
|
67
|
-
* @param text
|
|
68
|
-
* @param visibleChars
|
|
69
|
-
* @param mask?
|
|
70
|
-
* @returns string
|
|
76
|
+
* @param text The string value to mask.
|
|
77
|
+
* @param visibleChars The number of characters to keep visible at the start and end of the string.
|
|
78
|
+
* @param mask? An optional string to use as the mask. Defaults to '...'.
|
|
79
|
+
* @returns A string with the middle masked, keeping the specified number of visible characters at the start.
|
|
71
80
|
*/
|
|
72
81
|
declare const maskMiddle: (text: string, visibleChars: number, mask?: string) => string;
|
|
73
82
|
/**
|
|
@@ -78,13 +87,26 @@ declare const maskMiddle: (text: string, visibleChars: number, mask?: string) =>
|
|
|
78
87
|
* @param input The input string containing placeholders in the format of {{key}}.
|
|
79
88
|
* @param substitutions? An object containing key-value pairs for substitutions. The keys should
|
|
80
89
|
* match the placeholders in the input string, without the curly braces.
|
|
81
|
-
* @returns string
|
|
90
|
+
* @returns A string with the placeholders replaced by their corresponding values from the substitutions object.
|
|
82
91
|
*/
|
|
83
92
|
declare const applySubstitutions: (input: string, substitutions?: Record<string, unknown>) => string;
|
|
93
|
+
/**
|
|
94
|
+
* Converts a time string into milliseconds. The time string should be in the format of "{value} {unit}",
|
|
95
|
+
* where the value is a number and the unit can be milliseconds, seconds, minutes, hours, days, weeks,
|
|
96
|
+
* months, or years. For example: "2 days", "5 minutes", "2 hours".
|
|
97
|
+
* @param str The time string to convert into milliseconds.
|
|
98
|
+
* @returns The equivalent time in milliseconds.
|
|
99
|
+
* @throws
|
|
100
|
+
* - INVALID_TIME_STRING: if the provided time string is not a valid string.
|
|
101
|
+
* - INVALID_TIME_STRING: if the chunks do not match the expected format.
|
|
102
|
+
* - INVALID_TIME_STRING: if the value is not a valid positive integer.
|
|
103
|
+
* - INVALID_TIME_STRING: if the unit is not one of the accepted values.
|
|
104
|
+
*/
|
|
105
|
+
declare const toMS: (str: ITimeString) => number;
|
|
84
106
|
/**
|
|
85
107
|
* Serializes a JSON object with the JSON.stringify method.
|
|
86
|
-
* @param value
|
|
87
|
-
* @returns string
|
|
108
|
+
* @param value The value to be serialized. It should be an object or an array.
|
|
109
|
+
* @returns A string representing the serialized JSON object.
|
|
88
110
|
* @throws
|
|
89
111
|
* - UNSUPPORTED_DATA_TYPE: if the provided value is not an object or an array
|
|
90
112
|
* - UNABLE_TO_SERIALIZE_JSON: if the result of JSON.stringify is not a valid string
|
|
@@ -94,8 +116,8 @@ declare const stringifyJSON: <T>(value: T) => string;
|
|
|
94
116
|
/**
|
|
95
117
|
* Stringifies a JSON object in a deterministic way, ensuring that the keys are sorted and the
|
|
96
118
|
* output is consistent.
|
|
97
|
-
* @param value
|
|
98
|
-
* @returns string
|
|
119
|
+
* @param value The value to be serialized. It should be an object or an array.
|
|
120
|
+
* @returns A string representing the serialized JSON object with sorted keys.
|
|
99
121
|
* @throws
|
|
100
122
|
* - UNSUPPORTED_DATA_TYPE: if the provided value is not an object or an array
|
|
101
123
|
* - UNABLE_TO_SERIALIZE_JSON: if the result of JSON.stringify is not a valid string
|
|
@@ -104,8 +126,8 @@ declare const stringifyJSON: <T>(value: T) => string;
|
|
|
104
126
|
declare const stringifyJSONDeterministically: <T>(value: T) => string;
|
|
105
127
|
/**
|
|
106
128
|
* Deserializes a JSON string with the JSON.parse method.
|
|
107
|
-
* @param value
|
|
108
|
-
* @returns
|
|
129
|
+
* @param value The JSON string to be deserialized.
|
|
130
|
+
* @returns The deserialized object or array.
|
|
109
131
|
* @throws
|
|
110
132
|
* - UNSUPPORTED_DATA_TYPE: if the provided value is not a non-empty string
|
|
111
133
|
* - UNABLE_TO_DESERIALIZE_JSON: if the result of JSON.parse is not a valid object or array
|
|
@@ -114,16 +136,16 @@ declare const stringifyJSONDeterministically: <T>(value: T) => string;
|
|
|
114
136
|
declare const parseJSON: <T>(value: string) => T;
|
|
115
137
|
/**
|
|
116
138
|
* Creates a deep clone of an object by using the JSON.stringify and JSON.parse methods.
|
|
117
|
-
* @param value
|
|
118
|
-
* @returns
|
|
139
|
+
* @param value The value to be cloned. It should be an object or an array.
|
|
140
|
+
* @returns A deep clone of the provided value.
|
|
119
141
|
* @throws
|
|
120
142
|
* - UNABLE_TO_CREATE_DEEP_CLONE: if the value cannot be serialized and deserialized
|
|
121
143
|
*/
|
|
122
144
|
declare const createDeepClone: <T>(value: T) => T;
|
|
123
145
|
/**
|
|
124
146
|
* Removes null, undefined, empty objects, and empty arrays from the given data recursively.
|
|
125
|
-
* @param value
|
|
126
|
-
* @returns
|
|
147
|
+
* @param value The value to be pruned. It should be an object, array, or primitive value.
|
|
148
|
+
* @returns The pruned value, or null if the value is empty or invalid.
|
|
127
149
|
*/
|
|
128
150
|
declare const pruneJSON: <T extends IJSONValue>(value: T) => T | null;
|
|
129
|
-
export { prettifyNumber, prettifyDate, prettifyFileSize, prettifyBadgeCount, capitalizeFirst, toTitleCase, toSlug, truncateText, maskMiddle, applySubstitutions, stringifyJSON, stringifyJSONDeterministically, parseJSON, createDeepClone, pruneJSON, };
|
|
151
|
+
export { type INumberFormatConfig, type IDateTemplate, type ITimeString, prettifyNumber, prettifyDate, prettifyFileSize, prettifyBadgeCount, capitalizeFirst, toTitleCase, toSlug, truncateText, maskMiddle, applySubstitutions, toMS, stringifyJSON, stringifyJSONDeterministically, parseJSON, createDeepClone, pruneJSON, };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decodeError,encodeError,extractMessage}from"error-message-utils";import{ERRORS}from"../shared/errors.js";import{isObjectValid}from"../validations/index.js";import{DATE_TEMPLATE_CONFIGS,
|
|
1
|
+
import{decodeError,encodeError,extractMessage}from"error-message-utils";import{ERRORS}from"../shared/errors.js";import{isObjectValid}from"../validations/index.js";import{FILE_SIZE_THRESHOLD,FILE_SIZE_UNITS,DATE_TEMPLATE_CONFIGS,ONE_DAY_IN_MILLISECONDS,ONE_HOUR_IN_MILLISECONDS,ONE_MINUTE_IN_MILLISECONDS,ONE_MONTH_IN_MILLISECONDS,ONE_SECOND_IN_MILLISECONDS,ONE_WEEK_IN_MILLISECONDS,ONE_YEAR_IN_MILLISECONDS}from"./consts.js";import{canJSONBeSerialized,validateJSONSerializationResult,canJSONBeDeserialized,validateJSONDeserializationResult}from"./validations.js";import{buildNumberFormatConfig,getDateInstance,parseTimeString,sortJSONObjectKeys}from"./utils.js";const prettifyNumber=(e,r)=>{const t=buildNumberFormatConfig(r),i=e.toLocaleString(void 0,{minimumFractionDigits:t.minimumFractionDigits,maximumFractionDigits:t.maximumFractionDigits});return`${t.prefix}${i}${t.suffix}`},prettifyDate=(e,r)=>getDateInstance(e).toLocaleString(void 0,DATE_TEMPLATE_CONFIGS[r]),prettifyFileSize=(e,r=2)=>{if("number"==typeof e&&e>0){let t=e;if(Math.abs(e)<FILE_SIZE_THRESHOLD)return`${e} B`;let i=-1;const a=10**r;do{t/=FILE_SIZE_THRESHOLD,i+=1}while(Math.round(Math.abs(t)*a)/a>=FILE_SIZE_THRESHOLD&&i<FILE_SIZE_UNITS.length-1);return`${t.toFixed(r)} ${FILE_SIZE_UNITS[i]}`}return"0 B"},prettifyBadgeCount=(e,r=9)=>{if(0!==e)return e>=r?`${r}+`:String(e)},capitalizeFirst=e=>e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:"",toTitleCase=e=>e.replace(/\w\S*/g,(e=>e.charAt(0).toUpperCase()+e.substring(1).toLowerCase())),toSlug=e=>{const r=e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim().replace(/['’]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");if(0===r.length)throw new Error(encodeError(`Failed to slugify the string '${e}': the resulting slug is empty.`,ERRORS.UNABLE_TO_SLUGIFY_STRING));return r},truncateText=(e,r)=>e.length<=r?e:`${e.slice(0,r-3)}...`,maskMiddle=(e,r,t="...")=>e.length<=2*r?e:`${e.slice(0,r)}${t}${e.slice(-r)}`,applySubstitutions=(e,r={})=>e.replace(/{{(.*?)}}/g,((e,t)=>t in r?String(r[t]):e)),toMS=e=>{const{value:r,unit:t}=parseTimeString(e);switch(t){case"years":case"year":return r*ONE_YEAR_IN_MILLISECONDS;case"months":case"month":return r*ONE_MONTH_IN_MILLISECONDS;case"weeks":case"week":return r*ONE_WEEK_IN_MILLISECONDS;case"days":case"day":return r*ONE_DAY_IN_MILLISECONDS;case"hours":case"hour":return r*ONE_HOUR_IN_MILLISECONDS;case"minutes":case"minute":return r*ONE_MINUTE_IN_MILLISECONDS;case"seconds":case"second":return r*ONE_SECOND_IN_MILLISECONDS;case"milliseconds":case"millisecond":return r;default:throw new Error(encodeError(`The unit provided to the toMS function is invalid: "${t}". Received: ${e}`,ERRORS.INVALID_TIME_STRING))}},stringifyJSON=e=>{canJSONBeSerialized(e);try{const r=JSON.stringify(e);return validateJSONSerializationResult(e,r),r}catch(r){if(decodeError(r).code!==ERRORS.UNABLE_TO_SERIALIZE_JSON)throw new Error(encodeError(`Failed to stringify the JSON value '${e}': ${extractMessage(r)}`,ERRORS.UNABLE_TO_SERIALIZE_JSON));throw r}},stringifyJSONDeterministically=e=>{canJSONBeSerialized(e);try{return stringifyJSON(sortJSONObjectKeys(e))}catch(r){if(decodeError(r).code!==ERRORS.UNABLE_TO_SERIALIZE_JSON)throw new Error(encodeError(`Failed to stringify the JSON value deterministically '${e}': ${extractMessage(r)}`,ERRORS.UNABLE_TO_SERIALIZE_JSON));throw r}},parseJSON=e=>{canJSONBeDeserialized(e);try{const r=JSON.parse(e);return validateJSONDeserializationResult(e,r),r}catch(r){if(decodeError(r).code!==ERRORS.UNABLE_TO_DESERIALIZE_JSON)throw new Error(encodeError(`Failed to parse the JSON value '${e}': ${extractMessage(r)}`,ERRORS.UNABLE_TO_DESERIALIZE_JSON));throw r}},createDeepClone=e=>{try{return parseJSON(stringifyJSON(e))}catch(r){throw new Error(encodeError(`Failed to create a deep clone of the value '${e}': ${extractMessage(r)}`,ERRORS.UNABLE_TO_CREATE_DEEP_CLONE))}},pruneJSON=e=>{if(null==e)return null;if(Array.isArray(e)){const r=e.map((e=>pruneJSON(e))).filter((e=>null!=e&&(Array.isArray(e)?e.length>0:!isObjectValid(e,!0)||Object.keys(e).length>0)));return r.length>0?r:null}if(isObjectValid(e,!0)){const r={};return Object.entries(e).forEach((([e,t])=>{const i=pruneJSON(t);null!=i&&(Array.isArray(i)&&0===i.length||isObjectValid(i,!0)&&!isObjectValid(i)||(r[e]=i))})),Object.keys(r).length>0?r:null}return e};export{prettifyNumber,prettifyDate,prettifyFileSize,prettifyBadgeCount,capitalizeFirst,toTitleCase,toSlug,truncateText,maskMiddle,applySubstitutions,toMS,stringifyJSON,stringifyJSONDeterministically,parseJSON,createDeepClone,pruneJSON};
|
|
@@ -1,15 +1,8 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* JSON Value
|
|
3
|
-
* A value that can be represented in JSON format.
|
|
4
|
-
*/
|
|
5
|
-
type IJSONValue = string | number | boolean | null | IJSONValue[] | {
|
|
6
|
-
[key: string]: IJSONValue;
|
|
7
|
-
};
|
|
8
1
|
/**
|
|
9
2
|
* Number Format Configuration
|
|
10
3
|
* The configuration that will be used to prettify a number.
|
|
11
4
|
*/
|
|
12
|
-
type INumberFormatConfig = {
|
|
5
|
+
export type INumberFormatConfig = {
|
|
13
6
|
minimumFractionDigits: number;
|
|
14
7
|
maximumFractionDigits: number;
|
|
15
8
|
prefix: string;
|
|
@@ -27,12 +20,12 @@ type INumberFormatConfig = {
|
|
|
27
20
|
* - datetime-medium: Apr 29, 1453, 12:00:00 AM
|
|
28
21
|
* - datetime-long: Friday, April 29th, 1453 at 12:00:00 AM
|
|
29
22
|
*/
|
|
30
|
-
type IDateTemplate = 'date-short' | 'date-medium' | 'date-long' | 'time-short' | 'time-medium' | 'datetime-short' | 'datetime-medium' | 'datetime-long';
|
|
23
|
+
export type IDateTemplate = 'date-short' | 'date-medium' | 'date-long' | 'time-short' | 'time-medium' | 'datetime-short' | 'datetime-medium' | 'datetime-long';
|
|
31
24
|
/**
|
|
32
25
|
* Date Template Configs
|
|
33
26
|
* The options that will be combined in order to provide a format that can meet any requirement.
|
|
34
27
|
*/
|
|
35
|
-
type IDateTemplateConfigs = {
|
|
28
|
+
export type IDateTemplateConfigs = {
|
|
36
29
|
[key in IDateTemplate]: {
|
|
37
30
|
localeMatcher?: 'best fit' | 'lookup' | undefined;
|
|
38
31
|
weekday?: 'long' | 'short' | 'narrow' | undefined;
|
|
@@ -49,4 +42,20 @@ type IDateTemplateConfigs = {
|
|
|
49
42
|
timeZone?: string | undefined;
|
|
50
43
|
};
|
|
51
44
|
};
|
|
52
|
-
|
|
45
|
+
/**
|
|
46
|
+
* Time String
|
|
47
|
+
* The following types were extracted from the 'ms' package, which is a popular library for parsing
|
|
48
|
+
* and formatting time durations. For more information, please refer to the original source:
|
|
49
|
+
* https://github.com/vercel/ms
|
|
50
|
+
*/
|
|
51
|
+
type IYears = 'years' | 'year';
|
|
52
|
+
type IMonths = 'months' | 'month';
|
|
53
|
+
type IWeeks = 'weeks' | 'week';
|
|
54
|
+
type IDays = 'days' | 'day';
|
|
55
|
+
type IHours = 'hours' | 'hour';
|
|
56
|
+
type IMinutes = 'minutes' | 'minute';
|
|
57
|
+
type ISeconds = 'seconds' | 'second';
|
|
58
|
+
type IMilliseconds = 'milliseconds' | 'millisecond';
|
|
59
|
+
export type IUnit = IYears | IMonths | IWeeks | IDays | IHours | IMinutes | ISeconds | IMilliseconds;
|
|
60
|
+
export type ITimeString = `${number} ${IUnit}`;
|
|
61
|
+
export {};
|
|
@@ -1,21 +1,33 @@
|
|
|
1
|
-
import { INumberFormatConfig } from './types.js';
|
|
1
|
+
import { INumberFormatConfig, ITimeString } from './types.js';
|
|
2
2
|
/**
|
|
3
3
|
* Builds the object that will be passed to the number formatting function.
|
|
4
|
-
* @param config?
|
|
5
|
-
* @returns
|
|
4
|
+
* @param config? The optional configuration object for number formatting.
|
|
5
|
+
* @returns The configuration object for number formatting with default values applied.
|
|
6
6
|
*/
|
|
7
|
-
declare const buildNumberFormatConfig: (config?: Partial<INumberFormatConfig>) => INumberFormatConfig;
|
|
7
|
+
export declare const buildNumberFormatConfig: (config?: Partial<INumberFormatConfig>) => INumberFormatConfig;
|
|
8
8
|
/**
|
|
9
9
|
* Creates an instance of Date based on a value.
|
|
10
|
-
* @param value
|
|
11
|
-
* @returns Date
|
|
10
|
+
* @param value The value to create a Date instance from. It can be a Date object, a timestamp, or a date string.
|
|
11
|
+
* @returns A Date instance.
|
|
12
12
|
*/
|
|
13
|
-
declare const getDateInstance: (value: Date | number | string) => Date;
|
|
13
|
+
export declare const getDateInstance: (value: Date | number | string) => Date;
|
|
14
|
+
/**
|
|
15
|
+
* Parses a time string and returns an object containing the value and the unit.
|
|
16
|
+
* @param str The time string to parse.
|
|
17
|
+
* @returns The parsed time string as an object containing the value and the unit.
|
|
18
|
+
* @throws
|
|
19
|
+
* - INVALID_TIME_STRING: if the provided time string is not a valid string.
|
|
20
|
+
* - INVALID_TIME_STRING: if the chunks do not match the expected format.
|
|
21
|
+
* - INVALID_TIME_STRING: if the value is not a valid positive integer.
|
|
22
|
+
*/
|
|
23
|
+
export declare const parseTimeString: (str: ITimeString) => {
|
|
24
|
+
value: number;
|
|
25
|
+
unit: string;
|
|
26
|
+
};
|
|
14
27
|
/**
|
|
15
28
|
* Recursively sorts the keys of a JSON object. If the value is not an object or an array, it
|
|
16
29
|
* returns the value as is.
|
|
17
|
-
* @param val
|
|
18
|
-
* @returns
|
|
30
|
+
* @param val The value to sort. It can be an object, an array, or any other type.
|
|
31
|
+
* @returns The value with sorted keys if it's an object, or the original value otherwise.
|
|
19
32
|
*/
|
|
20
|
-
declare const sortJSONObjectKeys: (val: unknown) => unknown;
|
|
21
|
-
export { buildNumberFormatConfig, getDateInstance, sortJSONObjectKeys };
|
|
33
|
+
export declare const sortJSONObjectKeys: (val: unknown) => unknown;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isArrayValid,isObjectValid}from"../validations/index.js";const buildNumberFormatConfig=(i={})=>({minimumFractionDigits:i.minimumFractionDigits??0,maximumFractionDigits:i.maximumFractionDigits??2,prefix:i.prefix??"",suffix:i.suffix??""})
|
|
1
|
+
import{isArrayValid,isObjectValid}from"../validations/index.js";import{validateTimeStringChunks,validateTimeStringType,validateTimeStringValue}from"./validations.js";export const buildNumberFormatConfig=(i={})=>({minimumFractionDigits:i.minimumFractionDigits??0,maximumFractionDigits:i.maximumFractionDigits??2,prefix:i.prefix??"",suffix:i.suffix??""});export const getDateInstance=i=>i instanceof Date?i:new Date(i);export const parseTimeString=i=>{validateTimeStringType(i);const t=i.split(" ");validateTimeStringChunks(t);const e=Number(t[0]);return validateTimeStringValue(e),{value:e,unit:t[1]}};export const sortJSONObjectKeys=i=>isArrayValid(i)?i.map(sortJSONObjectKeys):isObjectValid(i)?Object.keys(i).sort().reduce(((t,e)=>({...t,[e]:sortJSONObjectKeys(i[e])})),{}):i;
|
|
@@ -1,31 +1,52 @@
|
|
|
1
|
+
import { ITimeString } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Ensures a provided time string is valid and can be parsed by the toMS function.
|
|
4
|
+
* @param str The time string to validate.
|
|
5
|
+
* @throws
|
|
6
|
+
* - INVALID_TIME_STRING: if the provided time string is not a valid string.
|
|
7
|
+
*/
|
|
8
|
+
export declare const validateTimeStringType: (str: ITimeString) => void;
|
|
9
|
+
/**
|
|
10
|
+
* Ensures the chunks obtained from splitting a time string are valid and can be parsed by the toMS function.
|
|
11
|
+
* @param chunks The chunks obtained from splitting a time string.
|
|
12
|
+
* @throws
|
|
13
|
+
* - INVALID_TIME_STRING: if the chunks do not match the expected format.
|
|
14
|
+
*/
|
|
15
|
+
export declare const validateTimeStringChunks: (chunks: string[]) => void;
|
|
16
|
+
/**
|
|
17
|
+
* Ensures the value obtained from a time string is a valid positive integer that can be parsed by the toMS function.
|
|
18
|
+
* @param value The value to validate.
|
|
19
|
+
* @throws
|
|
20
|
+
* - INVALID_TIME_STRING: if the value is not a valid positive integer.
|
|
21
|
+
*/
|
|
22
|
+
export declare const validateTimeStringValue: (value: number) => void;
|
|
1
23
|
/**
|
|
2
24
|
* Checks if a JSON value can be serialized (JSON.stringify).
|
|
3
|
-
* @param value
|
|
25
|
+
* @param value The value to check for JSON serialization. It should be an object or an array.
|
|
4
26
|
* @throws
|
|
5
27
|
* - UNSUPPORTED_DATA_TYPE: if the provided value is not an object or an array
|
|
6
28
|
*/
|
|
7
|
-
declare const canJSONBeSerialized: (value: unknown) => void;
|
|
29
|
+
export declare const canJSONBeSerialized: (value: unknown) => void;
|
|
8
30
|
/**
|
|
9
31
|
* Validates the result of a JSON serialization operation.
|
|
10
|
-
* @param value
|
|
11
|
-
* @param result
|
|
32
|
+
* @param value The original value that was attempted to be serialized.
|
|
33
|
+
* @param result The result of the JSON.stringify operation.
|
|
12
34
|
* @throws
|
|
13
35
|
* - UNABLE_TO_SERIALIZE_JSON: if the result of JSON.stringify is not a valid string
|
|
14
36
|
*/
|
|
15
|
-
declare const validateJSONSerializationResult: (value: unknown, result: unknown) => void;
|
|
37
|
+
export declare const validateJSONSerializationResult: (value: unknown, result: unknown) => void;
|
|
16
38
|
/**
|
|
17
39
|
* Checks if a JSON value can be deserialized (JSON.parse).
|
|
18
|
-
* @param value
|
|
40
|
+
* @param value The value to check for JSON deserialization.
|
|
19
41
|
* @throws
|
|
20
42
|
* - UNSUPPORTED_DATA_TYPE: if the provided value is not a non-empty string
|
|
21
43
|
*/
|
|
22
|
-
declare const canJSONBeDeserialized: (value: string) => void;
|
|
44
|
+
export declare const canJSONBeDeserialized: (value: string) => void;
|
|
23
45
|
/**
|
|
24
46
|
* Validates the result of a JSON deserialization operation (JSON.parse).
|
|
25
|
-
* @param value
|
|
26
|
-
* @param result
|
|
47
|
+
* @param value The original value that was attempted to be deserialized.
|
|
48
|
+
* @param result The result of the JSON.parse operation.
|
|
27
49
|
* @throws
|
|
28
50
|
* - UNABLE_TO_DESERIALIZE_JSON: if the result of JSON.parse is not a valid object or array
|
|
29
51
|
*/
|
|
30
|
-
declare const validateJSONDeserializationResult: (value: string, result: unknown) => void;
|
|
31
|
-
export { canJSONBeSerialized, validateJSONSerializationResult, canJSONBeDeserialized, validateJSONDeserializationResult, };
|
|
52
|
+
export declare const validateJSONDeserializationResult: (value: string, result: unknown) => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{encodeError}from"error-message-utils";import{ERRORS}from"../shared/errors.js";import{isArrayValid,isObjectValid}from"../validations/index.js";const canJSONBeSerialized=e=>{if(!isObjectValid(e,!0)&&!isArrayValid(e,!0))throw new Error(encodeError(`The JSON value must be an object or an array in order to be stringified. Received: ${e}`,ERRORS.UNSUPPORTED_DATA_TYPE))}
|
|
1
|
+
import{encodeError}from"error-message-utils";import{ERRORS}from"../shared/errors.js";import{isArrayValid,isIntegerValid,isObjectValid,isStringValid}from"../validations/index.js";export const validateTimeStringType=e=>{if(!isStringValid(e,5,100))throw new Error(encodeError(`The provided time string is invalid, it must be a string with length between 5 and 100. Received: ${e}`,ERRORS.INVALID_TIME_STRING))};export const validateTimeStringChunks=e=>{if(2!==e.length)throw new Error(encodeError(`The format of the provided time string is invalid, it must match the expected format {value} {unit}. For example: '2 days'. Received: ${JSON.stringify(e)}`,ERRORS.INVALID_TIME_STRING))};export const validateTimeStringValue=e=>{if(!isIntegerValid(e,1))throw new Error(encodeError(`The value of the provided time string is invalid, it must be a positive integer. Received: ${e}`,ERRORS.INVALID_TIME_STRING))};export const canJSONBeSerialized=e=>{if(!isObjectValid(e,!0)&&!isArrayValid(e,!0))throw new Error(encodeError(`The JSON value must be an object or an array in order to be stringified. Received: ${e}`,ERRORS.UNSUPPORTED_DATA_TYPE))};export const validateJSONSerializationResult=(e,r)=>{if("string"!=typeof r||!r.length)throw new Error(encodeError(`Stringifying the JSON value '${e}' produced an invalid result: ${r}.`,ERRORS.UNABLE_TO_SERIALIZE_JSON))};export const canJSONBeDeserialized=e=>{if("string"!=typeof e||!e.length)throw new Error(encodeError(`The JSON value must be a non-empty string in order to be parsed. Received: ${e}`,ERRORS.UNSUPPORTED_DATA_TYPE))};export const validateJSONDeserializationResult=(e,r)=>{if(!isObjectValid(r,!0)&&!isArrayValid(r,!0))throw new Error(encodeError(`Parsing the JSON value '${e}' produced an invalid result: ${r}.`,ERRORS.UNABLE_TO_DESERIALIZE_JSON))};
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -2,52 +2,52 @@ import { IUUIDVersion } from '../shared/types.js';
|
|
|
2
2
|
import { IFilterByQueryOptions, ISortDirection } from './types.js';
|
|
3
3
|
/**
|
|
4
4
|
* Generates a UUID based on a version.
|
|
5
|
-
* @param version
|
|
6
|
-
* @returns string
|
|
5
|
+
* @param version The version of the UUID to be generated.
|
|
6
|
+
* @returns A UUID string of the specified version.
|
|
7
7
|
*/
|
|
8
8
|
declare const generateUUID: (version: IUUIDVersion) => string;
|
|
9
9
|
/**
|
|
10
10
|
* Generates a string from randomly picked characters based on the length.
|
|
11
|
-
* @param length
|
|
12
|
-
* @param characters?
|
|
13
|
-
* @returns string
|
|
11
|
+
* @param length The length of the random string to be generated.
|
|
12
|
+
* @param characters? A string of characters to pick from when generating the random string. Defaults to 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.
|
|
13
|
+
* @returns A randomly generated string of the specified length.
|
|
14
14
|
*/
|
|
15
15
|
declare const generateRandomString: (length: number, characters?: string) => string;
|
|
16
16
|
/**
|
|
17
17
|
* Generates a random number (decimal) constrained by the range.
|
|
18
|
-
* @param min
|
|
19
|
-
* @param max
|
|
20
|
-
* @returns number
|
|
18
|
+
* @param min The minimum value of the range.
|
|
19
|
+
* @param max The maximum value of the range.
|
|
20
|
+
* @returns A randomly generated decimal number within the specified range.
|
|
21
21
|
*/
|
|
22
22
|
declare const generateRandomFloat: (min: number, max: number) => number;
|
|
23
23
|
/**
|
|
24
24
|
* Generates a random number (integer) constrained by the range.
|
|
25
|
-
* @param min
|
|
26
|
-
* @param max
|
|
27
|
-
* @returns number
|
|
25
|
+
* @param min The minimum value of the range.
|
|
26
|
+
* @param max The maximum value of the range.
|
|
27
|
+
* @returns A randomly generated integer number within the specified range.
|
|
28
28
|
*/
|
|
29
29
|
declare const generateRandomInteger: (min: number, max: number) => number;
|
|
30
30
|
/**
|
|
31
31
|
* Generates a sequence of numbers within a range based on a number of steps.
|
|
32
|
-
* @param start
|
|
33
|
-
* @param stop
|
|
34
|
-
* @param step?
|
|
35
|
-
* @returns
|
|
32
|
+
* @param start The starting value of the sequence.
|
|
33
|
+
* @param stop The ending value of the sequence.
|
|
34
|
+
* @param step? The step value to increment the sequence. Defaults to 1.
|
|
35
|
+
* @returns An array of numbers representing the sequence.
|
|
36
36
|
*/
|
|
37
37
|
declare const generateSequence: (start: number, stop: number, step?: number) => number[];
|
|
38
38
|
/**
|
|
39
39
|
* Sorts a list of primitive values based on their type and a sort direction.
|
|
40
|
-
* @param direction
|
|
41
|
-
* @returns
|
|
40
|
+
* @param direction The direction to sort the values.
|
|
41
|
+
* @returns A number indicating the sort order based on the primitive type.
|
|
42
42
|
* @throws
|
|
43
43
|
* - MIXED_OR_UNSUPPORTED_DATA_TYPES: if the values are mixed or are different to string | number
|
|
44
44
|
*/
|
|
45
45
|
declare const sortPrimitives: (direction: ISortDirection) => <T extends string | number>(a: T, b: T) => number;
|
|
46
46
|
/**
|
|
47
47
|
* Sorts a list of record values by key based on their type and a sort direction.
|
|
48
|
-
* @param key
|
|
49
|
-
* @param direction
|
|
50
|
-
* @returns
|
|
48
|
+
* @param key The key of the record to sort by.
|
|
49
|
+
* @param direction The direction to sort the values.
|
|
50
|
+
* @returns A number indicating the sort order based on the primitive type.
|
|
51
51
|
* @throws
|
|
52
52
|
* - MIXED_OR_UNSUPPORTED_DATA_TYPES: if the values are mixed or are different to string | number
|
|
53
53
|
*/
|
|
@@ -55,27 +55,27 @@ declare const sortRecords: (key: string, direction: ISortDirection) => <T extend
|
|
|
55
55
|
/**
|
|
56
56
|
* Creates a shallow copy of the input array and shuffles it, using a version of the Fisher-Yates
|
|
57
57
|
* algorithm.
|
|
58
|
-
* @param input
|
|
59
|
-
* @returns
|
|
58
|
+
* @param input The array to be shuffled.
|
|
59
|
+
* @returns A new array with the values of the input array in a random order.
|
|
60
60
|
* @throws
|
|
61
61
|
* - INVALID_OR_EMPTY_ARRAY: if the input is not array or it is empty
|
|
62
62
|
*/
|
|
63
63
|
declare const shuffleArray: <T>(input: Array<T>) => Array<T>;
|
|
64
64
|
/**
|
|
65
65
|
* Splits an array into smaller arrays (batches) of a given size.
|
|
66
|
-
* @param items
|
|
67
|
-
* @param batchSize
|
|
68
|
-
* @returns
|
|
66
|
+
* @param items The array to be split into batches.
|
|
67
|
+
* @param batchSize The size of each batch.
|
|
68
|
+
* @returns An array of arrays, where each inner array is a batch of the specified size.
|
|
69
69
|
* @throws
|
|
70
70
|
* - INVALID_BATCH_SIZE: if the batch size is not a valid integer greater than 0
|
|
71
71
|
*/
|
|
72
|
-
|
|
72
|
+
declare const splitArrayIntoBatches: <T>(items: T[], batchSize: number) => Array<T[]>;
|
|
73
73
|
/**
|
|
74
74
|
* Picks a list of properties from an object and returns a new object (shallow) with the provided
|
|
75
75
|
* keys.
|
|
76
|
-
* @param input
|
|
77
|
-
* @param propKeys
|
|
78
|
-
* @returns
|
|
76
|
+
* @param input The object from which to pick properties.
|
|
77
|
+
* @param propKeys The keys of the properties to pick.
|
|
78
|
+
* @returns A new object containing only the picked properties.
|
|
79
79
|
* @throws
|
|
80
80
|
* - INVALID_OR_EMPTY_OBJECT: if the input is not a valid object or it is empty
|
|
81
81
|
* - INVALID_OR_EMPTY_ARRAY: if the keys to be picked are not a valid array or it is empty
|
|
@@ -84,19 +84,19 @@ declare const pickProps: <T extends Record<string, any>, K extends keyof T>(inpu
|
|
|
84
84
|
/**
|
|
85
85
|
* Omits a list of properties from an object and returns a new object (shallow) with only those
|
|
86
86
|
* keys that weren't omitted
|
|
87
|
-
* @param input
|
|
88
|
-
* @param propKeys
|
|
89
|
-
* @returns
|
|
87
|
+
* @param input The object from which to omit properties.
|
|
88
|
+
* @param propKeys The keys of the properties to omit.
|
|
89
|
+
* @returns A new object containing only the properties that were not omitted.
|
|
90
90
|
* @throws
|
|
91
91
|
* - INVALID_OR_EMPTY_OBJECT: if the input is not a valid object or it is empty
|
|
92
92
|
* - INVALID_OR_EMPTY_ARRAY: if the keys to be omitted are not a valid array or it is empty
|
|
93
93
|
*/
|
|
94
94
|
declare const omitProps: <T extends Record<string, any>, K extends keyof T>(input: T, propKeys: K[]) => Omit<T, K>;
|
|
95
95
|
/**
|
|
96
|
-
* Compares two objects or arrays deeply and returns true if they are
|
|
97
|
-
* @param a
|
|
98
|
-
* @param b
|
|
99
|
-
* @returns boolean
|
|
96
|
+
* Compares two objects or arrays deeply and returns true if they are equal.
|
|
97
|
+
* @param a The first object or array to compare.
|
|
98
|
+
* @param b The second object or array to compare.
|
|
99
|
+
* @returns A boolean indicating whether the two values are equal.
|
|
100
100
|
* @throws
|
|
101
101
|
* - UNSUPPORTED_DATA_TYPE: if any of the values isn't an object or an array
|
|
102
102
|
* - UNABLE_TO_SERIALIZE_JSON: if any of the values contains data that cannot be serialized
|
|
@@ -106,25 +106,24 @@ declare const isEqual: (a: Record<string, any> | Array<any>, b: Record<string, a
|
|
|
106
106
|
* Filters an array of primitives based on a given query and returns a shallow copy.
|
|
107
107
|
* @IMPORTANT Providing the queryProp makes the query very efficient as it only attempts to match
|
|
108
108
|
* the value of that property, instead of the whole item.
|
|
109
|
-
* @param items
|
|
110
|
-
* @param query
|
|
111
|
-
* @param options?
|
|
112
|
-
* @returns
|
|
109
|
+
* @param items The array of items to be filtered by the query.
|
|
110
|
+
* @param query The query string to filter the items by.
|
|
111
|
+
* @param options? The options to filter the items by query.
|
|
112
|
+
* @returns A new array containing the items that match the query based on the provided options.
|
|
113
113
|
*/
|
|
114
114
|
declare const filterByQuery: <T>(items: T[], query: string, options?: IFilterByQueryOptions<T>) => T[];
|
|
115
115
|
/**
|
|
116
116
|
* Creates an asynchronous delay that resolves once the provided seconds have passed.
|
|
117
|
-
* @param seconds
|
|
118
|
-
* @returns
|
|
117
|
+
* @param seconds The number of seconds to delay before the promise resolves.
|
|
118
|
+
* @returns A promise that resolves after the specified number of seconds has passed.
|
|
119
119
|
*/
|
|
120
120
|
declare const delay: (seconds: number) => Promise<void>;
|
|
121
121
|
/**
|
|
122
122
|
* Executes an asynchronous function persistently, retrying on error with incremental delays
|
|
123
123
|
* defined in retryScheduleDuration (seconds).
|
|
124
|
-
* @param func
|
|
125
|
-
* @param
|
|
126
|
-
* @
|
|
127
|
-
* @returns Promise<T>
|
|
124
|
+
* @param func The asynchronous function to be executed persistently.
|
|
125
|
+
* @param retryScheduleDuration? An array of numbers representing the delay (in seconds) between each retry attempt. Defaults to [3, 5].
|
|
126
|
+
* @returns A promise that resolves with the result of the asynchronous function or rejects with the last encountered error.
|
|
128
127
|
*/
|
|
129
128
|
declare const retryAsyncFunction: <T>(func: () => Promise<T>, retryScheduleDuration?: number[]) => Promise<T>;
|
|
130
|
-
export { generateUUID, generateRandomString, generateRandomFloat, generateRandomInteger, generateSequence, sortPrimitives, sortRecords, shuffleArray, pickProps, omitProps, isEqual, filterByQuery, delay, retryAsyncFunction, };
|
|
129
|
+
export { type ISortDirection, type IFilterByQueryOptions, generateUUID, generateRandomString, generateRandomFloat, generateRandomInteger, generateSequence, sortPrimitives, sortRecords, shuffleArray, splitArrayIntoBatches, pickProps, omitProps, isEqual, filterByQuery, delay, retryAsyncFunction, };
|
package/dist/utils/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{v4 as uuidv4,v7 as uuidv7}from"uuid";import{encodeError}from"error-message-utils";import{ERRORS}from"../shared/errors.js";import{isIntegerValid}from"../validations/index.js";import{stringifyJSONDeterministically}from"../transformers/index.js";import{canArrayBeShuffled,validateObjectAndKeys}from"./validations.js";import{buildNormalizedQueryTokens}from"./transformers.js";import{filterItemsByQueryTokens}from"./utils.js";const generateUUID=e=>7===e?uuidv7():uuidv4(),generateRandomString=(e,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")=>{let t="",n=0;for(;n<e;)t+=r.charAt(Math.floor(Math.random()*r.length)),n+=1;return t},generateRandomFloat=(e,r)=>{const t=Math.random()*(r-e+1)+e;return t>r?r:t},generateRandomInteger=(e,r)=>Math.floor(generateRandomFloat(e,r)),generateSequence=(e,r,t=1)=>Array.from({length:(r-e)/t+1},((r,n)=>e+n*t)),__sortStringValues=(e,r,t)=>{const n=e.toLocaleLowerCase(),o=r.toLocaleLowerCase();return n>o?"asc"===t?1:-1:o>n?"asc"===t?-1:1:0},__sortNumberValues=(e,r,t)=>"asc"===t?e-r:r-e,sortPrimitives=e=>(r,t)=>{if("string"==typeof r&&"string"==typeof t)return __sortStringValues(r,t,e);if("number"==typeof r&&"number"==typeof t)return __sortNumberValues(r,t,e);throw new Error(encodeError(`Unable to sort list of primitive values as they can only be string | number and must not be mixed. Received: ${typeof r}, ${typeof t}`,ERRORS.MIXED_OR_UNSUPPORTED_DATA_TYPES))},sortRecords=(e,r)=>(t,n)=>{if("string"==typeof t[e]&&"string"==typeof n[e])return __sortStringValues(t[e],n[e],r);if("number"==typeof t[e]&&"number"==typeof n[e])return __sortNumberValues(t[e],n[e],r);throw new Error(encodeError(`Unable to sort list of record values as they can only be string | number and must not be mixed. Received: ${typeof t[e]}, ${typeof n[e]}`,ERRORS.MIXED_OR_UNSUPPORTED_DATA_TYPES))},shuffleArray=e=>{canArrayBeShuffled(e);const r=e.slice();for(let e=r.length-1;e>0;e-=1){const t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}return r}
|
|
1
|
+
import{v4 as uuidv4,v7 as uuidv7}from"uuid";import{encodeError}from"error-message-utils";import{ERRORS}from"../shared/errors.js";import{isIntegerValid}from"../validations/index.js";import{stringifyJSONDeterministically}from"../transformers/index.js";import{canArrayBeShuffled,validateObjectAndKeys}from"./validations.js";import{buildNormalizedQueryTokens}from"./transformers.js";import{filterItemsByQueryTokens}from"./utils.js";const generateUUID=e=>7===e?uuidv7():uuidv4(),generateRandomString=(e,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")=>{let t="",n=0;for(;n<e;)t+=r.charAt(Math.floor(Math.random()*r.length)),n+=1;return t},generateRandomFloat=(e,r)=>{const t=Math.random()*(r-e+1)+e;return t>r?r:t},generateRandomInteger=(e,r)=>Math.floor(generateRandomFloat(e,r)),generateSequence=(e,r,t=1)=>Array.from({length:(r-e)/t+1},((r,n)=>e+n*t)),__sortStringValues=(e,r,t)=>{const n=e.toLocaleLowerCase(),o=r.toLocaleLowerCase();return n>o?"asc"===t?1:-1:o>n?"asc"===t?-1:1:0},__sortNumberValues=(e,r,t)=>"asc"===t?e-r:r-e,sortPrimitives=e=>(r,t)=>{if("string"==typeof r&&"string"==typeof t)return __sortStringValues(r,t,e);if("number"==typeof r&&"number"==typeof t)return __sortNumberValues(r,t,e);throw new Error(encodeError(`Unable to sort list of primitive values as they can only be string | number and must not be mixed. Received: ${typeof r}, ${typeof t}`,ERRORS.MIXED_OR_UNSUPPORTED_DATA_TYPES))},sortRecords=(e,r)=>(t,n)=>{if("string"==typeof t[e]&&"string"==typeof n[e])return __sortStringValues(t[e],n[e],r);if("number"==typeof t[e]&&"number"==typeof n[e])return __sortNumberValues(t[e],n[e],r);throw new Error(encodeError(`Unable to sort list of record values as they can only be string | number and must not be mixed. Received: ${typeof t[e]}, ${typeof n[e]}`,ERRORS.MIXED_OR_UNSUPPORTED_DATA_TYPES))},shuffleArray=e=>{canArrayBeShuffled(e);const r=e.slice();for(let e=r.length-1;e>0;e-=1){const t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}return r},splitArrayIntoBatches=(e,r)=>{if(!e.length)return[];if(!isIntegerValid(r,1))throw new Error(encodeError(`In order to split an array into batches, the batch size must be an integer greater than 0. Received: ${r}`,ERRORS.INVALID_BATCH_SIZE));const t=[];for(let n=0;n<e.length;n+=r)t.push(e.slice(n,n+r));return t},pickProps=(e,r)=>(validateObjectAndKeys(e,r),Object.fromEntries(r.map((r=>[r,e[r]])))),omitProps=(e,r)=>(validateObjectAndKeys(e,r),Object.fromEntries(Object.entries(e).filter((([e])=>!r.includes(e))))),isEqual=(e,r)=>stringifyJSONDeterministically(e)===stringifyJSONDeterministically(r),filterByQuery=(e,r,t)=>{if(!e.length||!r)return e;const n=buildNormalizedQueryTokens(r);if(!n.length)return e;const o=filterItemsByQueryTokens(e,n,t?.queryProp);return"number"==typeof t?.limit?o.slice(0,t.limit):o},delay=e=>new Promise((r=>{setTimeout(r,Math.round(1e3*e))})),retryAsyncFunction=async(e,r=[3,5])=>{try{return await e()}catch(t){if(0===r.length)throw t;return await delay(r[0]),retryAsyncFunction(e,r.slice(1))}};export{generateUUID,generateRandomString,generateRandomFloat,generateRandomInteger,generateSequence,sortPrimitives,sortRecords,shuffleArray,splitArrayIntoBatches,pickProps,omitProps,isEqual,filterByQuery,delay,retryAsyncFunction};
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Builds an array of normalized query tokens from a given query string.
|
|
3
|
-
* @param query
|
|
4
|
-
* @returns
|
|
3
|
+
* @param query The query string to be normalized and tokenized.
|
|
4
|
+
* @returns A normalized array of query tokens.
|
|
5
5
|
*/
|
|
6
|
-
declare const buildNormalizedQueryTokens: (query: string) => string[];
|
|
6
|
+
export declare const buildNormalizedQueryTokens: (query: string) => string[];
|
|
7
7
|
/**
|
|
8
8
|
* Stringifies a value so it can be compared in a case-insensitive manner.
|
|
9
|
-
* @param value
|
|
10
|
-
* @returns string
|
|
9
|
+
* @param value The value to be normalized.
|
|
10
|
+
* @returns A normalized string representation of the value.
|
|
11
11
|
*/
|
|
12
|
-
declare const normalizeItemValue: (value: unknown) => string;
|
|
13
|
-
export { buildNormalizedQueryTokens, normalizeItemValue };
|
|
12
|
+
export declare const normalizeItemValue: (value: unknown) => string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isArrayValid,isObjectValid}from"../validations/index.js";const buildNormalizedQueryTokens=e=>e.toLowerCase().split(" ").filter(Boolean)
|
|
1
|
+
import{isArrayValid,isObjectValid}from"../validations/index.js";export const buildNormalizedQueryTokens=e=>e.toLowerCase().split(" ").filter(Boolean);export const normalizeItemValue=e=>"string"==typeof e?e.toLowerCase():isObjectValid(e,!0)?Object.values(e).map(normalizeItemValue).join(" "):isArrayValid(e,!0)?e.map(normalizeItemValue).join(" "):null!=e?String(e).toLowerCase():"";
|
package/dist/utils/types.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
type ISortDirection = 'asc' | 'desc';
|
|
2
|
-
type IFilterByQueryOptions<T> = {
|
|
1
|
+
export type ISortDirection = 'asc' | 'desc';
|
|
2
|
+
export type IFilterByQueryOptions<T> = {
|
|
3
3
|
queryProp?: keyof T;
|
|
4
4
|
limit?: number;
|
|
5
5
|
};
|
|
6
|
-
export type { ISortDirection, IFilterByQueryOptions, };
|
package/dist/utils/utils.d.ts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Applies the filter to the items based on the query tokens and returns a filtered list.
|
|
3
|
-
* @param items
|
|
4
|
-
* @param queryTokens
|
|
5
|
-
* @param queryProp
|
|
6
|
-
* @returns
|
|
3
|
+
* @param items The list of items to be filtered.
|
|
4
|
+
* @param queryTokens The array of normalized query tokens to filter the items by.
|
|
5
|
+
* @param queryProp The property of the item to filter by, if not provided, the whole item will be used for filtering.
|
|
6
|
+
* @returns A filtered array of items that match the query tokens.
|
|
7
7
|
*/
|
|
8
|
-
declare const filterItemsByQueryTokens: <T>(items: T[], queryTokens: string[], queryProp: keyof T | undefined) => T[];
|
|
9
|
-
export { filterItemsByQueryTokens };
|
|
8
|
+
export declare const filterItemsByQueryTokens: <T>(items: T[], queryTokens: string[], queryProp: keyof T | undefined) => T[];
|
package/dist/utils/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{normalizeItemValue}from"./transformers.js";const filterItemsByQueryTokens=(e,r,t)=>e.filter((e=>{const o=normalizeItemValue("string"==typeof t?e[t]:e);return r.some((e=>o.includes(e)))}));
|
|
1
|
+
import{normalizeItemValue}from"./transformers.js";export const filterItemsByQueryTokens=(e,r,t)=>e.filter((e=>{const o=normalizeItemValue("string"==typeof t?e[t]:e);return r.some((e=>o.includes(e)))}));
|
|
@@ -4,14 +4,13 @@
|
|
|
4
4
|
* @throws
|
|
5
5
|
* - INVALID_OR_EMPTY_ARRAY: If the input is not an array or has less than 2 items.
|
|
6
6
|
*/
|
|
7
|
-
declare const canArrayBeShuffled: (input: unknown[]) => void;
|
|
7
|
+
export declare const canArrayBeShuffled: (input: unknown[]) => void;
|
|
8
8
|
/**
|
|
9
9
|
* Validates the input object and the keys to be picked/omitted.
|
|
10
|
-
* @param input
|
|
11
|
-
* @param propKeys
|
|
10
|
+
* @param input The object to be validated.
|
|
11
|
+
* @param propKeys The keys to be picked/omitted, which must be a non-empty array of strings.
|
|
12
12
|
* @throws
|
|
13
13
|
* - INVALID_OR_EMPTY_OBJECT: If the input is not a valid object or is empty.
|
|
14
14
|
* - INVALID_OR_EMPTY_ARRAY: If the keys are not a valid array or are empty.
|
|
15
15
|
*/
|
|
16
|
-
declare const validateObjectAndKeys: (input: unknown, propKeys: unknown) => void;
|
|
17
|
-
export { canArrayBeShuffled, validateObjectAndKeys };
|
|
16
|
+
export declare const validateObjectAndKeys: (input: unknown, propKeys: unknown) => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{encodeError}from"error-message-utils";import{ERRORS}from"../shared/errors.js";import{isArrayValid,isObjectValid}from"../validations/index.js";const canArrayBeShuffled=r=>{if(!Array.isArray(r)||r.length<=1)throw new Error(encodeError("For an array to be shuffled it must contain at least 2 items.",ERRORS.INVALID_OR_EMPTY_ARRAY))}
|
|
1
|
+
import{encodeError}from"error-message-utils";import{ERRORS}from"../shared/errors.js";import{isArrayValid,isObjectValid}from"../validations/index.js";export const canArrayBeShuffled=r=>{if(!Array.isArray(r)||r.length<=1)throw new Error(encodeError("For an array to be shuffled it must contain at least 2 items.",ERRORS.INVALID_OR_EMPTY_ARRAY))};export const validateObjectAndKeys=(r,e)=>{if(!isObjectValid(r))throw new Error(encodeError("The input must be a valid and non-empty object.",ERRORS.INVALID_OR_EMPTY_OBJECT));if(!isArrayValid(e))throw new Error(encodeError("The keys must be a valid and non-empty array of strings.",ERRORS.INVALID_OR_EMPTY_ARRAY))};
|
|
@@ -1,80 +1,81 @@
|
|
|
1
1
|
import { IUUIDVersion } from '../shared/types.js';
|
|
2
2
|
/**
|
|
3
3
|
* Verifies if a value is a valid string and its length is within a range (optional).
|
|
4
|
-
* @param value
|
|
5
|
-
* @param minLength?
|
|
6
|
-
* @param maxLength?
|
|
7
|
-
* @
|
|
4
|
+
* @param value The value to be validated.
|
|
5
|
+
* @param minLength? The minimum length of the string. If not provided, it will not check for a minimum length. Defaults to 1.
|
|
6
|
+
* @param maxLength? The maximum length of the string. If not provided, it will not check for a maximum length.
|
|
7
|
+
* @param disallowWhitespaceOnly? A boolean indicating whether strings that contain only whitespace should be considered invalid. Defaults to true.
|
|
8
|
+
* @returns A boolean indicating whether the value is a valid string and meets the length requirements (if provided).
|
|
8
9
|
*/
|
|
9
|
-
declare const isStringValid: (value: unknown, minLength?: number, maxLength?: number) => value is string;
|
|
10
|
+
export declare const isStringValid: (value: unknown, minLength?: number, maxLength?: number, disallowWhitespaceOnly?: boolean) => value is string;
|
|
10
11
|
/**
|
|
11
12
|
* Verifies if a value is a valid number and is within a range (optional). The minimum value
|
|
12
13
|
* defaults to Number.MIN_SAFE_INTEGER (-9007199254740991) while the maximum value defaults to
|
|
13
14
|
* Number.MAX_SAFE_INTEGER (9007199254740991).
|
|
14
|
-
* @param value
|
|
15
|
-
* @param min?
|
|
16
|
-
* @param max?
|
|
17
|
-
* @returns boolean
|
|
15
|
+
* @param value The value to be validated.
|
|
16
|
+
* @param min? The minimum value. If not provided, it will default to Number.MIN_SAFE_INTEGER.
|
|
17
|
+
* @param max? The maximum value. If not provided, it will default to Number.MAX_SAFE_INTEGER.
|
|
18
|
+
* @returns A boolean indicating whether the value is a valid number and within the specified range.
|
|
18
19
|
*/
|
|
19
|
-
declare const isNumberValid: (value: unknown, min?: number, max?: number) => value is number;
|
|
20
|
+
export declare const isNumberValid: (value: unknown, min?: number, max?: number) => value is number;
|
|
20
21
|
/**
|
|
21
22
|
* Verifies if a value is a valid integer and is within a range (optional). If a range is not
|
|
22
23
|
* provided, it will use the properties Number.MIN_SAFE_INTEGER & Number.MAX_SAFE_INTEGER.
|
|
23
|
-
* @param value
|
|
24
|
-
* @param min?
|
|
25
|
-
* @param max?
|
|
26
|
-
* @returns boolean
|
|
24
|
+
* @param value The value to be validated.
|
|
25
|
+
* @param min? The minimum value. If not provided, it will default to Number.MIN_SAFE_INTEGER.
|
|
26
|
+
* @param max? The maximum value. If not provided, it will default to Number.MAX_SAFE_INTEGER.
|
|
27
|
+
* @returns A boolean indicating whether the value is a valid integer and within the specified range.
|
|
27
28
|
*/
|
|
28
|
-
declare const isIntegerValid: (value: unknown, min?: number, max?: number) => value is number;
|
|
29
|
+
export declare const isIntegerValid: (value: unknown, min?: number, max?: number) => value is number;
|
|
29
30
|
/**
|
|
30
31
|
* Verifies if a value is a valid unix timestamp in milliseconds. The smallest value is set for
|
|
31
32
|
* the beginning of the Unix epoch (January 1st, 1970 - 14400000) while the largest value is based
|
|
32
33
|
* on the numeric limit established by JavaScript (9007199254740991).
|
|
33
|
-
* @param value
|
|
34
|
-
* @returns boolean
|
|
34
|
+
* @param value The value to be validated.
|
|
35
|
+
* @returns A boolean indicating whether the value is a valid unix timestamp in milliseconds.
|
|
35
36
|
*/
|
|
36
|
-
declare const isTimestampValid: (value: unknown) => value is number;
|
|
37
|
+
export declare const isTimestampValid: (value: unknown) => value is number;
|
|
37
38
|
/**
|
|
38
39
|
* Verifies if a value is a valid numeric string.
|
|
39
|
-
* @param value
|
|
40
|
-
* @returns boolean
|
|
40
|
+
* @param value The value to be validated.
|
|
41
|
+
* @returns A boolean indicating whether the value is a valid numeric string.
|
|
41
42
|
*/
|
|
42
|
-
declare const isNumeric: (value: string) => boolean;
|
|
43
|
+
export declare const isNumeric: (value: string) => boolean;
|
|
43
44
|
/**
|
|
44
45
|
* Verifies if a value is an actual object. It also validates if it has keys (optional).
|
|
45
|
-
* @param value
|
|
46
|
-
* @param allowEmpty?
|
|
47
|
-
* @returns boolean
|
|
46
|
+
* @param value The value to be validated.
|
|
47
|
+
* @param allowEmpty? A boolean indicating whether empty objects are allowed. Defaults to false.
|
|
48
|
+
* @returns A boolean indicating whether the value is a valid object and meets the key requirements (if provided).
|
|
48
49
|
*/
|
|
49
|
-
declare const isObjectValid: (value: unknown, allowEmpty?: boolean) => value is Record<string, any>;
|
|
50
|
+
export declare const isObjectValid: (value: unknown, allowEmpty?: boolean) => value is Record<string, any>;
|
|
50
51
|
/**
|
|
51
52
|
* Verifies if a value is an array. It also validates if it has elements inside (optional).
|
|
52
|
-
* @param value
|
|
53
|
-
* @param allowEmpty?
|
|
54
|
-
* @returns boolean
|
|
53
|
+
* @param value The value to be validated.
|
|
54
|
+
* @param allowEmpty? A boolean indicating whether empty arrays are allowed. Defaults to false.
|
|
55
|
+
* @returns A boolean indicating whether the value is a valid array and meets the element requirements (if provided).
|
|
55
56
|
*/
|
|
56
|
-
declare const isArrayValid: (value: unknown, allowEmpty?: boolean) => value is Array<any>;
|
|
57
|
+
export declare const isArrayValid: (value: unknown, allowEmpty?: boolean) => value is Array<any>;
|
|
57
58
|
/**
|
|
58
59
|
* Verifies if a value is a valid email address.
|
|
59
60
|
* Important: when providing forbiddenExtensions, ensure to include the dot (.) at the beginning.
|
|
60
61
|
* For example, to forbid .con, use ['.con'].
|
|
61
|
-
* @param value
|
|
62
|
-
* @param forbiddenExtensions?
|
|
63
|
-
* @returns boolean
|
|
62
|
+
* @param value The value to be validated.
|
|
63
|
+
* @param forbiddenExtensions? An array of forbidden email extensions. Defaults to ['.con'].
|
|
64
|
+
* @returns A boolean indicating whether the value is a valid email address and does not have a forbidden extension.
|
|
64
65
|
*/
|
|
65
|
-
declare const isEmailValid: (value: unknown, forbiddenExtensions?: string[]) => value is string;
|
|
66
|
+
export declare const isEmailValid: (value: unknown, forbiddenExtensions?: string[]) => value is string;
|
|
66
67
|
/**
|
|
67
68
|
* Verifies if a slug meets the following requirements:
|
|
68
|
-
* - Accepts any
|
|
69
|
+
* - Accepts any lowercase alpha characters
|
|
69
70
|
* - Accepts any digits
|
|
70
71
|
* - Accepts - , . and/or _
|
|
71
72
|
* - Meets a length range (Defaults to 2 - 16)
|
|
72
|
-
* @param value
|
|
73
|
-
* @param minLength?
|
|
74
|
-
* @param maxLength?
|
|
75
|
-
* @returns boolean
|
|
73
|
+
* @param value The value to be validated.
|
|
74
|
+
* @param minLength? The minimum length of the slug. Defaults to 2.
|
|
75
|
+
* @param maxLength? The maximum length of the slug. Defaults to 16.
|
|
76
|
+
* @returns A boolean indicating whether the value is a valid slug.
|
|
76
77
|
*/
|
|
77
|
-
declare const isSlugValid: (value: unknown, minLength?: number, maxLength?: number) => value is string;
|
|
78
|
+
export declare const isSlugValid: (value: unknown, minLength?: number, maxLength?: number) => value is string;
|
|
78
79
|
/**
|
|
79
80
|
* Verifies if a password meets the following requirements:
|
|
80
81
|
* - Meets a length range (Defaults to 8 - 2048)
|
|
@@ -82,58 +83,57 @@ declare const isSlugValid: (value: unknown, minLength?: number, maxLength?: numb
|
|
|
82
83
|
* - At least one lowercase letter
|
|
83
84
|
* - At least one number
|
|
84
85
|
* - At least one special character
|
|
85
|
-
* @param value
|
|
86
|
-
* @param minLength?
|
|
87
|
-
* @param maxLength?
|
|
88
|
-
* @returns boolean
|
|
86
|
+
* @param value The value to be validated.
|
|
87
|
+
* @param minLength? The minimum length of the password. Defaults to 8.
|
|
88
|
+
* @param maxLength? The maximum length of the password. Defaults to 2048.
|
|
89
|
+
* @returns A boolean indicating whether the value is a valid password.
|
|
89
90
|
*/
|
|
90
|
-
declare const isPasswordValid: (value: unknown, minLength?: number, maxLength?: number) => value is string;
|
|
91
|
+
export declare const isPasswordValid: (value: unknown, minLength?: number, maxLength?: number) => value is string;
|
|
91
92
|
/**
|
|
92
93
|
* Verifies if a value has the correct OTP Secret Format.
|
|
93
|
-
* @param value
|
|
94
|
-
* @returns boolean
|
|
94
|
+
* @param value The value to be validated.
|
|
95
|
+
* @returns A boolean indicating whether the value is a valid OTP secret.
|
|
95
96
|
*/
|
|
96
|
-
declare const isOTPSecretValid: (value: unknown) => value is string;
|
|
97
|
+
export declare const isOTPSecretValid: (value: unknown) => value is string;
|
|
97
98
|
/**
|
|
98
99
|
* Verifies if a value has the correct OTP Token Format.
|
|
99
|
-
* @param value
|
|
100
|
-
* @returns boolean
|
|
100
|
+
* @param value The value to be validated.
|
|
101
|
+
* @returns A boolean indicating whether the value is a valid OTP token.
|
|
101
102
|
*/
|
|
102
|
-
declare const isOTPTokenValid: (value: unknown) => value is string;
|
|
103
|
+
export declare const isOTPTokenValid: (value: unknown) => value is string;
|
|
103
104
|
/**
|
|
104
105
|
* Verifies if a value has a correct JWT Format:
|
|
105
106
|
* [Base64-URL Encoded Header].[Base64-URL Encoded Payload].[Signature]
|
|
106
|
-
* @param value
|
|
107
|
-
* @returns boolean
|
|
107
|
+
* @param value The value to be validated.
|
|
108
|
+
* @returns A boolean indicating whether the value is a valid JWT.
|
|
108
109
|
*/
|
|
109
|
-
declare const isJWTValid: (value: unknown) => value is string;
|
|
110
|
+
export declare const isJWTValid: (value: unknown) => value is string;
|
|
110
111
|
/**
|
|
111
112
|
* Verifies if a value has a valid Authorization Header format based on the RFC6750. Example:
|
|
112
113
|
* Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9TJV...r7E20RMHrHDcEfxjoYZgeFONFh7HgQ
|
|
113
114
|
* More info:
|
|
114
115
|
* - https://stackoverflow.com/questions/33265812/best-http-authorization-header-type-for-jwt
|
|
115
116
|
* - https://www.rfc-editor.org/rfc/rfc6750
|
|
116
|
-
* @param value
|
|
117
|
-
* @returns boolean
|
|
117
|
+
* @param value The value to be validated.
|
|
118
|
+
* @returns A boolean indicating whether the value is a valid Authorization header.
|
|
118
119
|
*/
|
|
119
|
-
declare const isAuthorizationHeaderValid: (value: unknown) => value is string;
|
|
120
|
+
export declare const isAuthorizationHeaderValid: (value: unknown) => value is string;
|
|
120
121
|
/**
|
|
121
122
|
* Verifies if a value complies with semantic versioning.
|
|
122
|
-
* @param value
|
|
123
|
-
* @returns boolean
|
|
123
|
+
* @param value The value to be validated.
|
|
124
|
+
* @returns A boolean indicating whether the value is a valid semantic version.
|
|
124
125
|
*/
|
|
125
|
-
declare const isSemverValid: (value: unknown) => value is string;
|
|
126
|
+
export declare const isSemverValid: (value: unknown) => value is string;
|
|
126
127
|
/**
|
|
127
128
|
* Verifies if a value is a valid URL.
|
|
128
|
-
* @param value
|
|
129
|
-
* @returns boolean
|
|
129
|
+
* @param value The value to be validated.
|
|
130
|
+
* @returns A boolean indicating whether the value is a valid URL.
|
|
130
131
|
*/
|
|
131
|
-
declare const isURLValid: (value: unknown) => value is string;
|
|
132
|
+
export declare const isURLValid: (value: unknown) => value is string;
|
|
132
133
|
/**
|
|
133
134
|
* Verifies if a value is a valid UUID and that it matches a specific version.
|
|
134
|
-
* @param value
|
|
135
|
-
* @param version
|
|
136
|
-
* @returns boolean
|
|
135
|
+
* @param value The value to be validated.
|
|
136
|
+
* @param version The UUID version to be validated against.
|
|
137
|
+
* @returns A boolean indicating whether the value is a valid UUID of the specified version.
|
|
137
138
|
*/
|
|
138
|
-
declare const isUUIDValid: (value: unknown, version: IUUIDVersion) => value is string;
|
|
139
|
-
export { isStringValid, isNumberValid, isIntegerValid, isTimestampValid, isNumeric, isObjectValid, isArrayValid, isEmailValid, isSlugValid, isPasswordValid, isOTPSecretValid, isOTPTokenValid, isJWTValid, isAuthorizationHeaderValid, isSemverValid, isURLValid, isUUIDValid, };
|
|
139
|
+
export declare const isUUIDValid: (value: unknown, version: IUUIDVersion) => value is string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{version as uuidVersion,validate as uuidValidate}from"uuid";const isStringValid=(
|
|
1
|
+
import{version as uuidVersion,validate as uuidValidate}from"uuid";export const isStringValid=(t,e=1,i,r=!0)=>"string"==typeof t&&(void 0===e||t.length>=e)&&(void 0===i||t.length<=i)&&(!r||t.trim().length>0);export const isNumberValid=(t,e=Number.MIN_SAFE_INTEGER,i=Number.MAX_SAFE_INTEGER)=>"number"==typeof t&&t>=e&&t<=i;export const isIntegerValid=(t,e,i)=>isNumberValid(t,e,i)&&Number.isInteger(t);export const isTimestampValid=t=>isIntegerValid(t,144e5);export const isNumeric=t=>"string"==typeof t&&/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/.test(t);export const isObjectValid=(t,e)=>null!==t&&"object"==typeof t&&!Array.isArray(t)&&(e||Object.keys(t).length>0);export const isArrayValid=(t,e)=>Array.isArray(t)&&(e||t.length>0);export const isEmailValid=(t,e=[".con"])=>{if(!isStringValid(t,5,200))return!1;const i=t.toLowerCase();return/^[a-z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/.test(i)&&!e.some((t=>i.endsWith(t)))};export const isSlugValid=(t,e=2,i=16)=>isStringValid(t,e,i)&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t);export const isPasswordValid=(t,e=8,i=2048)=>isStringValid(t,e,i)&&/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_])[A-Za-z\d\W_]+$/.test(t);export const isOTPSecretValid=t=>"string"==typeof t&&/^[0-9a-zA-Z]{16,64}$/.test(t);export const isOTPTokenValid=t=>"string"==typeof t&&/^[0-9]{6}$/.test(t);export const isJWTValid=t=>"string"==typeof t&&/^[A-Za-z0-9-_]{2,1000}\.[A-Za-z0-9-_]{2,1000}\.[A-Za-z0-9-_]{2,1000}$/.test(t);export const isAuthorizationHeaderValid=t=>"string"==typeof t&&/^Bearer [A-Za-z0-9-_]{2,1000}\.[A-Za-z0-9-_]{2,1000}\.[A-Za-z0-9-_]{2,1000}$/.test(t);export const isSemverValid=t=>"string"==typeof t&&/^[0-9]{1,5}\.[0-9]{1,5}\.[0-9]{1,5}$/.test(t);export const isURLValid=t=>{if("string"!=typeof t)return!1;try{new URL(t);return!0}catch(t){return!1}};export const isUUIDValid=(t,e)=>"string"==typeof t&&uuidValidate(t)&&uuidVersion(t)===e;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "web-utils-kit",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.1",
|
|
4
4
|
"description": "The web-utils-kit package provides a collection of well-tested and thoroughly documented utility functions for various web development needs. Each function adheres to a strict coding style and best practices to ensure consistency and maintainability.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"vitest": "3.2.4"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"error-message-utils": "1.1
|
|
49
|
+
"error-message-utils": "1.2.1",
|
|
50
50
|
"uuid": "11.0.3"
|
|
51
51
|
}
|
|
52
52
|
}
|