@resk/core
Version:
An innovative TypeScript framework that empowers developers to build applications with a fully decorator-based architecture for efficient resource management. By combining the power of decorators with a resource-oriented design, DecorRes enhances code cla
399 lines (394 loc) • 18.3 kB
TypeScript
import { IInputFormatterMask, IInputFormatterMaskArray, IInputFormatterMaskOptions, IInputFormatterOptions, IInputFormatterResult, IInputFormatterMaskResult, IInputFormatterMaskWithValidation } from "./types";
import "../utils/numbers";
import { PhoneNumber, PhoneNumberFormat } from "google-libphonenumber";
import { ICountryCode } from "../countries/index";
export * from "./types";
/***
InputFormatter class is used to format the value to the desired format
*/
export default class InputFormatter {
/**
* @description
* Formats a value according to the provided options defined in the IInputFormatterOptions interface.
*
* This function takes an input value and formats it based on the specified type, format function,
* and other parameters. It returns an object containing the formatted value and other relevant
* information, such as whether the value can be a decimal.
*
* @param {IInputFormatterOptions} options - The options for formatting, adhering to the IInputFormatterOptions interface.
* @param {boolean} returnObject - Optional. If true, the function will return an object instead of a formatted string.
*
* @returns {IInputFormatterResult} - An object containing:
* - formattedValue: The formatted output based on the provided options.
* - isDecimalType: A boolean indicating if the value can be treated as a decimal.
* - value: The original input value.
* - format: The formatting function or type used.
* - parsedValue: The parsed numeric value.
* - decimalValue: The decimal representation of the value, defaulting to 0 if not applicable.
*
* Example:
* ```typescript
* const options = {
* value: "123.45",
* type: "decimal",
* format: (opts) => `${opts.value} formatted`,
* };
* const result = formatValue(options);
* console.log(result);
* // Output: {
* // formattedValue: "123.45 formatted",
* // isDecimalType: true,
* // value: "123.45",
* // format: [Function],
* // parsedValue: 123.45,
* // decimalValue: 123.45
* // }
* ```
*/
static formatValue({ value, type, format, dateFormat, phoneCountryCode, abreviateNumber, ...rest }: IInputFormatterOptions): IInputFormatterResult;
/**
* Gets the dial code for a given country code.
*
* @param {ICountryCode} code The country code.
* @returns {string} The dial code for the given country code, or an empty string if the country code is not found.
*
* @example
* ```typescript
* console.log(CountriesManager.getCountryDialCode('US')); // '+1'
* ```
*/
static getCountryDialCode(countryCode: ICountryCode): string;
/**
* @description
* Formats a value based on the provided options and returns the formatted string.
*
* This function serves as a simpler interface for formatting values. It internally calls
* the `formatValue` function to obtain the formatted value and then returns it
* as a string. This is useful for scenarios where only the formatted string is needed.
*
* @param options - The options for formatting, adhering to the IInputFormatterOptions interface.
* @ param returnObject - Optional. If true, the function will return an object instead of a formatted string.
*
* @returns {string} - The formatted value as a string.
*
* Example:
* ```typescript
* const options = {
* value: "123.45",
* type: "decimal",
* format: (opts) => `${opts.value} formatted`,
* };
* const formattedString = formatValue(options);
* console.log(formattedString);
* // Output: "123.45 formatted"
* ```
*/
static formatValueAsString(options: IInputFormatterOptions): string;
/***
* Check if a given mask is valid or not
* @param {IInputFormatterMask}, the input mask to check
* @return {boolean} Wheather the mask is valid or not
*/
static isValidMask(mask?: IInputFormatterMask): mask is IInputFormatterMaskArray | ((options: IInputFormatterOptions) => IInputFormatterMaskArray);
/**
* Parses a given value and converts it into a decimal number.
*
* This function takes a value as input and performs the following checks:
* - If the value is already a number, it returns the value directly.
* - If the value is undefined, null, or not a string, it returns 0.
* - If the value is a string, it trims whitespace, replaces commas with periods,
* and removes any spaces before converting it to a float.
*
* ### Parameters:
* - `value`:
* - **Type**: `any`
* - The value to be parsed. This can be a number, string, or any other type.
* The function will attempt to convert it to a decimal number.
*
* ### Returns:
* - **Type**: `number`
* - The decimal representation of the input value. If the input is invalid
* (e.g., undefined, null, or not a valid string), it returns 0.
*
* ### Example Usage:
* ```typescript
* const decimal1 = parseDecimal("1,234.56"); // Returns: 1234.56
* const decimal2 = parseDecimal(789); // Returns: 789
* const decimal3 = parseDecimal(null); // Returns: 0
* const decimal4 = parseDecimal("invalid"); // Returns: 0
* ```
*/
static parseDecimal: (value: any) => number;
/***
Normalize a value to a string.
This method takes a value and a facultative decimal separator. It removes leading and trailing
whitespace, commas. It also replaces the comma with the decimal separator.
If the value is a number, it will be converted to a string.
@param {any} value - The value to normalize
@param {string} decimalSeparator - The decimal separator to use
*/
static normalizeNumber(value: any, decimalSeparator?: string): string;
/***
* Check if the value ends with a decimal separator
* @param {any} value - The value to Check
* @returns {boolean} Whether the value ends with a decimal separator
*/
static endsWithDecimalSeparator: (value: any) => boolean;
/**
* Formats a value with a mask.
*
* This method takes an options object with a value, mask, and other settings, and returns an object with the masked, unmasked, and obfuscated values, as well as the original mask array.
*
* @param options The options object with the value, mask, and other settings.
* @returns An object with the masked, unmasked, and obfuscated values, as well as the original mask array.
*
* @example
* ```typescript
* const options: IInputFormatterMaskOptions = {
* value: '12345',
* mask: ['(', /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
* obfuscationCharacter: '*',
* };
* const result = formatWithMask(options);
* console.log(result);
* // Output:
* ```
*
*
* @license This code is adapted from [Original Repository Name] (https://github.com/CaioQuirinoMedeiros/react-native-mask-input).
*
* Copyright (c) [2025] [CaioQuirinoMedeiros]
* Licensed under the MIT License (https://github.com/CaioQuirinoMedeiros/react-native-mask-input/blob/main/LICENSE)
*
*/
static formatWithMask(options: IInputFormatterMaskOptions): IInputFormatterMaskResult;
/***
* Predefined masks for common moment formats.
* The keys of the object are the moment format strings, and the values are arrays of regular expressions or strings that define the expected format of the input value.
*/
static MOMENT_MASKS_MAP: {
YYYY: any[];
YY: any[];
MM: any[];
M: (string | RegExp)[][];
MMMM: any[];
MMM: any[];
DD: any[];
D: (string | RegExp)[][];
HH: any[];
H: (string | RegExp)[][];
hh: any[];
h: (string | RegExp)[][];
mm: any[];
m: (string | RegExp)[][];
ss: any[];
s: (string | RegExp)[][];
SSS: any[];
Z: RegExp[];
ZZ: RegExp[];
A: string[];
a: string[];
};
/***
* A map of moment separators and their corresponding characters.
* The keys of the object are the separators, and the values are the corresponding characters.
*/
static MOMENT_SEPARATOR_MAP: {
"/": string;
"-": string;
".": string;
" ": string;
":": string;
T: string;
};
/***
* Creates a date mask, based on the specified moment format.
* @param {string} momentDateFormat - The moment format string.
* @returns {IInputFormatterMaskWithValidation}} - An object containing the mask and a validation function.
*/
static createDateMask(momentDateFormat: string): IInputFormatterMaskWithValidation;
/***
* A mask for single facilitative space.
* @description A mask for a single facilitative space.
*/
static SINGLE_SPACE_MASK: string;
/**
* Generates a phone number mask based on the country code.
* @param countryCode - The country code (e.g., "US", "FR", "IN").
* @param {PhoneNumberFormat} [format] - The format to use for the phone number mask. Defaults to PhoneNumberFormat.INTERNATIONAL.
* @returns {IInputFormatterMaskWithValidation} The phone number mask, an array of mask elements (strings or regexes) representing the phone number format..
*/
static createPhoneNumberMask(countryCode: ICountryCode, format?: PhoneNumberFormat): IInputFormatterMaskWithValidation;
/****
* Gets the phone number example for the given country code.
* @param countryCode The country code.
* @returns {PhoneNumber|null} The phone number example for the given country code, or null if no example is found.
*/
static getPhoneNumberExample(countryCode: ICountryCode): PhoneNumber | null;
/**
* Creates a phone number mask based on the provided phone number example and country code.
* Uses google-libphonenumber to ensure accurate regional formatting
This function takes a phone number example and an optional country code as input. It creates a mask based on the example number and the country code.
The function returns an object with a mask and a validation function. The mask is an array of mask elements, where each element represents a character or a regex pattern. The validation function checks if the input value is a valid phone number based on the provided country code.
If the country code is not provided, the default country code is used. If no example number is found for the provided country code, the function returns an empty mask and a validation function that always returns false.
@param {string} phoneNumberExample - The phone number example to use for the mask.
@param {ICountryCode} [countryCode] - The country code to use for the mask. If not provided, the default country code is used.
@returns {IInputFormatterMaskWithValidation} An object containing the mask and a validation function.
*/
static createPhoneNumberMaskFromExample(phoneNumber: string, countryCode?: ICountryCode, format?: PhoneNumberFormat): IInputFormatterMaskWithValidation;
/**
* Predefined masks for common input formats.
*
* This object contains a set of predefined masks for common input formats such as date, time, date-time, and credit card numbers.
* Each mask is an array of regular expressions or strings that define the expected format of the input value.
* ```
*/
static MASKS_WITH_VALIDATIONS: {
/**
* Mask for date input format.
*
* This mask expects the input value to be in the format of `YYYY-MM-DD` or `YYYY/MM/DD` or `YYYY.MM.DD`.
*/
readonly DATE: IInputFormatterMaskWithValidation;
/**
* Mask for time input format.
*
* This mask expects the input value to be in the format of `HH:MM:SS` or `HHHMMSS`.
*/
readonly TIME: IInputFormatterMaskWithValidation;
readonly DATE_TIME: IInputFormatterMaskWithValidation;
CREDIT_CARD: {
mask: IInputFormatterMaskArray;
validate: (value: string) => boolean;
};
};
/***
* Parse a phone number using the google-libphonenumber library.
* @param {string} number - The phone number to parse.
* @param {ICountryCode} [countryCode] - The country code to use for parsing the phone number.
* @returns {PhoneNumber | null} The parsed phone number, or null if the parsing fails.
* @example
* // Parse a phone number
* const phoneNumber = InputFormatter.parsePhoneNumber('+1 (555) 123-4567');
* console.log(phoneNumber); // Output: PhoneNumber { countryCode: 'US', nationalNumber: '5551234567', ...}
*
*/
static parsePhoneNumber(number: string, countryCode?: ICountryCode): PhoneNumber | null;
/***
* Prefix a phone number with a dial code.
* @param {string} phoneNumber - The phone number to prefix.
* @param {string} dialCode - The dial code to prefix the phone number with.
* @returns {string} The prefixed phone number.
* @example
* // Prefix a phone number with a dial code
* const prefixedPhoneNumber = InputFormatter.prefixPhoneNumberWithDialCode('5551234567', '+1');
* console.log(prefixedPhoneNumber); // Output: +15551234567
*/
static prefixPhoneNumberWithDialCode(phoneNumber: string, dialCode: string): string;
/**
* Validates a phone number using the google-libphonenumber library.
*
* @param {string} phoneNumber The phone number to validate.
* @param {ICountryCode}, The country code to use for validation. If not provided, the default country code will be used.
* @returns True if the phone number is valid, false otherwise.
* @throws Error if there's an issue parsing the phone number.
* @example
* ```typescript
* const isValid = isValidPhoneNumber ('+1 202 555 0144');
* console.log(isValid); // Output: true
* ```
*/
static isValidPhoneNumber(phoneNumber: string, countryCode?: ICountryCode): phoneNumber is string;
/***
* An utility function that formats phone numbers using Google's libphonenumber library.
* @example
* // Returns "+1 650 253 0000"
* InputFormatter.formatPhoneNumber("6502530000", "US");
*
* @example
* // Returns "+44 20 7031 3000"
* InputFormatter.formatPhoneNumber("2070313000", "GB");
*
* @example
* // Returns "+33 1 42 68 53 00"
* InputFormatter.formatPhoneNumber("+33142685300");
*
* @example
* // Returns null (invalid phone number)
* InputFormatter.formatPhoneNumber("123", "US");
* Formats a phone number using the google-libphonenumber library.
* @param {string} phoneNumber - The phone number to format (can be in various formats)
* @param {ICountryCode}, - ISO 3166-1 alpha-2 country code to use if the phone number doesn't have a country code
* @returns The formatted international phone number or null if parsing fails
*
*/
static formatPhoneNumber(phoneNumber: string, countryCode?: ICountryCode): string | null;
/***
* Cleans the phone number string by removing leading and trailing whitespace,
* replacing dots and hyphens with empty strings, and trimming the string.
*
* @param phoneNumber - The phone number string to Clean
* @returns The cleaned phone number string
*/
static cleanPhoneNumber(phoneNumber: string): string;
/**
* Extracts the country dial code from international phone numbers.
* Supports formats based on ITU-T E.164 and common regional variations.
*
* Supported formats:
* 1. E.164 format: +[country code][area code][local number]
* Example: +12125551234
*
* 2. International format with spaces/separators:
* - +[country code] [area code] [local number]
* - +[country code].[area code].[local number]
* - +[country code]-[area code]-[local number]
* Examples:
* - +1 212 555 1234
* - +44.20.7123.4567
* - +81-3-1234-5678
*
* 3. International format with parentheses:
* - +[country code] ([area code]) [local number]
* - ([country code]) [area code] [local number]
* Examples:
* - +1 (212) 555-1234
* - (44) 20 7123 4567
*
* 4. 00 prefix format (common in Europe):
* - 00[country code][remainder]
* Example: 00441234567890
*
* 5. Regional formats:
* - 011[country code] (US/Canada international prefix)
* - 010[country code] (Japan international prefix)
*
* @param phoneNumber - The phone number string to extract the dial code from
* @param countryCode - The country code to use for extracting the dial code
* @returns The dial code with + prefix, or null if no valid code is found
*/
static extractDialCodeFromPhoneNumber(phoneNumber: string, countryCode?: ICountryCode): string;
/***
* Check if the provided number is a valid numeric string.
* @param {string} n The number to check.
* @returns {boolean} True if the number is a valid numeric string, false otherwise.
* @example
* ```typescript
* console.log(isNumericString('123')); // Output: true
* console.log(isNumericString('abc')); // Output: false
* ```
*/
static isNumericString(n: string): boolean;
/***
* Extracts the numeric part of a phone number string.
* @param {string} str The phone number string.
* @returns {string} The numeric part of the phone number string.
* @example
* ```typescript
* console.log(extractNumbersFromString('+1 202 555 0144')); // Output: 2025550144
* console.log(extractNumbersFromString('+1 202 555 0144')); // Output: 2025550144
* console.log(extractNumbersFromString('2025550144')); // Output: 2025550144
* ```
*/
static extractNumbersFromString(str: string): string;
}