@arkyn/shared 2.0.1-beta.0 → 2.0.1-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/formats/formatDate.d.ts +43 -0
  2. package/dist/formats/formatDate.d.ts.map +1 -0
  3. package/dist/formats/formatDate.js +77 -0
  4. package/dist/formats/formatJsonObject.d.ts +33 -0
  5. package/dist/formats/formatJsonObject.d.ts.map +1 -0
  6. package/dist/formats/formatJsonObject.js +90 -0
  7. package/dist/formats/formatJsonString.d.ts +39 -0
  8. package/dist/formats/formatJsonString.d.ts.map +1 -0
  9. package/dist/formats/formatJsonString.js +46 -0
  10. package/dist/formats/formatToCep.d.ts +29 -0
  11. package/dist/formats/formatToCep.d.ts.map +1 -0
  12. package/dist/formats/formatToCep.js +34 -0
  13. package/dist/formats/formatToCnpj.d.ts +30 -0
  14. package/dist/formats/formatToCnpj.d.ts.map +1 -0
  15. package/dist/formats/formatToCnpj.js +35 -0
  16. package/dist/formats/formatToCpf.d.ts +30 -0
  17. package/dist/formats/formatToCpf.d.ts.map +1 -0
  18. package/dist/formats/formatToCpf.js +35 -0
  19. package/dist/formats/formatToCpfCnpj.d.ts +24 -0
  20. package/dist/formats/formatToCpfCnpj.d.ts.map +1 -0
  21. package/dist/formats/formatToCpfCnpj.js +33 -0
  22. package/dist/formats/formatToCurrency.d.ts +29 -0
  23. package/dist/formats/formatToCurrency.d.ts.map +1 -0
  24. package/dist/formats/formatToCurrency.js +41 -0
  25. package/dist/formats/formatToEllipsis.d.ts +16 -0
  26. package/dist/formats/formatToEllipsis.d.ts.map +1 -0
  27. package/dist/formats/formatToEllipsis.js +21 -0
  28. package/dist/formats/formatToHiddenDigits.d.ts +32 -0
  29. package/dist/formats/formatToHiddenDigits.d.ts.map +1 -0
  30. package/dist/formats/formatToHiddenDigits.js +60 -0
  31. package/dist/formats/formatToPhone.d.ts +34 -0
  32. package/dist/formats/formatToPhone.d.ts.map +1 -0
  33. package/dist/formats/formatToPhone.js +131 -0
  34. package/dist/generators/generateColorByString.d.ts +15 -0
  35. package/dist/generators/generateColorByString.d.ts.map +1 -0
  36. package/dist/generators/generateColorByString.js +25 -0
  37. package/dist/generators/generateId.d.ts +28 -0
  38. package/dist/generators/generateId.d.ts.map +1 -0
  39. package/dist/generators/generateId.js +29 -0
  40. package/dist/generators/generateSlug.d.ts +17 -0
  41. package/dist/generators/generateSlug.d.ts.map +1 -0
  42. package/dist/generators/generateSlug.js +25 -0
  43. package/dist/index.d.ts +23 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +22 -0
  46. package/dist/regex/index.d.ts +6 -0
  47. package/dist/regex/index.d.ts.map +1 -0
  48. package/dist/regex/index.js +4 -0
  49. package/dist/services/calculateCardInstallment.d.ts +33 -0
  50. package/dist/services/calculateCardInstallment.d.ts.map +1 -0
  51. package/dist/services/calculateCardInstallment.js +55 -0
  52. package/dist/services/maskSensitiveData.d.ts +26 -0
  53. package/dist/services/maskSensitiveData.d.ts.map +1 -0
  54. package/dist/services/maskSensitiveData.js +60 -0
  55. package/dist/services/removeCurrencySymbols.d.ts +20 -0
  56. package/dist/services/removeCurrencySymbols.d.ts.map +1 -0
  57. package/dist/services/removeCurrencySymbols.js +23 -0
  58. package/dist/services/removeNonNumeric.d.ts +15 -0
  59. package/dist/services/removeNonNumeric.d.ts.map +1 -0
  60. package/dist/services/removeNonNumeric.js +16 -0
  61. package/dist/services/truncateLargeFields.d.ts +32 -0
  62. package/dist/services/truncateLargeFields.d.ts.map +1 -0
  63. package/dist/services/truncateLargeFields.js +57 -0
  64. package/dist/validations/validateCpf.d.ts +24 -0
  65. package/dist/validations/validateCpf.d.ts.map +1 -0
  66. package/dist/validations/validateCpf.js +56 -0
  67. package/dist/validations/validateDate.d.ts +29 -0
  68. package/dist/validations/validateDate.d.ts.map +1 -0
  69. package/dist/validations/validateDate.js +73 -0
  70. package/dist/validations/validatePhone.d.ts +29 -0
  71. package/dist/validations/validatePhone.d.ts.map +1 -0
  72. package/dist/validations/validatePhone.js +44 -0
  73. package/package.json +1 -1
  74. package/src/regex/index.ts +2 -35
  75. package/tsconfig.json +2 -2
  76. package/src/formats/__test__/formatDate.spec.ts +0 -88
  77. package/src/formats/__test__/formatJsonObject.spec.ts +0 -87
  78. package/src/formats/__test__/formatJsonString.spec.ts +0 -83
  79. package/src/formats/__test__/formatToCep.spec.ts +0 -37
  80. package/src/formats/__test__/formatToCnpj.spec.ts +0 -35
  81. package/src/formats/__test__/formatToCpfCnpj.spec.ts +0 -43
  82. package/src/formats/__test__/formatToCurrency.spec.ts +0 -50
  83. package/src/formats/__test__/formatToEllipsis.spec.ts +0 -44
  84. package/src/formats/__test__/formatToHiddenDigits.spec.ts +0 -58
  85. package/src/formats/__test__/formatToPhone.spec.ts +0 -58
  86. package/src/generators/__test__/generateColorByString.spec.ts +0 -37
  87. package/src/generators/__test__/generateId.spec.ts +0 -44
  88. package/src/generators/__test__/generateSlug.spec.ts +0 -47
  89. package/src/services/__test__/calculateCardInstallment.spec.ts +0 -87
  90. package/src/services/__test__/maskSensitiveData.spec.ts +0 -102
  91. package/src/services/__test__/removeCurrencySymbols.spec.ts +0 -41
  92. package/src/services/__test__/removeNonNumeric.spec.ts +0 -33
  93. package/src/services/__test__/truncateLargeFields.spec.ts +0 -90
  94. package/src/validations/__test__/validateCpf.spec.ts +0 -38
  95. package/src/validations/__test__/validateDate.spec.ts +0 -81
  96. package/src/validations/__test__/validatePhone.spec.ts +0 -39
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Calculates the installment price and total price for a card payment plan.
3
+ *
4
+ * @remarks
5
+ * **Important:** When the interest amount (`fees`) is equal to 0 or the number of installments (`numberInstallments`) is equal to 1, no interest will be charged.
6
+ *
7
+ * @throws Will throw an error if the number of installments is less than or equal to 0.
8
+ * @throws Will throw an error if the fees are less than 0.
9
+ *
10
+ * @param props - The input parameters for the calculation.
11
+ * @param props.cashPrice - The total cash price of the product or service.
12
+ * @param props.numberInstallments - The number of installments for the payment plan.
13
+ * @param props.fees - The interest rate per installment (default is 0.0349).
14
+ *
15
+ * @returns An object containing:
16
+ * - `totalPrice`: The total price to be paid, rounded to two decimal places.
17
+ * - `installmentPrice`: The price of each installment, rounded to two decimal places.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const result = calculateCardInstallment({
22
+ * cashPrice: 1000,
23
+ * numberInstallments: 12,
24
+ * fees: 0.02,
25
+ * });
26
+ * console.log(result);
27
+ * // Output: { totalPrice: 1124.62, installmentPrice: 93.72 }
28
+ * ```
29
+ */
30
+ const calculateCardInstallment = (props) => {
31
+ const { cashPrice, numberInstallments, fees = 0.0349 } = props;
32
+ if (fees === 0 || numberInstallments === 1) {
33
+ return {
34
+ totalPrice: cashPrice,
35
+ installmentPrice: cashPrice / numberInstallments,
36
+ };
37
+ }
38
+ if (numberInstallments <= 0) {
39
+ throw new Error("Number of installments must be greater than 0");
40
+ }
41
+ if (fees < 0) {
42
+ throw new Error("Fees must be greater than or equal to 0");
43
+ }
44
+ let installmentPrice = 0;
45
+ let totalPrice = 0;
46
+ let numerator = Math.pow(1 + fees, numberInstallments) * fees;
47
+ let denominator = Math.pow(1 + fees, numberInstallments) - 1;
48
+ installmentPrice = cashPrice * (numerator / denominator);
49
+ totalPrice = numberInstallments * installmentPrice;
50
+ return {
51
+ totalPrice: +totalPrice.toFixed(2),
52
+ installmentPrice: +installmentPrice.toFixed(2),
53
+ };
54
+ };
55
+ export { calculateCardInstallment };
@@ -0,0 +1,26 @@
1
+ import type { MaskSensitiveDataFunction } from "@arkyn/types";
2
+ /**
3
+ * Masks sensitive data in a JSON string by replacing the values of specified keys with "****".
4
+ *
5
+ * @param jsonString - The JSON string to be processed.
6
+ * @param sensitiveKeys - An array of keys whose values should be masked. Defaults to `["password", "confirmPassword", "creditCard"]`.
7
+ * @returns A JSON string with sensitive data masked. If the input is not a valid JSON string, it returns the original string.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * const jsonString = JSON.stringify({
12
+ * username: "user123",
13
+ * password: "secret",
14
+ * profile: {
15
+ * creditCard: "1234-5678-9012-3456",
16
+ * },
17
+ * });
18
+ *
19
+ * const result = maskSensitiveData(jsonString, ["password", "creditCard"]);
20
+ * console.log(result);
21
+ * // Output: '{"username":"user123","password":"****","profile":{"creditCard":"****"}}'
22
+ * ```
23
+ */
24
+ declare const maskSensitiveData: MaskSensitiveDataFunction;
25
+ export { maskSensitiveData };
26
+ //# sourceMappingURL=maskSensitiveData.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"maskSensitiveData.d.ts","sourceRoot":"","sources":["../../src/services/maskSensitiveData.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,cAAc,CAAC;AAE9D;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,QAAA,MAAM,iBAAiB,EAAE,yBAqCxB,CAAC;AAEF,OAAO,EAAE,iBAAiB,EAAE,CAAC"}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Masks sensitive data in a JSON string by replacing the values of specified keys with "****".
3
+ *
4
+ * @param jsonString - The JSON string to be processed.
5
+ * @param sensitiveKeys - An array of keys whose values should be masked. Defaults to `["password", "confirmPassword", "creditCard"]`.
6
+ * @returns A JSON string with sensitive data masked. If the input is not a valid JSON string, it returns the original string.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * const jsonString = JSON.stringify({
11
+ * username: "user123",
12
+ * password: "secret",
13
+ * profile: {
14
+ * creditCard: "1234-5678-9012-3456",
15
+ * },
16
+ * });
17
+ *
18
+ * const result = maskSensitiveData(jsonString, ["password", "creditCard"]);
19
+ * console.log(result);
20
+ * // Output: '{"username":"user123","password":"****","profile":{"creditCard":"****"}}'
21
+ * ```
22
+ */
23
+ const maskSensitiveData = (jsonString, sensitiveKeys = ["password", "confirmPassword", "creditCard"]) => {
24
+ function maskValue(key, value) {
25
+ if (sensitiveKeys.includes(key))
26
+ return "****";
27
+ return value;
28
+ }
29
+ function recursiveMask(obj) {
30
+ if (Array.isArray(obj)) {
31
+ return obj.map((item) => recursiveMask(item));
32
+ }
33
+ else if (obj !== null && typeof obj === "object") {
34
+ return Object.keys(obj).reduce((acc, key) => {
35
+ let value = obj[key];
36
+ if (typeof value === "string") {
37
+ try {
38
+ const parsedValue = JSON.parse(value);
39
+ if (typeof parsedValue === "object") {
40
+ value = JSON.stringify(recursiveMask(parsedValue));
41
+ }
42
+ }
43
+ catch (e) { }
44
+ }
45
+ acc[key] = recursiveMask(maskValue(key, value));
46
+ return acc;
47
+ }, {});
48
+ }
49
+ return obj;
50
+ }
51
+ try {
52
+ const jsonObject = JSON.parse(jsonString);
53
+ const maskedObject = recursiveMask(jsonObject);
54
+ return JSON.stringify(maskedObject);
55
+ }
56
+ catch (error) {
57
+ return jsonString;
58
+ }
59
+ };
60
+ export { maskSensitiveData };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Removes currency symbols from a given formatted string.
3
+ *
4
+ * This function takes a string that may contain currency symbols
5
+ * and removes them using a regular expression. The resulting string
6
+ * is also trimmed of any leading or trailing whitespace.
7
+ *
8
+ * @param formattedValue - The input string containing currency symbols.
9
+ * @returns A string with all currency symbols removed and trimmed of whitespace.
10
+ *
11
+ * @example
12
+ * removeCurrencySymbols("R$13,45"); // "13,45"
13
+ * removeCurrencySymbols("$123.45"); // "123.45"
14
+ * removeCurrencySymbols("€99.99"); // "99.99"
15
+ * removeCurrencySymbols("¥1,000"); // "1,000"
16
+ * removeCurrencySymbols("123.45"); // "123.45" (no symbols to remove)
17
+ */
18
+ declare const removeCurrencySymbols: (formattedValue: string) => string;
19
+ export { removeCurrencySymbols };
20
+ //# sourceMappingURL=removeCurrencySymbols.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"removeCurrencySymbols.d.ts","sourceRoot":"","sources":["../../src/services/removeCurrencySymbols.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,QAAA,MAAM,qBAAqB,GAAI,gBAAgB,MAAM,KAAG,MAIvD,CAAC;AAEF,OAAO,EAAE,qBAAqB,EAAE,CAAC"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Removes currency symbols from a given formatted string.
3
+ *
4
+ * This function takes a string that may contain currency symbols
5
+ * and removes them using a regular expression. The resulting string
6
+ * is also trimmed of any leading or trailing whitespace.
7
+ *
8
+ * @param formattedValue - The input string containing currency symbols.
9
+ * @returns A string with all currency symbols removed and trimmed of whitespace.
10
+ *
11
+ * @example
12
+ * removeCurrencySymbols("R$13,45"); // "13,45"
13
+ * removeCurrencySymbols("$123.45"); // "123.45"
14
+ * removeCurrencySymbols("€99.99"); // "99.99"
15
+ * removeCurrencySymbols("¥1,000"); // "1,000"
16
+ * removeCurrencySymbols("123.45"); // "123.45" (no symbols to remove)
17
+ */
18
+ const removeCurrencySymbols = (formattedValue) => {
19
+ return formattedValue
20
+ .replace(/(?:R\$|\p{Sc}|[$€¥£])/gu, "") // Inclui "R$" e outros símbolos comuns
21
+ .trim();
22
+ };
23
+ export { removeCurrencySymbols };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Removes all non-numeric characters from a given string.
3
+ *
4
+ * @param prop - The input string from which non-numeric characters will be removed.
5
+ * @returns A new string containing only numeric characters from the input.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const result = removeNonNumeric("abc123def456");
10
+ * console.log(result); // Output: "123456"
11
+ * ```
12
+ */
13
+ declare function removeNonNumeric(prop: string): string;
14
+ export { removeNonNumeric };
15
+ //# sourceMappingURL=removeNonNumeric.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"removeNonNumeric.d.ts","sourceRoot":"","sources":["../../src/services/removeNonNumeric.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,iBAAS,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE9C;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Removes all non-numeric characters from a given string.
3
+ *
4
+ * @param prop - The input string from which non-numeric characters will be removed.
5
+ * @returns A new string containing only numeric characters from the input.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const result = removeNonNumeric("abc123def456");
10
+ * console.log(result); // Output: "123456"
11
+ * ```
12
+ */
13
+ function removeNonNumeric(prop) {
14
+ return prop.replace(/[^0-9]/g, "");
15
+ }
16
+ export { removeNonNumeric };
@@ -0,0 +1,32 @@
1
+ import type { TruncateLargeFieldsFunction } from "@arkyn/types";
2
+ /**
3
+ * Truncates large string fields in a JSON string to a specified maximum length.
4
+ *
5
+ * This function parses a JSON string, traverses its structure recursively, and truncates
6
+ * any string fields that exceed the specified maximum length. If a string field is truncated,
7
+ * it is replaced with a message indicating the original length of the field.
8
+ *
9
+ * @param jsonString - The JSON string to process.
10
+ * @param maxLength - The maximum allowed length for string fields. Defaults to 1000.
11
+ * @returns A JSON string with large string fields truncated.
12
+ *
13
+ * @throws {Error} Throws an error if the input is not a valid JSON string.
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const json = JSON.stringify({
18
+ * name: "John",
19
+ * description: "A very long description that exceeds the maximum length...",
20
+ * nested: {
21
+ * details: "Another long string that needs truncation."
22
+ * }
23
+ * });
24
+ *
25
+ * const result = truncateLargeFields(json, 50);
26
+ * console.log(result);
27
+ * // Output: '{"name":"John","description":"To large information: field as 57 characters","nested":{"details":"To large information: field as 43 characters"}}'
28
+ * ```
29
+ */
30
+ declare const truncateLargeFields: TruncateLargeFieldsFunction;
31
+ export { truncateLargeFields };
32
+ //# sourceMappingURL=truncateLargeFields.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"truncateLargeFields.d.ts","sourceRoot":"","sources":["../../src/services/truncateLargeFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAEhE;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,QAAA,MAAM,mBAAmB,EAAE,2BAgC1B,CAAC;AAEF,OAAO,EAAE,mBAAmB,EAAE,CAAC"}
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Truncates large string fields in a JSON string to a specified maximum length.
3
+ *
4
+ * This function parses a JSON string, traverses its structure recursively, and truncates
5
+ * any string fields that exceed the specified maximum length. If a string field is truncated,
6
+ * it is replaced with a message indicating the original length of the field.
7
+ *
8
+ * @param jsonString - The JSON string to process.
9
+ * @param maxLength - The maximum allowed length for string fields. Defaults to 1000.
10
+ * @returns A JSON string with large string fields truncated.
11
+ *
12
+ * @throws {Error} Throws an error if the input is not a valid JSON string.
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * const json = JSON.stringify({
17
+ * name: "John",
18
+ * description: "A very long description that exceeds the maximum length...",
19
+ * nested: {
20
+ * details: "Another long string that needs truncation."
21
+ * }
22
+ * });
23
+ *
24
+ * const result = truncateLargeFields(json, 50);
25
+ * console.log(result);
26
+ * // Output: '{"name":"John","description":"To large information: field as 57 characters","nested":{"details":"To large information: field as 43 characters"}}'
27
+ * ```
28
+ */
29
+ const truncateLargeFields = (jsonString, maxLength = 1000) => {
30
+ function truncateValue(value) {
31
+ if (typeof value === "string" && value.length > maxLength) {
32
+ return `To large information: field as ${value.length} characters`;
33
+ }
34
+ return value;
35
+ }
36
+ function recursiveTruncate(obj) {
37
+ if (Array.isArray(obj)) {
38
+ return obj.map((item) => recursiveTruncate(item)); // Corrigido para processar elementos do array
39
+ }
40
+ else if (obj !== null && typeof obj === "object") {
41
+ return Object.fromEntries(Object.entries(obj).map(([key, value]) => [
42
+ key,
43
+ recursiveTruncate(value), // Corrigido para aplicar recursão corretamente
44
+ ]));
45
+ }
46
+ return truncateValue(obj); // Corrigido para truncar valores diretamente
47
+ }
48
+ try {
49
+ const parsedJson = JSON.parse(jsonString);
50
+ const truncatedJson = recursiveTruncate(parsedJson);
51
+ return JSON.stringify(truncatedJson);
52
+ }
53
+ catch (error) {
54
+ throw new Error("Invalid JSON string");
55
+ }
56
+ };
57
+ export { truncateLargeFields };
@@ -0,0 +1,24 @@
1
+ import type { ValidateCpfFunction } from "@arkyn/types";
2
+ /**
3
+ * Validates a Brazilian CPF (Cadastro de Pessoas Físicas) number.
4
+ *
5
+ * The CPF is a unique identifier assigned to Brazilian citizens and residents.
6
+ * This function checks if the provided CPF is valid by performing the following steps:
7
+ * - Removes any non-digit characters from the input.
8
+ * - Verifies if the CPF has the correct length (11 digits).
9
+ * - Ensures that all digits are not the same (e.g., "111.111.111-11" is invalid).
10
+ * - Calculates the first and second verification digits using the CPF algorithm.
11
+ * - Compares the calculated verification digits with the ones provided in the CPF.
12
+ *
13
+ * @param rawCpf - The raw CPF string, which may include formatting characters (e.g., dots or dashes).
14
+ * @returns `true` if the CPF is valid, otherwise `false`.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * validateCpf("123.456.789-09"); // false
19
+ * validateCpf("111.444.777-35"); // true
20
+ * ```
21
+ */
22
+ declare const validateCpf: ValidateCpfFunction;
23
+ export { validateCpf };
24
+ //# sourceMappingURL=validateCpf.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validateCpf.d.ts","sourceRoot":"","sources":["../../src/validations/validateCpf.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AA6BxD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,QAAA,MAAM,WAAW,EAAE,mBAWlB,CAAC;AAEF,OAAO,EAAE,WAAW,EAAE,CAAC"}
@@ -0,0 +1,56 @@
1
+ function removeNonDigits(cpf) {
2
+ return cpf.replace(/\D/g, "");
3
+ }
4
+ function isInvalidLength(cpf) {
5
+ const CPF_LENGTH = 11;
6
+ return cpf.length !== CPF_LENGTH;
7
+ }
8
+ function hasAllDigitsEqual(cpf) {
9
+ const [firstCpfDigit] = cpf;
10
+ return [...cpf].every((digit) => digit === firstCpfDigit);
11
+ }
12
+ function calculateDigit(cpf, factor) {
13
+ let total = 0;
14
+ for (const digit of cpf) {
15
+ if (factor > 1)
16
+ total += parseInt(digit) * factor--;
17
+ }
18
+ const rest = total % 11;
19
+ return rest < 2 ? 0 : 11 - rest;
20
+ }
21
+ function extractDigit(cpf) {
22
+ return cpf.slice(9);
23
+ }
24
+ /**
25
+ * Validates a Brazilian CPF (Cadastro de Pessoas Físicas) number.
26
+ *
27
+ * The CPF is a unique identifier assigned to Brazilian citizens and residents.
28
+ * This function checks if the provided CPF is valid by performing the following steps:
29
+ * - Removes any non-digit characters from the input.
30
+ * - Verifies if the CPF has the correct length (11 digits).
31
+ * - Ensures that all digits are not the same (e.g., "111.111.111-11" is invalid).
32
+ * - Calculates the first and second verification digits using the CPF algorithm.
33
+ * - Compares the calculated verification digits with the ones provided in the CPF.
34
+ *
35
+ * @param rawCpf - The raw CPF string, which may include formatting characters (e.g., dots or dashes).
36
+ * @returns `true` if the CPF is valid, otherwise `false`.
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * validateCpf("123.456.789-09"); // false
41
+ * validateCpf("111.444.777-35"); // true
42
+ * ```
43
+ */
44
+ const validateCpf = (rawCpf) => {
45
+ if (!rawCpf)
46
+ return false;
47
+ const cpf = removeNonDigits(rawCpf);
48
+ if (isInvalidLength(cpf))
49
+ return false;
50
+ if (hasAllDigitsEqual(cpf))
51
+ return false;
52
+ const digit1 = calculateDigit(cpf, 10);
53
+ const digit2 = calculateDigit(cpf, 11);
54
+ return extractDigit(cpf) === `${digit1}${digit2}`;
55
+ };
56
+ export { validateCpf };
@@ -0,0 +1,29 @@
1
+ import type { ValidateDateFunction } from "@arkyn/types";
2
+ /**
3
+ * Validates a date string based on the provided format and configuration.
4
+ *
5
+ * @param date - The date string to validate.
6
+ * @param config - Optional configuration object to customize validation.
7
+ * @param config.inputFormat - The expected format of the input date.
8
+ * Supported formats are "DD/MM/YYYY", "MM-DD-YYYY", and "YYYY-MM-DD".
9
+ * Defaults to "DD/MM/YYYY".
10
+ * @param config.minYear - The minimum allowed year for the date. Defaults to 1900.
11
+ * @param config.maxYear - The maximum allowed year for the date. Defaults to 3000.
12
+ *
13
+ * @returns `true` if the date is valid according to the specified format and configuration, otherwise `false`.
14
+ *
15
+ * @throws {Error} If an invalid date format is provided in the configuration.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * validateDate("31/12/2023"); // true
20
+ * validateDate("12-31-2023", { inputFormat: "MM-DD-YYYY" }); // true
21
+ * validateDate("2023-12-31", { inputFormat: "YYYY-MM-DD", minYear: 2000, maxYear: 2100 }); // true
22
+ * validateDate("29/02/2024", { inputFormat: "DD/MM/YYYY" }); // true (leap year)
23
+ * validateDate("29/02/2023", { inputFormat: "DD/MM/YYYY" }); // false (not a leap year)
24
+ * validateDate("31/04/2023", { inputFormat: "DD/MM/YYYY" }); // false (April has 30 days)
25
+ * ```
26
+ */
27
+ declare const validateDate: ValidateDateFunction;
28
+ export { validateDate };
29
+ //# sourceMappingURL=validateDate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validateDate.d.ts","sourceRoot":"","sources":["../../src/validations/validateDate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,QAAA,MAAM,YAAY,EAAE,oBA8CnB,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,CAAC"}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Validates a date string based on the provided format and configuration.
3
+ *
4
+ * @param date - The date string to validate.
5
+ * @param config - Optional configuration object to customize validation.
6
+ * @param config.inputFormat - The expected format of the input date.
7
+ * Supported formats are "DD/MM/YYYY", "MM-DD-YYYY", and "YYYY-MM-DD".
8
+ * Defaults to "DD/MM/YYYY".
9
+ * @param config.minYear - The minimum allowed year for the date. Defaults to 1900.
10
+ * @param config.maxYear - The maximum allowed year for the date. Defaults to 3000.
11
+ *
12
+ * @returns `true` if the date is valid according to the specified format and configuration, otherwise `false`.
13
+ *
14
+ * @throws {Error} If an invalid date format is provided in the configuration.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * validateDate("31/12/2023"); // true
19
+ * validateDate("12-31-2023", { inputFormat: "MM-DD-YYYY" }); // true
20
+ * validateDate("2023-12-31", { inputFormat: "YYYY-MM-DD", minYear: 2000, maxYear: 2100 }); // true
21
+ * validateDate("29/02/2024", { inputFormat: "DD/MM/YYYY" }); // true (leap year)
22
+ * validateDate("29/02/2023", { inputFormat: "DD/MM/YYYY" }); // false (not a leap year)
23
+ * validateDate("31/04/2023", { inputFormat: "DD/MM/YYYY" }); // false (April has 30 days)
24
+ * ```
25
+ */
26
+ const validateDate = (date, config) => {
27
+ let day, month, year;
28
+ const inputFormat = config?.inputFormat || "DD/MM/YYYY";
29
+ const minYear = config?.minYear || 1900;
30
+ const maxYear = config?.maxYear || 3000;
31
+ if (inputFormat === "DD/MM/YYYY") {
32
+ const dateRegex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
33
+ if (!dateRegex.test(date))
34
+ return false;
35
+ [, day, month, year] = date.match(dateRegex) || [];
36
+ }
37
+ else if (inputFormat === "MM-DD-YYYY") {
38
+ const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
39
+ if (!dateRegex.test(date))
40
+ return false;
41
+ [, month, day, year] = date.match(dateRegex) || [];
42
+ }
43
+ else if (inputFormat === "YYYY-MM-DD") {
44
+ const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
45
+ if (!dateRegex.test(date))
46
+ return false;
47
+ [, year, month, day] = date.match(dateRegex) || [];
48
+ }
49
+ else {
50
+ throw new Error("Invalid date format");
51
+ }
52
+ const dayNum = parseInt(day, 10);
53
+ const monthNum = parseInt(month, 10);
54
+ const yearNum = parseInt(year, 10);
55
+ if (dayNum < 1 || dayNum > 31)
56
+ return false;
57
+ if (monthNum < 1 || monthNum > 12)
58
+ return false;
59
+ const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
60
+ if (monthNum === 2) {
61
+ const isLeapYear = (yearNum % 4 === 0 && yearNum % 100 !== 0) || yearNum % 400 === 0;
62
+ if (dayNum > (isLeapYear ? 29 : 28))
63
+ return false;
64
+ }
65
+ else if (dayNum > daysInMonth[monthNum - 1]) {
66
+ return false;
67
+ }
68
+ if (yearNum < minYear || yearNum > maxYear)
69
+ return false;
70
+ const isValidDate = new Date(yearNum, monthNum - 1, dayNum).getDate() === dayNum;
71
+ return isValidDate;
72
+ };
73
+ export { validateDate };
@@ -0,0 +1,29 @@
1
+ import type { ValidatePhoneFunction } from "@arkyn/types";
2
+ /**
3
+ * Validates a phone number against a list of country-specific formats.
4
+ *
5
+ * The function iterates through a predefined list of countries and checks if the
6
+ * provided phone number matches the format for any of the countries. It uses
7
+ * regular expressions to validate the phone number based on the country's code,
8
+ * prefix, and mask.
9
+ *
10
+ * Special handling is applied for Brazilian phone numbers (ISO code "BR"), which
11
+ * allows for an optional ninth digit.
12
+ *
13
+ * @param phone - The phone number to validate as a string.
14
+ * @returns `true` if the phone number matches any country's format, otherwise `false`.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { validatePhone } from "./validatePhone";
19
+ *
20
+ * validatePhone("+55 32912345678"); // true for a valid Brazilian phone number
21
+ * validatePhone("+55 3212345678"); // true for a valid Brazilian phone number
22
+ * validatePhone("+1-684 1234567"); // true for a valid American Samoa phone number
23
+ * validatePhone("+5532912345678"); // false for an invalid Brazilian phone number
24
+ * validatePhone("+55 1234567890"); // false for an invalid Brazilian phone number
25
+ * ```
26
+ */
27
+ declare const validatePhone: ValidatePhoneFunction;
28
+ export { validatePhone };
29
+ //# sourceMappingURL=validatePhone.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validatePhone.d.ts","sourceRoot":"","sources":["../../src/validations/validatePhone.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,QAAA,MAAM,aAAa,EAAE,qBAiBpB,CAAC;AAEF,OAAO,EAAE,aAAa,EAAE,CAAC"}
@@ -0,0 +1,44 @@
1
+ import { countries } from "@arkyn/templates";
2
+ /**
3
+ * Validates a phone number against a list of country-specific formats.
4
+ *
5
+ * The function iterates through a predefined list of countries and checks if the
6
+ * provided phone number matches the format for any of the countries. It uses
7
+ * regular expressions to validate the phone number based on the country's code,
8
+ * prefix, and mask.
9
+ *
10
+ * Special handling is applied for Brazilian phone numbers (ISO code "BR"), which
11
+ * allows for an optional ninth digit.
12
+ *
13
+ * @param phone - The phone number to validate as a string.
14
+ * @returns `true` if the phone number matches any country's format, otherwise `false`.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { validatePhone } from "./validatePhone";
19
+ *
20
+ * validatePhone("+55 32912345678"); // true for a valid Brazilian phone number
21
+ * validatePhone("+55 3212345678"); // true for a valid Brazilian phone number
22
+ * validatePhone("+1-684 1234567"); // true for a valid American Samoa phone number
23
+ * validatePhone("+5532912345678"); // false for an invalid Brazilian phone number
24
+ * validatePhone("+55 1234567890"); // false for an invalid Brazilian phone number
25
+ * ```
26
+ */
27
+ const validatePhone = (phone) => {
28
+ for (const country of countries) {
29
+ const countryCode = country.code;
30
+ const prefix = country.prefix ? `-${country.prefix}` : "";
31
+ const digitCount = country.mask.replace(/[^_]/g, "").length;
32
+ if (country.iso === "BR") {
33
+ const brazilRegex = new RegExp(`^\\${countryCode} \\d{2}9?\\d{8}$`);
34
+ if (brazilRegex.test(phone))
35
+ return true;
36
+ continue;
37
+ }
38
+ const regex = new RegExp(`^\\${countryCode}${prefix} \\d{${digitCount}}$`);
39
+ if (regex.test(phone))
40
+ return true;
41
+ }
42
+ return false;
43
+ };
44
+ export { validatePhone };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arkyn/shared",
3
- "version": "2.0.1-beta.0",
3
+ "version": "2.0.1-beta.2",
4
4
  "main": "./dist/bundle.js",
