@arkyn/shared 1.4.52 → 2.0.1-beta.0

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 (134) hide show
  1. package/package.json +4 -2
  2. package/src/formats/__test__/formatDate.spec.ts +88 -0
  3. package/src/formats/__test__/formatJsonObject.spec.ts +87 -0
  4. package/src/formats/__test__/formatJsonString.spec.ts +83 -0
  5. package/src/formats/__test__/formatToCep.spec.ts +37 -0
  6. package/src/formats/__test__/formatToCnpj.spec.ts +35 -0
  7. package/src/formats/__test__/formatToCpfCnpj.spec.ts +43 -0
  8. package/src/formats/__test__/formatToCurrency.spec.ts +50 -0
  9. package/src/formats/__test__/formatToEllipsis.spec.ts +44 -0
  10. package/src/formats/__test__/formatToHiddenDigits.spec.ts +58 -0
  11. package/src/formats/__test__/formatToPhone.spec.ts +58 -0
  12. package/src/formats/formatDate.ts +97 -0
  13. package/src/formats/formatJsonObject.ts +68 -26
  14. package/src/formats/formatJsonString.ts +40 -4
  15. package/src/formats/formatToCep.ts +35 -7
  16. package/src/formats/formatToCnpj.ts +39 -0
  17. package/src/formats/formatToCpf.ts +39 -0
  18. package/src/formats/formatToCpfCnpj.ts +31 -7
  19. package/src/formats/formatToCurrency.ts +53 -0
  20. package/src/formats/formatToEllipsis.ts +23 -3
  21. package/src/formats/formatToHiddenDigits.ts +75 -7
  22. package/src/formats/formatToPhone.ts +156 -6
  23. package/src/generators/__test__/generateColorByString.spec.ts +37 -0
  24. package/src/generators/__test__/generateId.spec.ts +44 -0
  25. package/src/generators/__test__/generateSlug.spec.ts +47 -0
  26. package/src/generators/generateColorByString.ts +18 -4
  27. package/src/generators/generateId.ts +36 -5
  28. package/src/generators/generateSlug.ts +17 -2
  29. package/src/index.ts +7 -15
  30. package/src/services/__test__/calculateCardInstallment.spec.ts +87 -0
  31. package/src/services/__test__/maskSensitiveData.spec.ts +102 -0
  32. package/src/services/__test__/removeCurrencySymbols.spec.ts +41 -0
  33. package/src/services/__test__/removeNonNumeric.spec.ts +33 -0
  34. package/src/services/__test__/truncateLargeFields.spec.ts +90 -0
  35. package/src/services/calculateCardInstallment.ts +57 -12
  36. package/src/services/maskSensitiveData.ts +29 -4
  37. package/src/services/removeCurrencySymbols.ts +25 -0
  38. package/src/services/removeNonNumeric.ts +18 -0
  39. package/src/services/truncateLargeFields.ts +40 -6
  40. package/src/validations/__test__/validateCpf.spec.ts +38 -0
  41. package/src/validations/__test__/validateDate.spec.ts +81 -0
  42. package/src/validations/__test__/validatePhone.spec.ts +39 -0
  43. package/src/validations/validateCpf.ts +64 -0
  44. package/src/validations/validateDate.ts +33 -11
  45. package/src/validations/validatePhone.ts +29 -2
  46. package/vitest.config.ts +5 -0
  47. package/dist/formats/formatBrazilianDateHour.d.ts +0 -3
  48. package/dist/formats/formatBrazilianDateHour.d.ts.map +0 -1
  49. package/dist/formats/formatBrazilianDateHour.js +0 -12
  50. package/dist/formats/formatBrazilianDateToDate.d.ts +0 -3
  51. package/dist/formats/formatBrazilianDateToDate.d.ts.map +0 -1
  52. package/dist/formats/formatBrazilianDateToDate.js +0 -9
  53. package/dist/formats/formatDateHour.d.ts +0 -3
  54. package/dist/formats/formatDateHour.d.ts.map +0 -1
  55. package/dist/formats/formatDateHour.js +0 -11
  56. package/dist/formats/formatJsonObject.d.ts +0 -3
  57. package/dist/formats/formatJsonObject.d.ts.map +0 -1
  58. package/dist/formats/formatJsonObject.js +0 -49
  59. package/dist/formats/formatJsonString.d.ts +0 -3
  60. package/dist/formats/formatJsonString.d.ts.map +0 -1
  61. package/dist/formats/formatJsonString.js +0 -12
  62. package/dist/formats/formatToBRL.d.ts +0 -3
  63. package/dist/formats/formatToBRL.d.ts.map +0 -1
  64. package/dist/formats/formatToBRL.js +0 -8
  65. package/dist/formats/formatToCNPJ.d.ts +0 -3
  66. package/dist/formats/formatToCNPJ.d.ts.map +0 -1
  67. package/dist/formats/formatToCNPJ.js +0 -9
  68. package/dist/formats/formatToCPF.d.ts +0 -3
  69. package/dist/formats/formatToCPF.d.ts.map +0 -1
  70. package/dist/formats/formatToCPF.js +0 -9
  71. package/dist/formats/formatToCep.d.ts +0 -3
  72. package/dist/formats/formatToCep.d.ts.map +0 -1
  73. package/dist/formats/formatToCep.js +0 -9
  74. package/dist/formats/formatToCpfCnpj.d.ts +0 -3
  75. package/dist/formats/formatToCpfCnpj.d.ts.map +0 -1
  76. package/dist/formats/formatToCpfCnpj.js +0 -13
  77. package/dist/formats/formatToEllipsis.d.ts +0 -3
  78. package/dist/formats/formatToEllipsis.d.ts.map +0 -1
  79. package/dist/formats/formatToEllipsis.js +0 -4
  80. package/dist/formats/formatToHiddenDigits.d.ts +0 -4
  81. package/dist/formats/formatToHiddenDigits.d.ts.map +0 -1
  82. package/dist/formats/formatToHiddenDigits.js +0 -14
  83. package/dist/formats/formatToPhone.d.ts +0 -3
  84. package/dist/formats/formatToPhone.d.ts.map +0 -1
  85. package/dist/formats/formatToPhone.js +0 -9
  86. package/dist/generators/generateColorByString.d.ts +0 -3
  87. package/dist/generators/generateColorByString.d.ts.map +0 -1
  88. package/dist/generators/generateColorByString.js +0 -14
  89. package/dist/generators/generateId.d.ts +0 -6
  90. package/dist/generators/generateId.d.ts.map +0 -1
  91. package/dist/generators/generateId.js +0 -23
  92. package/dist/generators/generateSlug.d.ts +0 -3
  93. package/dist/generators/generateSlug.d.ts.map +0 -1
  94. package/dist/generators/generateSlug.js +0 -11
  95. package/dist/index.d.ts +0 -26
  96. package/dist/index.d.ts.map +0 -1
  97. package/dist/index.js +0 -30
  98. package/dist/parsers/parseToCharacters.d.ts +0 -17
  99. package/dist/parsers/parseToCharacters.d.ts.map +0 -1
  100. package/dist/parsers/parseToCharacters.js +0 -13
  101. package/dist/services/calculateCardInstallment.d.ts +0 -7
  102. package/dist/services/calculateCardInstallment.d.ts.map +0 -1
  103. package/dist/services/calculateCardInstallment.js +0 -14
  104. package/dist/services/maskSensitiveData.d.ts +0 -3
  105. package/dist/services/maskSensitiveData.d.ts.map +0 -1
  106. package/dist/services/maskSensitiveData.js +0 -38
  107. package/dist/services/range.d.ts +0 -4
  108. package/dist/services/range.d.ts.map +0 -1
  109. package/dist/services/range.js +0 -9
  110. package/dist/services/truncateLargeFields.d.ts +0 -3
  111. package/dist/services/truncateLargeFields.d.ts.map +0 -1
  112. package/dist/services/truncateLargeFields.js +0 -29
  113. package/dist/validations/regex.d.ts +0 -15
  114. package/dist/validations/regex.d.ts.map +0 -1
  115. package/dist/validations/regex.js +0 -25
  116. package/dist/validations/validateCPF.d.ts +0 -3
  117. package/dist/validations/validateCPF.d.ts.map +0 -1
  118. package/dist/validations/validateCPF.js +0 -36
  119. package/dist/validations/validateDate.d.ts +0 -8
  120. package/dist/validations/validateDate.d.ts.map +0 -1
  121. package/dist/validations/validateDate.js +0 -47
  122. package/dist/validations/validatePhone.d.ts +0 -3
  123. package/dist/validations/validatePhone.d.ts.map +0 -1
  124. package/dist/validations/validatePhone.js +0 -19
  125. package/src/formats/formatBrazilianDateHour.ts +0 -17
  126. package/src/formats/formatBrazilianDateToDate.ts +0 -13
  127. package/src/formats/formatDateHour.ts +0 -15
  128. package/src/formats/formatToBRL.ts +0 -10
  129. package/src/formats/formatToCNPJ.ts +0 -10
  130. package/src/formats/formatToCPF.ts +0 -10
  131. package/src/parsers/parseToCharacters.ts +0 -34
  132. package/src/services/range.ts +0 -15
  133. package/src/validations/validateCPF.ts +0 -38
  134. /package/src/{validations/regex.ts → regex/index.ts} +0 -0