5
5
  "module": "./src/index.ts",
6
6
  "type": "module",
@@ -1,41 +1,8 @@
1
- const CEP = /^(\d{8}|\d{2}\.?\d{3}\-\d{3})$/;
2
-
3
- const CNPJ = /(^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$)/;
4
-
5
- const CPF = /(^\d{3}\.\d{3}\.\d{3}\-\d{2}$)/;
6
-
7
- const DATE = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/\d{4}$/;
8
-
9
- const DATEHOUR =
10
- /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/\d{4}\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$/;
11
-
12
- const HOUR = /^(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$/;
1
+ const RG = /(^\d{1,2}).?(\d{3}).?(\d{3})-?(\d{1}|X|x$)/;
13
2
 
14
3
  const PASSWORD =
15
4
  /(?=^.{8,}$)((?=.*\w)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[|!"$%&\/\(\)\?\^\'\\\+\-\*]))^.*/;
16
5
 
17
- const PHONE = /([0-9]{2})?(\s|-)?(9?[0-9]{4})-?([0-9]{4}$)/;
18
-
19
- const RG = /(^\d{1,2}).?(\d{3}).?(\d{3})-?(\d{1}|X|x$)/;
20
-
21
- const URL =
22
- /^(((https?|ftp):\/\/)?([\w\-\.])+(\.)([\w]){2,4}([\w\/+=%&_\.~?\-]*))*$/;
23
-
24
- const CPFCNPJ =
25
- /^(?:(\d{3}\.\d{3}\.\d{3}-\d{2})|(\d{11})|(\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2})|(\d{14}))$/;
26
-
27
- const regex = {
28
- URL,
29
- HOUR,
30
- RG,
31
- PHONE,
32
- PASSWORD,
33
- DATEHOUR,
34
- CPF,
35
- CNPJ,
36
- CEP,
37
- CPFCNPJ,
38
- DATE,
39
- };
6
+ const regex = { RG, PASSWORD };
40
7
 
41
8
  export { regex };