@@ -0,0 +1,33 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { removeNonNumeric } from "../removeNonNumeric";
3
+
4
+ describe("removeNonNumeric", () => {
5
+ it("should remove all non-numeric characters from a string", () => {
6
+ expect(removeNonNumeric("abc123def456")).toBe("123456");
7
+ expect(removeNonNumeric("!@#123$%^456&*()")).toBe("123456");
8
+ expect(removeNonNumeric("a1b2c3")).toBe("123");
9
+ });
10
+
11
+ it("should return an empty string if there are no numeric characters", () => {
12
+ expect(removeNonNumeric("abcdef")).toBe("");
13
+ expect(removeNonNumeric("!@#$%^&*()")).toBe("");
14
+ });
15
+
16
+ it("should return the same string if it contains only numeric characters", () => {
17
+ expect(removeNonNumeric("123456")).toBe("123456");
18
+ expect(removeNonNumeric("000123")).toBe("000123");
19
+ });
20
+
21
+ it("should handle an empty string input", () => {
22
+ expect(removeNonNumeric("")).toBe("");
23
+ });
24
+
25
+ it("should handle strings with spaces and remove them", () => {
26
+ expect(removeNonNumeric("123 456 789")).toBe("123456789");
27
+ expect(removeNonNumeric(" 1 2 3 ")).toBe("123");
28
+ });
29
+
30
+ it("should handle strings with special characters and preserve only numbers", () => {
31
+ expect(removeNonNumeric("12-34.56/78")).toBe("12345678");
32
+ });
33
+ });
@@ -0,0 +1,90 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { truncateLargeFields } from "../truncateLargeFields";
3
+
4
+ describe("truncateLargeFields", () => {
5
+ it("should truncate string fields exceeding the maxLength", () => {
6
+ const json = JSON.stringify({
7
+ name: "John",
8
+ description: "A very long description that exceeds the maximum length...",
9
+ });
10
+
11
+ const result = truncateLargeFields(json, 20);
12
+ expect(result).toBe(
13
+ '{"name":"John","description":"To large information: field as 58 characters"}'
14
+ );
15
+ });
16
+
17
+ it("should handle nested objects and truncate large string fields", () => {
18
+ const json = JSON.stringify({
19
+ nested: {
20
+ details: "Another long string that needs truncation.",
21
+ },
22
+ });
23
+
24
+ const result = truncateLargeFields(json, 20);
25
+ expect(result).toBe(
26
+ '{"nested":{"details":"To large information: field as 42 characters"}}'
27
+ );
28
+ });
29
+
30
+ it("should handle arrays and truncate large string fields within them", () => {
31
+ const json = JSON.stringify({
32
+ items: ["short", "A very long string in an array that exceeds the limit"],
33
+ });
34
+
35
+ const result = truncateLargeFields(json, 20);
36
+ expect(result).toBe(
37
+ '{"items":["short","To large information: field as 53 characters"]}'
38
+ );
39
+ });
40
+
41
+ it("should not modify fields that are within the maxLength", () => {
42
+ const json = JSON.stringify({
43
+ name: "John",
44
+ description: "Short description",
45
+ });
46
+
47
+ const result = truncateLargeFields(json, 20);
48
+ expect(result).toBe('{"name":"John","description":"Short description"}');
49
+ });
50
+
51
+ it("should throw an error for invalid JSON strings", () => {
52
+ const invalidJson = "{ name: 'John' }"; // Invalid JSON
53
+ expect(() => truncateLargeFields(invalidJson, 20)).toThrow(
54
+ "Invalid JSON string"
55
+ );
56
+ });
57
+
58
+ it("should handle empty JSON objects", () => {
59
+ const json = JSON.stringify({});
60
+ const result = truncateLargeFields(json, 20);
61
+ expect(result).toBe("{}");
62
+ });
63
+
64
+ it("should handle empty arrays", () => {
65
+ const json = JSON.stringify([]);
66
+ const result = truncateLargeFields(json, 20);
67
+ expect(result).toBe("[]");
68
+ });
69
+
70
+ it("should handle non-string fields without modification", () => {
71
+ const json = JSON.stringify({
72
+ number: 123,
73
+ boolean: true,
74
+ nullValue: null,
75
+ });
76
+
77
+ const result = truncateLargeFields(json, 20);
78
+ expect(result).toBe('{"number":123,"boolean":true,"nullValue":null}');
79
+ });
80
+
81
+ it("should use the default maxLength of 1000 if not provided", () => {
82
+ const longString = "a".repeat(1500);
83
+ const json = JSON.stringify({ longField: longString });
84
+ const result = truncateLargeFields(json);
85
+
86
+ expect(result).toBe(
87
+ `{"longField":"To large information: field as 1500 characters"}`
88
+ );
89
+ });
90
+ });
@@ -1,21 +1,66 @@
1
- import type { CalculateCardInstallmentProps } from "@arkyn/types";
1
+ import type { CalculateCardInstallmentFunction } from "@arkyn/types";
2
2
 
3
- function calculateCardInstallment(args: CalculateCardInstallmentProps) {
4
- const { cash_price, number_installments, fees = 0.0349 } = args;
3
+ /**
4
+ * Calculates the installment price and total price for a card payment plan.
5
+ *
6
+ * @remarks
7
+ * **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.
8
+ *
9
+ * @throws Will throw an error if the number of installments is less than or equal to 0.
10
+ * @throws Will throw an error if the fees are less than 0.
11
+ *
12
+ * @param props - The input parameters for the calculation.
13
+ * @param props.cashPrice - The total cash price of the product or service.
14
+ * @param props.numberInstallments - The number of installments for the payment plan.
15
+ * @param props.fees - The interest rate per installment (default is 0.0349).
16
+ *
17
+ * @returns An object containing:
18
+ * - `totalPrice`: The total price to be paid, rounded to two decimal places.
19
+ * - `installmentPrice`: The price of each installment, rounded to two decimal places.
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * const result = calculateCardInstallment({
24
+ * cashPrice: 1000,
25
+ * numberInstallments: 12,
26
+ * fees: 0.02,
27
+ * });
28
+ * console.log(result);
29
+ * // Output: { totalPrice: 1124.62, installmentPrice: 93.72 }
30
+ * ```
31
+ */
5
32
 
6
- let installment_price = 0;
7
- let total_price = 0;
33
+ const calculateCardInstallment: CalculateCardInstallmentFunction = (props) => {
34
+ const { cashPrice, numberInstallments, fees = 0.0349 } = props;
8
35
 
9
- let numerator = Math.pow(1 + fees, number_installments) * fees;
10
- let denominator = Math.pow(1 + fees, number_installments) - 1;
36
+ if (fees === 0 || numberInstallments === 1) {
37
+ return {
38
+ totalPrice: cashPrice,
39
+ installmentPrice: cashPrice / numberInstallments,
40
+ };
41
+ }
11
42
 
12
- installment_price = cash_price * (numerator / denominator);
13
- total_price = number_installments * installment_price;
43
+ if (numberInstallments <= 0) {
44
+ throw new Error("Number of installments must be greater than 0");
45
+ }
46
+
47
+ if (fees < 0) {
48
+ throw new Error("Fees must be greater than or equal to 0");
49
+ }
50
+
51
+ let installmentPrice = 0;
52
+ let totalPrice = 0;
53
+
54
+ let numerator = Math.pow(1 + fees, numberInstallments) * fees;
55
+ let denominator = Math.pow(1 + fees, numberInstallments) - 1;
56
+
57
+ installmentPrice = cashPrice * (numerator / denominator);
58
+ totalPrice = numberInstallments * installmentPrice;
14
59
 
15
60
  return {
16
- total_price: +total_price.toFixed(2),
17
- installment_price: +installment_price.toFixed(2),
61
+ totalPrice: +totalPrice.toFixed(2),
62
+ installmentPrice: +installmentPrice.toFixed(2),
18
63
  };
19
- }
64
+ };
20
65
 
21
66
  export { calculateCardInstallment };
@@ -1,7 +1,32 @@
1
- function maskSensitiveData(
2
- jsonString: string,
1
+ import type { MaskSensitiveDataFunction } from "@arkyn/types";
2
+
3
+ /**
4
+ * Masks sensitive data in a JSON string by replacing the values of specified keys with "****".
5
+ *
6
+ * @param jsonString - The JSON string to be processed.
7
+ * @param sensitiveKeys - An array of keys whose values should be masked. Defaults to `["password", "confirmPassword", "creditCard"]`.
8
+ * @returns A JSON string with sensitive data masked. If the input is not a valid JSON string, it returns the original string.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const jsonString = JSON.stringify({
13
+ * username: "user123",
14
+ * password: "secret",
15
+ * profile: {
16
+ * creditCard: "1234-5678-9012-3456",
17
+ * },
18
+ * });
19
+ *
20
+ * const result = maskSensitiveData(jsonString, ["password", "creditCard"]);
21
+ * console.log(result);
22
+ * // Output: '{"username":"user123","password":"****","profile":{"creditCard":"****"}}'
23
+ * ```
24
+ */
25
+
26
+ const maskSensitiveData: MaskSensitiveDataFunction = (
27
+ jsonString,
3
28
  sensitiveKeys = ["password", "confirmPassword", "creditCard"]
4
- ): string {
29
+ ) => {
5
30
  function maskValue(key: string, value: any): any {
6
31
  if (sensitiveKeys.includes(key)) return "****";
7
32
  return value;
@@ -35,6 +60,6 @@ function maskSensitiveData(
35
60
  } catch (error) {
36
61
  return jsonString;
37
62
  }
38
- }
63
+ };
39
64
 
40
65
  export { maskSensitiveData };
@@ -0,0 +1,25 @@
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
+
19
+ const removeCurrencySymbols = (formattedValue: string): string => {
20
+ return formattedValue
21
+ .replace(/(?:R\$|\p{Sc}|[$€¥£])/gu, "") // Inclui "R$" e outros símbolos comuns
22
+ .trim();
23
+ };
24
+
25
+ export { removeCurrencySymbols };
@@ -0,0 +1,18 @@
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
+
14
+ function removeNonNumeric(prop: string): string {
15
+ return prop.replace(/[^0-9]/g, "");
16
+ }
17
+
18
+ export { removeNonNumeric };
@@ -1,5 +1,39 @@
1
- function truncateLargeFields(jsonString: string, maxLength = 1000): string {
2
- function truncateValue(key: string, value: any): any {
1
+ import type { TruncateLargeFieldsFunction } from "@arkyn/types";
2
+
3
+ /**
4
+ * Truncates large string fields in a JSON string to a specified maximum length.
5
+ *
6
+ * This function parses a JSON string, traverses its structure recursively, and truncates
7
+ * any string fields that exceed the specified maximum length. If a string field is truncated,
8
+ * it is replaced with a message indicating the original length of the field.
9
+ *
10
+ * @param jsonString - The JSON string to process.
11
+ * @param maxLength - The maximum allowed length for string fields. Defaults to 1000.
12
+ * @returns A JSON string with large string fields truncated.
13
+ *
14
+ * @throws {Error} Throws an error if the input is not a valid JSON string.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * const json = JSON.stringify({
19
+ * name: "John",
20
+ * description: "A very long description that exceeds the maximum length...",
21
+ * nested: {
22
+ * details: "Another long string that needs truncation."
23
+ * }
24
+ * });
25
+ *
26
+ * const result = truncateLargeFields(json, 50);
27
+ * console.log(result);
28
+ * // Output: '{"name":"John","description":"To large information: field as 57 characters","nested":{"details":"To large information: field as 43 characters"}}'
29
+ * ```
30
+ */
31
+
32
+ const truncateLargeFields: TruncateLargeFieldsFunction = (
33
+ jsonString,
34
+ maxLength = 1000
35
+ ) => {
36
+ function truncateValue(value: any): any {
3
37
  if (typeof value === "string" && value.length > maxLength) {
4
38
  return `To large information: field as ${value.length} characters`;
5
39
  }
@@ -8,16 +42,16 @@ function truncateLargeFields(jsonString: string, maxLength = 1000): string {
8
42
 
9
43
  function recursiveTruncate(obj: any): any {
10
44
  if (Array.isArray(obj)) {
11
- return obj.map(recursiveTruncate);
45
+ return obj.map((item) => recursiveTruncate(item)); // Corrigido para processar elementos do array
12
46
  } else if (obj !== null && typeof obj === "object") {
13
47
  return Object.fromEntries(
14
48
  Object.entries(obj).map(([key, value]) => [
15
49
  key,
16
- truncateValue(key, recursiveTruncate(value)),
50
+ recursiveTruncate(value), // Corrigido para aplicar recursão corretamente
17
51
  ])
18
52
  );
19
53
  }
20
- return obj;
54
+ return truncateValue(obj); // Corrigido para truncar valores diretamente
21
55
  }
22
56
 
23
57
  try {
@@ -27,6 +61,6 @@ function truncateLargeFields(jsonString: string, maxLength = 1000): string {
27
61
  } catch (error) {
28
62
  throw new Error("Invalid JSON string");
29
63
  }
30
- }
64
+ };
31
65
 
32
66
  export { truncateLargeFields };
@@ -0,0 +1,38 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { validateCpf } from "../validateCpf";
3
+
4
+ describe("validateCpf", () => {
5
+ it("should return false for an empty CPF", () => {
6
+ expect(validateCpf("")).toBe(false);
7
+ });
8
+
9
+ it("should return false for a CPF with invalid length", () => {
10
+ expect(validateCpf("123.456")).toBe(false);
11
+ expect(validateCpf("123.456.789.123")).toBe(false);
12
+ });
13
+
14
+ it("should return false for a CPF with all digits equal", () => {
15
+ expect(validateCpf("111.111.111-11")).toBe(false);
16
+ expect(validateCpf("222.222.222-22")).toBe(false);
17
+ });
18
+
19
+ it("should return false for an invalid CPF", () => {
20
+ expect(validateCpf("123.456.789-19")).toBe(false);
21
+ expect(validateCpf("987.654.321-01")).toBe(false);
22
+ });
23
+
24
+ it("should return true for a valid CPF", () => {
25
+ expect(validateCpf("111.444.777-35")).toBe(true);
26
+ expect(validateCpf("935.411.347-80")).toBe(true);
27
+ });
28
+
29
+ it("should ignore formatting characters and validate correctly", () => {
30
+ expect(validateCpf("11144477735")).toBe(true);
31
+ expect(validateCpf("935.411.347-80")).toBe(true);
32
+ });
33
+
34
+ it("should return false for a CPF with non-digit characters", () => {
35
+ expect(validateCpf("111.444.777-3a")).toBe(false);
36
+ expect(validateCpf("935.411.347-8x")).toBe(false);
37
+ });
38
+ });
@@ -0,0 +1,81 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { validateDate } from "../validateDate";
3
+
4
+ describe("validateDate", () => {
5
+ it("should return true for valid dates in DD/MM/YYYY format", () => {
6
+ expect(validateDate("31/12/2023")).toBe(true);
7
+ expect(validateDate("29/02/2024", { inputFormat: "DD/MM/YYYY" })).toBe(
8
+ true
9
+ ); // Leap year
10
+ });
11
+
12
+ it("should return false for invalid dates in DD/MM/YYYY format", () => {
13
+ expect(validateDate("31/04/2023", { inputFormat: "DD/MM/YYYY" })).toBe(
14
+ false
15
+ ); // April has 30 days
16
+ expect(validateDate("29/02/2023", { inputFormat: "DD/MM/YYYY" })).toBe(
17
+ false
18
+ ); // Not a leap year
19
+ expect(validateDate("32/01/2023", { inputFormat: "DD/MM/YYYY" })).toBe(
20
+ false
21
+ ); // Invalid day
22
+ });
23
+
24
+ it("should return true for valid dates in MM-DD-YYYY format", () => {
25
+ expect(validateDate("12-31-2023", { inputFormat: "MM-DD-YYYY" })).toBe(
26
+ true
27
+ );
28
+ });
29
+
30
+ it("should return false for invalid dates in MM-DD-YYYY format", () => {
31
+ expect(validateDate("04-31-2023", { inputFormat: "MM-DD-YYYY" })).toBe(
32
+ false
33
+ ); // April has 30 days
34
+ expect(validateDate("02-29-2023", { inputFormat: "MM-DD-YYYY" })).toBe(
35
+ false
36
+ ); // Not a leap year
37
+ expect(validateDate("13-01-2023", { inputFormat: "MM-DD-YYYY" })).toBe(
38
+ false
39
+ ); // Invalid month
40
+ });
41
+
42
+ it("should return true for valid dates in YYYY-MM-DD format", () => {
43
+ expect(validateDate("2023-12-31", { inputFormat: "YYYY-MM-DD" })).toBe(
44
+ true
45
+ );
46
+ expect(validateDate("2024-02-29", { inputFormat: "YYYY-MM-DD" })).toBe(
47
+ true
48
+ ); // Leap year
49
+ });
50
+
51
+ it("should return false for invalid dates in YYYY-MM-DD format", () => {
52
+ expect(validateDate("2023-04-31", { inputFormat: "YYYY-MM-DD" })).toBe(
53
+ false
54
+ ); // April has 30 days
55
+ expect(validateDate("2023-02-29", { inputFormat: "YYYY-MM-DD" })).toBe(
56
+ false
57
+ ); // Not a leap year
58
+ expect(validateDate("2023-13-01", { inputFormat: "YYYY-MM-DD" })).toBe(
59
+ false
60
+ ); // Invalid month
61
+ });
62
+
63
+ it("should respect minYear and maxYear configuration", () => {
64
+ expect(validateDate("01/01/1899", { minYear: 1900 })).toBe(false); // Below minYear
65
+ expect(validateDate("01/01/1900", { minYear: 1900 })).toBe(true); // Equal to minYear
66
+ expect(validateDate("31/12/3001", { maxYear: 3000 })).toBe(false); // Above maxYear
67
+ expect(validateDate("31/12/3000", { maxYear: 3000 })).toBe(true); // Equal to maxYear
68
+ });
69
+
70
+ it("should throw an error for unsupported date formats", () => {
71
+ expect(() =>
72
+ validateDate("2023.12.31", { inputFormat: "YYYY.MM.DD" } as any)
73
+ ).toThrow("Invalid date format");
74
+ });
75
+
76
+ it("should return false for completely invalid date strings", () => {
77
+ expect(validateDate("invalid-date")).toBe(false);
78
+ expect(validateDate("12345678")).toBe(false);
79
+ expect(validateDate("")).toBe(false);
80
+ });
81
+ });
@@ -0,0 +1,39 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { validatePhone } from "../validatePhone";
3
+
4
+ describe("validatePhone", () => {
5
+ it("should return true for valid Brazilian phone numbers", () => {
6
+ expect(validatePhone("+55 32912345678")).toBe(true); // Valid with 9th digit
7
+ expect(validatePhone("+55 3212345678")).toBe(true); // Valid without 9th digit
8
+ });
9
+
10
+ it("should return false for invalid Brazilian phone numbers", () => {
11
+ expect(validatePhone("+5532912345678")).toBe(false); // Missing space
12
+ expect(validatePhone("+55 123456789")).toBe(false); // Invalid format
13
+ });
14
+
15
+ it("should return true for valid American Samoa phone numbers", () => {
16
+ expect(validatePhone("+1-684 1234567")).toBe(true); // Valid format
17
+ });
18
+
19
+ it("should return false for invalid phone numbers", () => {
20
+ expect(validatePhone("+1-684 12345")).toBe(false); // Too few digits
21
+ expect(validatePhone("+99 1234567890")).toBe(false); // Non-existent country code
22
+ });
23
+
24
+ it("should return true for valid phone numbers from other countries", () => {
25
+ expect(validatePhone("+44 1234567890")).toBe(true); // Example for UK
26
+ expect(validatePhone("+91 9876543210")).toBe(true); // Example for India
27
+ });
28
+
29
+ it("should return false for phone numbers with incorrect prefixes", () => {
30
+ expect(validatePhone("+44-20 12345678")).toBe(false); // Invalid prefix for UK
31
+ expect(validatePhone("+91-80 12345678")).toBe(false); // Invalid prefix for India
32
+ });
33
+
34
+ it("should handle edge cases gracefully", () => {
35
+ expect(validatePhone("")).toBe(false); // Empty string
36
+ expect(validatePhone("+55")).toBe(false); // Only country code
37
+ expect(validatePhone("+55 329123456789")).toBe(false); // Too many digits
38
+ });
39
+ });
@@ -0,0 +1,64 @@
1
+ import type { ValidateCpfFunction } from "@arkyn/types";
2
+
3
+ function removeNonDigits(cpf: string) {
4
+ return cpf.replace(/\D/g, "");
5
+ }
6
+
7
+ function isInvalidLength(cpf: string) {
8
+ const CPF_LENGTH = 11;
9
+ return cpf.length !== CPF_LENGTH;
10
+ }
11
+
12
+ function hasAllDigitsEqual(cpf: string) {
13
+ const [firstCpfDigit] = cpf;
14
+ return [...cpf].every((digit) => digit === firstCpfDigit);
15
+ }
16
+
17
+ function calculateDigit(cpf: string, factor: number) {
18
+ let total = 0;
19
+ for (const digit of cpf) {
20
+ if (factor > 1) total += parseInt(digit) * factor--;
21
+ }
22
+ const rest = total % 11;
23
+ return rest < 2 ? 0 : 11 - rest;
24
+ }
25
+
26
+ function extractDigit(cpf: string) {
27
+ return cpf.slice(9);
28
+ }
29
+
30
+ /**
31
+ * Validates a Brazilian CPF (Cadastro de Pessoas Físicas) number.
32
+ *
33
+ * The CPF is a unique identifier assigned to Brazilian citizens and residents.
34
+ * This function checks if the provided CPF is valid by performing the following steps:
35
+ * - Removes any non-digit characters from the input.
36
+ * - Verifies if the CPF has the correct length (11 digits).
37
+ * - Ensures that all digits are not the same (e.g., "111.111.111-11" is invalid).
38
+ * - Calculates the first and second verification digits using the CPF algorithm.
39
+ * - Compares the calculated verification digits with the ones provided in the CPF.
40
+ *
41
+ * @param rawCpf - The raw CPF string, which may include formatting characters (e.g., dots or dashes).
42
+ * @returns `true` if the CPF is valid, otherwise `false`.
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * validateCpf("123.456.789-09"); // false
47
+ * validateCpf("111.444.777-35"); // true
48
+ * ```
49
+ */
50
+
51
+ const validateCpf: ValidateCpfFunction = (rawCpf) => {
52
+ if (!rawCpf) return false;
53
+ const cpf = removeNonDigits(rawCpf);
54
+
55
+ if (isInvalidLength(cpf)) return false;
56
+ if (hasAllDigitsEqual(cpf)) return false;
57
+
58
+ const digit1 = calculateDigit(cpf, 10);
59
+ const digit2 = calculateDigit(cpf, 11);
60
+
61
+ return extractDigit(cpf) === `${digit1}${digit2}`;
62
+ };
63
+
64
+ export { validateCpf };
@@ -1,25 +1,47 @@
1
- type Format = "DD/MM/YYYY" | "MM-DD-YYYY" | "YYYY-MM-DD";
1
+ import type { ValidateDateFunction } from "@arkyn/types";
2
2
 
3
- type Config = {
4
- minYear?: number;
5
- maxYear?: number;
6
- };
3
+ /**
4
+ * Validates a date string based on the provided format and configuration.
5
+ *
6
+ * @param date - The date string to validate.
7
+ * @param config - Optional configuration object to customize validation.
8
+ * @param config.inputFormat - The expected format of the input date.
9
+ * Supported formats are "DD/MM/YYYY", "MM-DD-YYYY", and "YYYY-MM-DD".
10
+ * Defaults to "DD/MM/YYYY".
11
+ * @param config.minYear - The minimum allowed year for the date. Defaults to 1900.
12
+ * @param config.maxYear - The maximum allowed year for the date. Defaults to 3000.
13
+ *
14
+ * @returns `true` if the date is valid according to the specified format and configuration, otherwise `false`.
15
+ *
16
+ * @throws {Error} If an invalid date format is provided in the configuration.
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * validateDate("31/12/2023"); // true
21
+ * validateDate("12-31-2023", { inputFormat: "MM-DD-YYYY" }); // true
22
+ * validateDate("2023-12-31", { inputFormat: "YYYY-MM-DD", minYear: 2000, maxYear: 2100 }); // true
23
+ * validateDate("29/02/2024", { inputFormat: "DD/MM/YYYY" }); // true (leap year)
24
+ * validateDate("29/02/2023", { inputFormat: "DD/MM/YYYY" }); // false (not a leap year)
25
+ * validateDate("31/04/2023", { inputFormat: "DD/MM/YYYY" }); // false (April has 30 days)
26
+ * ```
27
+ */
7
28
 
8
- function validateDate(date: string, format: Format, config?: Config): boolean {
29
+ const validateDate: ValidateDateFunction = (date, config) => {
9
30
  let day: string, month: string, year: string;
10
31
 
11
- const minYear = config?.minYear || 0;
32
+ const inputFormat = config?.inputFormat || "DD/MM/YYYY";
33
+ const minYear = config?.minYear || 1900;
12
34
  const maxYear = config?.maxYear || 3000;
13
35
 
14
- if (format === "DD/MM/YYYY") {
36
+ if (inputFormat === "DD/MM/YYYY") {
15
37
  const dateRegex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
16
38
  if (!dateRegex.test(date)) return false;
17
39
  [, day, month, year] = date.match(dateRegex) || [];
18
- } else if (format === "MM-DD-YYYY") {
40
+ } else if (inputFormat === "MM-DD-YYYY") {
19
41
  const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
20
42
  if (!dateRegex.test(date)) return false;
21
43
  [, month, day, year] = date.match(dateRegex) || [];
22
- } else if (format === "YYYY-MM-DD") {
44
+ } else if (inputFormat === "YYYY-MM-DD") {
23
45
  const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
24
46
  if (!dateRegex.test(date)) return false;
25
47
  [, year, month, day] = date.match(dateRegex) || [];
@@ -50,6 +72,6 @@ function validateDate(date: string, format: Format, config?: Config): boolean {
50
72
  new Date(yearNum, monthNum - 1, dayNum).getDate() === dayNum;
51
73
 
52
74
  return isValidDate;
53
- }
75
+ };
54
76
 
55
77
  export { validateDate };