@arkyn/shared 3.0.1-beta.155 → 3.0.1-beta.156

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 (55) hide show
  1. package/dist/index.js +371 -30
  2. package/dist/modules/formats/formatDate.js +42 -0
  3. package/dist/modules/formats/formatJsonObject.js +32 -0
  4. package/dist/modules/formats/formatJsonString.js +13 -0
  5. package/dist/modules/formats/formatToCapitalizeFirstWordLetter.js +9 -0
  6. package/dist/modules/formats/formatToCep.js +9 -0
  7. package/dist/modules/formats/formatToCnpj.js +9 -0
  8. package/dist/modules/formats/formatToCpf.js +9 -0
  9. package/dist/modules/formats/formatToCurrency.js +15 -0
  10. package/dist/modules/formats/formatToEllipsis.js +11 -0
  11. package/dist/modules/formats/formatToHiddenDigits.js +12 -0
  12. package/dist/modules/formats/formatToPhone.js +17 -0
  13. package/dist/modules/generators/generateColorByString.js +9 -0
  14. package/dist/modules/generators/generateId.js +26 -0
  15. package/dist/modules/generators/generateSlug.js +7 -0
  16. package/dist/modules/index.js +52 -0
  17. package/dist/modules/parsers/parseLargeFields.js +22 -0
  18. package/dist/modules/parsers/parseSensitiveData.js +26 -0
  19. package/dist/modules/parsers/parseToDate.js +27 -0
  20. package/dist/modules/services/validateDateService.js +59 -0
  21. package/dist/modules/utilities/calculateCardInstallment.js +21 -0
  22. package/dist/modules/utilities/ensureQuotes.js +7 -0
  23. package/dist/modules/utilities/findCountryMask.js +25 -0
  24. package/dist/modules/utilities/isHtml.js +6 -0
  25. package/dist/modules/utilities/removeCurrencySymbols.js +6 -0
  26. package/dist/modules/utilities/removeNonNumeric.js +6 -0
  27. package/dist/modules/utilities/stripHtmlTags.js +6 -0
  28. package/package.json +100 -74
  29. package/dist/bundle.js +0 -3719
  30. package/dist/bundle.umd.cjs +0 -10
  31. package/dist/formats/formatDate.js +0 -65
  32. package/dist/formats/formatJsonObject.js +0 -89
  33. package/dist/formats/formatJsonString.js +0 -30
  34. package/dist/formats/formatToCapitalizeFirstWordLetter.js +0 -23
  35. package/dist/formats/formatToCep.js +0 -28
  36. package/dist/formats/formatToCnpj.js +0 -26
  37. package/dist/formats/formatToCpf.js +0 -28
  38. package/dist/formats/formatToCurrency.js +0 -31
  39. package/dist/formats/formatToEllipsis.js +0 -32
  40. package/dist/formats/formatToHiddenDigits.js +0 -49
  41. package/dist/formats/formatToPhone.js +0 -43
  42. package/dist/generators/generateColorByString.js +0 -28
  43. package/dist/generators/generateId.js +0 -29
  44. package/dist/generators/generateSlug.js +0 -31
  45. package/dist/parsers/parseLargeFields.js +0 -55
  46. package/dist/parsers/parseSensitiveData.js +0 -57
  47. package/dist/parsers/parseToDate.js +0 -51
  48. package/dist/services/validateDateService.js +0 -81
  49. package/dist/utilities/calculateCardInstallment.js +0 -39
  50. package/dist/utilities/ensureQuotes.js +0 -26
  51. package/dist/utilities/findCountryMask.js +0 -49
  52. package/dist/utilities/isHtml.js +0 -23
  53. package/dist/utilities/removeCurrencySymbols.js +0 -23
  54. package/dist/utilities/removeNonNumeric.js +0 -16
  55. package/dist/utilities/stripHtmlTags.js +0 -23
@@ -1,89 +0,0 @@
1
- /**
2
- * Formats a JSON object into a human-readable string with proper indentation.
3
- *
4
- * - If the input is an object, it will be formatted with keys and values properly indented.
5
- * - If the input is an array, each element will be formatted and indented on a new line.
6
- * - If the input is a string that can be parsed as JSON, it will attempt to parse and format it.
7
- * - Primitive values (e.g., numbers, booleans, null) will be converted to their string representation.
8
- *
9
- * @param json - The value to format: object, array, string, or primitive.
10
- * @param indentLevel - Current indentation depth (used recursively; pass `0` at the top level).
11
- * @returns A pretty-printed string representation of the value.
12
- *
13
- * @example
14
- * ```typescript
15
- * const obj = { name: "John", age: 30, hobbies: ["reading", "gaming"] };
16
- * const formatted = formatJsonObject(obj, 0);
17
- * console.log(formatted);
18
- * // Output:
19
- * // {
20
- * // "name": "John",
21
- * // "age": 30,
22
- * // "hobbies": [
23
- * // "reading",
24
- * // "gaming"
25
- * // ]
26
- * // }
27
- * ```
28
- */
29
- const formatJsonObject = (json, indentLevel) => {
30
- const indent = " ".repeat(indentLevel);
31
- let formattedString = "";
32
- if (typeof json === "object" && json !== null) {
33
- if (Array.isArray(json)) {
34
- if (json.length === 0) {
35
- // Caso especial para arrays vazios
36
- formattedString += "[]";
37
- }
38
- else {
39
- formattedString += "[\n";
40
- json.forEach((item, index) => {
41
- formattedString +=
42
- indent + " " + formatJsonObject(item, indentLevel + 1);
43
- if (index < json.length - 1) {
44
- formattedString += ",";
45
- }
46
- formattedString += "\n";
47
- });
48
- formattedString += indent + "]";
49
- }
50
- }
51
- else {
52
- const keys = Object.keys(json);
53
- if (keys.length === 0) {
54
- // Caso especial para objetos vazios
55
- formattedString += "{}";
56
- }
57
- else {
58
- formattedString += "{\n";
59
- keys.forEach((key, index) => {
60
- formattedString +=
61
- indent +
62
- ' "' +
63
- key +
64
- '": ' +
65
- formatJsonObject(json[key], indentLevel + 1);
66
- if (index < keys.length - 1) {
67
- formattedString += ",";
68
- }
69
- formattedString += "\n";
70
- });
71
- formattedString += indent + "}";
72
- }
73
- }
74
- }
75
- else if (typeof json === "string") {
76
- try {
77
- const parsedObj = JSON.parse(json);
78
- formattedString += formatJsonObject(parsedObj, indentLevel);
79
- }
80
- catch {
81
- formattedString += '"' + json + '"';
82
- }
83
- }
84
- else {
85
- formattedString += json;
86
- }
87
- return formattedString;
88
- };
89
- export { formatJsonObject };
@@ -1,30 +0,0 @@
1
- import { formatJsonObject } from "./formatJsonObject";
2
- /**
3
- * Parses a JSON string and returns a human-readable pretty-printed representation.
4
- * Throws if the input is not valid JSON.
5
- *
6
- * @param jsonString - A valid JSON string to format.
7
- * @returns A pretty-printed string representation.
8
- *
9
- * @example
10
- * ```typescript
11
- * formatJsonString('{"name":"John","hobbies":["reading","gaming"]}');
12
- * // {
13
- * // "name": "John",
14
- * // "hobbies": [
15
- * // "reading",
16
- * // "gaming"
17
- * // ]
18
- * // }
19
- * ```
20
- */
21
- const formatJsonString = (jsonString) => {
22
- try {
23
- const jsonObject = JSON.parse(jsonString);
24
- return formatJsonObject(jsonObject, 0);
25
- }
26
- catch (error) {
27
- throw new Error(`Invalid JSON string \n ${error}`);
28
- }
29
- };
30
- export { formatJsonString };
@@ -1,23 +0,0 @@
1
- /**
2
- * Capitalizes the first letter of each word and lowercases the rest.
3
- * Words are separated by spaces.
4
- *
5
- * @param sentence - The string to format.
6
- * @returns The sentence with every word title-cased.
7
- *
8
- * @example
9
- * ```typescript
10
- * formatToCapitalizeFirstWordLetter("hello world"); // "Hello World"
11
- * formatToCapitalizeFirstWordLetter("HELLO WORLD"); // "Hello World"
12
- * ```
13
- */
14
- function formatToCapitalizeFirstWordLetter(sentence) {
15
- const words = sentence.split(" ");
16
- const capitalizedWords = words.map((word) => {
17
- const firstLetter = word.charAt(0).toUpperCase();
18
- const restOfWord = word.slice(1).toLowerCase();
19
- return firstLetter + restOfWord;
20
- });
21
- return capitalizedWords.join(" ");
22
- }
23
- export { formatToCapitalizeFirstWordLetter };
@@ -1,28 +0,0 @@
1
- import { removeNonNumeric } from "../utilities/removeNonNumeric";
2
- /**
3
- * Formats a given string into a Brazilian postal code (CEP) format.
4
- *
5
- * The function removes all non-numeric characters from the input string
6
- * and attempts to format it as a CEP in the pattern `XXXXX-XXX`.
7
- * If the input does not match the expected format, an error is thrown.
8
- *
9
- * @param value - Input string with 8 numeric digits (special characters are stripped).
10
- * @returns The formatted CEP string in the pattern `XXXXX-XXX`.
11
- *
12
- * @throws {Error} If the input does not match the expected CEP format.
13
- *
14
- * @example
15
- * ```typescript
16
- * const formattedCep = formatToCep("12345678");
17
- * console.log(formattedCep); // Output: "12345-678"
18
- * ```
19
- */
20
- function formatToCep(value) {
21
- const cleaned = removeNonNumeric(value);
22
- const match = cleaned.match(/^(\d{5})(\d{3})$/);
23
- const errorMessage = `CEP must be contain 8 numeric digits: ${value}`;
24
- if (!match)
25
- throw new Error(errorMessage);
26
- return `${match[1]}-${match[2]}`;
27
- }
28
- export { formatToCep };
@@ -1,26 +0,0 @@
1
- import { removeNonNumeric } from "../utilities/removeNonNumeric";
2
- /**
3
- * Formats a given string or number into a CNPJ (Cadastro Nacional da Pessoa Jurídica) format.
4
- *
5
- * The CNPJ format is: `XX.XXX.XXX/XXXX-XX`, where `X` represents a digit.
6
- *
7
- * @param value - Input string with 14 numeric digits (special characters are stripped).
8
- * @returns The formatted CNPJ string in the pattern `XX.XXX.XXX/XXXX-XX`.
9
- *
10
- * @throws {Error} Throws an error if the input does not contain exactly 14 numeric digits.
11
- *
12
- * @example
13
- * ```typescript
14
- * const formattedCnpj = formatToCnpj("12345678000195");
15
- * console.log(formattedCnpj); // Output: "12.345.678/0001-95"
16
- * ```
17
- */
18
- function formatToCnpj(value) {
19
- const cleaned = removeNonNumeric(value);
20
- const match = cleaned.match(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/);
21
- const errorMessage = `CNPJ must be contain 14 numeric digits: ${value}`;
22
- if (!match)
23
- throw new Error(errorMessage);
24
- return `${match[1]}.${match[2]}.${match[3]}/${match[4]}-${match[5]}`;
25
- }
26
- export { formatToCnpj };
@@ -1,28 +0,0 @@
1
- import { removeNonNumeric } from "../utilities/removeNonNumeric";
2
- /**
3
- * Formats a given string into a CPF (Cadastro de Pessoas Físicas) format.
4
- *
5
- * A CPF is a Brazilian individual taxpayer registry identification format.
6
- * This function ensures the input is cleaned of non-numeric characters and
7
- * then formats it into the standard CPF format: `XXX.XXX.XXX-XX`.
8
- *
9
- * @param value - Input string with 11 numeric digits (special characters are stripped).
10
- * @returns The formatted CPF string in the pattern `XXX.XXX.XXX-XX`.
11
- *
12
- * @throws {Error} If the input string does not match the expected CPF format.
13
- *
14
- * @example
15
- * ```typescript
16
- * const formattedCpf = formatToCpf("12345678909");
17
- * console.log(formattedCpf); // Output: "123.456.789-09"
18
- * ```
19
- */
20
- function formatToCpf(value) {
21
- const cleaned = removeNonNumeric(value);
22
- const match = cleaned.match(/^(\d{3})(\d{3})(\d{3})(\d{2})$/);
23
- const errorMessage = `CPF must be contain 11 numeric digits: ${value}`;
24
- if (!match)
25
- throw new Error(errorMessage);
26
- return `${match[1]}.${match[2]}.${match[3]}-${match[4]}`;
27
- }
28
- export { formatToCpf };
@@ -1,31 +0,0 @@
1
- import { countryCurrencies } from "@arkyn/templates";
2
- import { removeCurrencySymbols } from "../utilities/removeCurrencySymbols";
3
- /**
4
- * Formats a number into a locale-aware currency string using `Intl.NumberFormat`.
5
- *
6
- * @param value - The numeric value to format.
7
- * @param currency - A currency code from `@arkyn/templates` (e.g. `"BRL"`, `"USD"`).
8
- * @param config.showPrefix - Whether to include the currency symbol. Defaults to `true`.
9
- * @returns The formatted currency string.
10
- *
11
- * @example
12
- * ```typescript
13
- * formatToCurrency(1234.56, "BRL"); // "R$ 1.234,56"
14
- * formatToCurrency(1234.56, "USD", { showPrefix: false }); // "1,234.56"
15
- * ```
16
- */
17
- function formatToCurrency(value, currency, config) {
18
- if (!countryCurrencies?.[currency]) {
19
- throw new Error("Unsupported currency code");
20
- }
21
- const showPrefix = config?.showPrefix ?? true;
22
- const { countryCurrency, countryLanguage } = countryCurrencies[currency];
23
- const format = new Intl.NumberFormat(countryLanguage, {
24
- style: "currency",
25
- currency: countryCurrency,
26
- }).format(value);
27
- return showPrefix
28
- ? format.replace(/\s/g, " ")
29
- : removeCurrencySymbols(format).replace(/\s/g, " ");
30
- }
31
- export { formatToCurrency };
@@ -1,32 +0,0 @@
1
- /**
2
- * Truncates a given text to a specified maximum length and appends an ellipsis ("...")
3
- * if the text exceeds the maximum length.
4
- *
5
- * @param text - The input string to be truncated.
6
- * @param maxLength - Maximum allowed length before truncation.
7
- * @returns The truncated string with `"..."` appended, or the original string if it fits.
8
- * @example
9
- * ```typescript
10
- * const result = formatToEllipsis("Hello, world!", 5);
11
- * console.log(result); // Output: "Hello..."
12
- * ```
13
- */
14
- function formatToEllipsis(text, maxLength) {
15
- if (text.length > maxLength) {
16
- let trimmedText = text.substring(0, maxLength);
17
- // Find the last space to avoid breaking words
18
- const lastSpaceIndex = trimmedText.lastIndexOf(" ");
19
- if (lastSpaceIndex > 0) {
20
- trimmedText = trimmedText.substring(0, lastSpaceIndex);
21
- }
22
- // Remove trailing punctuation
23
- trimmedText = trimmedText.replace(/[\s.,!?;:]+$/, "");
24
- // If after removing punctuation the text is empty or only contains punctuation/spaces, return only "..."
25
- if (trimmedText.trim().length === 0 || /^[.,!?;:\s]+$/.test(trimmedText)) {
26
- return "...";
27
- }
28
- return `${trimmedText}...`;
29
- }
30
- return text;
31
- }
32
- export { formatToEllipsis };
@@ -1,49 +0,0 @@
1
- const DIGIT = /^\d$/;
2
- const parseToCharacters = (value) => {
3
- let digits = 0;
4
- const children = value
5
- .split("")
6
- .map((character) => {
7
- if (DIGIT.test(character))
8
- return { character, kind: "digit", digit: ++digits };
9
- return { character, kind: "other" };
10
- });
11
- return { digits, children, kind: "root" };
12
- };
13
- const normalizeRange = (range, limit) => {
14
- if (Array.isArray(range))
15
- return range;
16
- if (range >= 0)
17
- return [0, range];
18
- return [limit + 1 - Math.abs(range), limit];
19
- };
20
- const within = (range, value) => value >= range[0] && value <= range[1];
21
- /**
22
- * Replaces specific digits in a string with a masking character, leaving non-digit characters unchanged.
23
- *
24
- * @param value - The input string to mask.
25
- * @param options.range - Which digits to hide:
26
- * - Positive number `n` — hides the first `n` digits.
27
- * - Negative number `-n` — hides the last `n` digits.
28
- * - Tuple `[start, end]` — hides digits from position `start` to `end` (inclusive, 1-indexed).
29
- * - Defaults to `3`.
30
- * @param options.hider - The masking character. Defaults to `"*"`.
31
- * @returns The string with the specified digit positions replaced.
32
- *
33
- * @example
34
- * ```typescript
35
- * formatToHiddenDigits("123-456-7890", { range: 3 }); // "***-456-7890"
36
- * formatToHiddenDigits("123-456-7890", { range: [4, 6], hider: "#" }); // "123-###-7890"
37
- * ```
38
- */
39
- function formatToHiddenDigits(value, options) {
40
- const characters = parseToCharacters(value);
41
- const range = normalizeRange(options?.range ?? 3, characters.digits);
42
- const mappedCharacters = characters.children.map((node) => {
43
- if (node.kind === "digit" && within(range, node.digit))
44
- return options?.hider ?? "*";
45
- return node.character;
46
- });
47
- return mappedCharacters.join("");
48
- }
49
- export { formatToHiddenDigits };
@@ -1,43 +0,0 @@
1
- import { parsePhoneNumberWithError } from "libphonenumber-js";
2
- import { findCountryMask } from "../utilities/findCountryMask";
3
- /**
4
- * Formats a phone number string according to the country mask defined in `@arkyn/templates`.
5
- *
6
- * The function parses the input using libphonenumber-js to determine the country and
7
- * national number, then applies the corresponding country's mask (underscore `_` used
8
- * as digit placeholder) replacing placeholders with actual digits.
9
- *
10
- * @param phoneNumber - The input phone number in E.164 format (e.g. `"+5534920524282"`).
11
- * @returns The phone number formatted according to the country's mask.
12
- *
13
- * @throws {Error} If the phone number is invalid or if no country mask is found for the parsed country.
14
- *
15
- * @example
16
- * ```typescript
17
- * console.log(formatToPhone("+5534920524282")); // Output: "(34) 92052-4282" (Brazilian format)
18
- * console.log(formatToPhone("+553420524282")); // Output: "(34) 2052-4282" (Brazilian format with optional ninth digit)
19
- * console.log(formatToPhone("+12125550199")); // Output: "(212) 555-0199" (American Samoa format)
20
- * ```
21
- */
22
- function formatToPhone(phoneNumber) {
23
- try {
24
- const parsedPhone = parsePhoneNumberWithError(phoneNumber);
25
- const phoneNumberDigits = parsedPhone.nationalNumber.toString();
26
- let formattedNumber = findCountryMask(phoneNumber)[0];
27
- for (let i = 0, j = 0; i < formattedNumber.length && j < phoneNumberDigits.length; i++) {
28
- if (formattedNumber[i] === "_") {
29
- formattedNumber =
30
- formattedNumber.substring(0, i) +
31
- phoneNumberDigits[j] +
32
- formattedNumber.substring(i + 1);
33
- j++;
34
- }
35
- }
36
- return formattedNumber;
37
- }
38
- catch (rawError) {
39
- const error = rawError;
40
- throw new Error(error.message);
41
- }
42
- }
43
- export { formatToPhone };
@@ -1,28 +0,0 @@
1
- /**
2
- * Generates a hexadecimal color code based on the input string.
3
- * The function creates a hash from the string and uses it to calculate
4
- * RGB values, which are then converted to a hexadecimal color code.
5
- *
6
- * @param rawString - The input string used to generate the color.
7
- * @returns A hexadecimal color code (e.g., `"#a1b2c3"`) derived from the input string.
8
- *
9
- * @example
10
- * ```typescript
11
- * const color = generateColorByString("example");
12
- * console.log(color); // Outputs a consistent hex color like "#5e8f9a"
13
- * ```
14
- */
15
- function generateColorByString(rawString) {
16
- var hash = 0;
17
- for (var i = 0; i < rawString.length; i++) {
18
- hash = rawString.charCodeAt(i) + ((hash << 5) - hash);
19
- }
20
- var red = (hash & 0xff0000) >> 16;
21
- var green = (hash & 0x00ff00) >> 8;
22
- var blue = hash & 0x0000ff;
23
- var redHex = red.toString(16).padStart(2, "0");
24
- var greenHex = green.toString(16).padStart(2, "0");
25
- var blueHex = blue.toString(16).padStart(2, "0");
26
- return "#" + redHex + greenHex + blueHex;
27
- }
28
- export { generateColorByString };
@@ -1,29 +0,0 @@
1
- import { v4, v7 } from "uuid";
2
- function hexToBin(hex) {
3
- hex = hex.replace(/-/g, "");
4
- const buffer = new Uint8Array(hex.length / 2);
5
- for (let i = 0; i < hex.length; i += 2) {
6
- buffer[i / 2] = parseInt(hex.substring(i, i + 2), 16);
7
- }
8
- return buffer;
9
- }
10
- function uuidV4() {
11
- const uuid = v4();
12
- return { text: uuid, binary: hexToBin(uuid) };
13
- }
14
- function uuidV7() {
15
- const uuid = v7();
16
- return { text: uuid, binary: hexToBin(uuid) };
17
- }
18
- function generateId(type, format) {
19
- if (type === "text" && format === "v4")
20
- return uuidV4().text;
21
- if (type === "binary" && format === "v4")
22
- return uuidV4().binary;
23
- if (type === "text" && format === "v7")
24
- return uuidV7().text;
25
- if (type === "binary" && format === "v7")
26
- return uuidV7().binary;
27
- throw new Error("Invalid type or format");
28
- }
29
- export { generateId };
@@ -1,31 +0,0 @@
1
- /**
2
- * Generates a URL-friendly slug from a given string.
3
- *
4
- * The function performs the following transformations:
5
- * - Normalizes the string to remove diacritical marks (e.g., accents).
6
- * - Removes non-alphanumeric characters except for spaces and hyphens.
7
- * - Replaces spaces with hyphens.
8
- * - Converts the string to lowercase.
9
- * - Collapses multiple consecutive hyphens into a single hyphen.
10
- * - Trims leading and trailing hyphens.
11
- *
12
- * @param rawString - The input string to be converted into a slug.
13
- * @returns A URL-friendly slug derived from the input string.
14
- *
15
- * @example
16
- * ```typescript
17
- * const slug = generateSlug("Hello, World! This is a Test.");
18
- * console.log(slug); // Outputs: "hello-world-this-is-a-test"
19
- * ```
20
- */
21
- function generateSlug(rawString) {
22
- let slug = rawString.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
23
- slug = slug
24
- .replace(/[^\w\s-]/g, "")
25
- .replace(/\s+/g, "-")
26
- .toLowerCase();
27
- slug = slug.replace(/-{2,}/g, "-");
28
- slug = slug.replace(/^-+|-+$/g, "");
29
- return slug;
30
- }
31
- export { generateSlug };
@@ -1,55 +0,0 @@
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: { details: "Another long string that needs truncation." }
20
- * });
21
- *
22
- * const result = parseLargeFields(json, 50);
23
- * console.log(result);
24
- * // Output: '{"name":"John","description":"To large information: field as 57 characters","nested":{"details":"To large information: field as 43 characters"}}'
25
- * ```
26
- */
27
- function parseLargeFields(jsonString, maxLength = 1000) {
28
- function truncateValue(value) {
29
- if (typeof value === "string" && value.length > maxLength) {
30
- return `To large information: field as ${value.length} characters`;
31
- }
32
- return value;
33
- }
34
- function recursiveTruncate(obj) {
35
- if (Array.isArray(obj)) {
36
- return obj.map((item) => recursiveTruncate(item));
37
- }
38
- else if (obj !== null && typeof obj === "object") {
39
- return Object.fromEntries(Object.entries(obj).map(([key, value]) => [
40
- key,
41
- recursiveTruncate(value),
42
- ]));
43
- }
44
- return truncateValue(obj);
45
- }
46
- try {
47
- const parsedJson = JSON.parse(jsonString);
48
- const truncatedJson = recursiveTruncate(parsedJson);
49
- return JSON.stringify(truncatedJson);
50
- }
51
- catch (error) {
52
- throw new Error("Invalid JSON string");
53
- }
54
- }
55
- export { parseLargeFields };
@@ -1,57 +0,0 @@
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 - Keys whose values will be replaced with `"****"`. Defaults to `["password", "confirmPassword", "creditCard"]`.
6
- * @returns A JSON string with sensitive values masked. Returns the original string if it is not valid JSON.
7
- *
8
- * @example
9
- * ```typescript
10
- * const jsonString = JSON.stringify({
11
- * username: "user123",
12
- * password: "secret",
13
- * profile: { creditCard: "1234-5678-9012-3456" },
14
- * });
15
- *
16
- * const result = parseSensitiveData(jsonString, ["password", "creditCard"]);
17
- * console.log(result); // Output: '{"username":"user123","password":"****","profile":{"creditCard":"****"}}'
18
- * ```
19
- */
20
- function parseSensitiveData(jsonString, sensitiveKeys = ["password", "confirmPassword", "creditCard"]) {
21
- function maskValue(key, value) {
22
- if (sensitiveKeys.includes(key))
23
- return "****";
24
- return value;
25
- }
26
- function recursiveMask(obj) {
27
- if (Array.isArray(obj)) {
28
- return obj.map((item) => recursiveMask(item));
29
- }
30
- else if (obj !== null && typeof obj === "object") {
31
- return Object.keys(obj).reduce((acc, key) => {
32
- let value = obj[key];
33
- if (typeof value === "string") {
34
- try {
35
- const parsedValue = JSON.parse(value);
36
- if (typeof parsedValue === "object") {
37
- value = JSON.stringify(recursiveMask(parsedValue));
38
- }
39
- }
40
- catch (e) { }
41
- }
42
- acc[key] = recursiveMask(maskValue(key, value));
43
- return acc;
44
- }, {});
45
- }
46
- return obj;
47
- }
48
- try {
49
- const jsonObject = JSON.parse(jsonString);
50
- const maskedObject = recursiveMask(jsonObject);
51
- return JSON.stringify(maskedObject);
52
- }
53
- catch (error) {
54
- return jsonString;
55
- }
56
- }
57
- export { parseSensitiveData };
@@ -1,51 +0,0 @@
1
- import { ValidateDateService } from "../services/validateDateService";
2
- /**
3
- * Parses a date (and optional time) string into a JavaScript `Date` object.
4
- * All calculations are in UTC+0; use `timezone` to shift the result.
5
- *
6
- * @param date - Date string in the format determined by `inputFormat`.
7
- * @param time - Optional time string `"HH:mm:ss"` (defaults to `"00:00:00"`).
8
- * @param inputFormat - Parsing format:
9
- * - `"brazilianDate"`: DD/MM/YYYY
10
- * - `"isoDate"`: MM-DD-YYYY
11
- * - `"timestamp"`: YYYY-MM-DD
12
- * @param timezone - UTC offset in hours (e.g. `-3` for UTC-3). Defaults to `0`.
13
- * @returns A `Date` object representing the parsed date and time.
14
- *
15
- * @example
16
- * ```typescript
17
- * parseToDate(["25/12/2023", "15:30:00"], "brazilianDate", -3);
18
- * // Date: 2023-12-25T12:30:00.000Z
19
- *
20
- * parseToDate(["2023-12-25"], "timestamp");
21
- * // Date: 2023-12-25T00:00:00.000Z
22
- * ```
23
- */
24
- function parseToDate([date, time = "00:00:00"], inputFormat, timezone = 0) {
25
- const validateDateService = new ValidateDateService();
26
- validateDateService.validateInputFormat(inputFormat);
27
- const dateParts = date.split(/[-/]/).map(Number);
28
- const timeParts = time.split(".")[0].split(":").map(Number);
29
- let day, month, year;
30
- const [hours = 0, minutes = 0, seconds = 0] = timeParts;
31
- switch (inputFormat) {
32
- case "brazilianDate":
33
- [day, month, year] = dateParts;
34
- validateDateService.validateDateParts(year, month, day);
35
- break;
36
- case "isoDate":
37
- [month, day, year] = dateParts;
38
- validateDateService.validateDateParts(year, month, day);
39
- break;
40
- case "timestamp":
41
- [year, month, day] = dateParts;
42
- validateDateService.validateDateParts(year, month, day);
43
- break;
44
- }
45
- const formattedDate = new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds));
46
- if (isNaN(formattedDate.getTime()))
47
- throw new Error("Invalid date");
48
- formattedDate.setUTCHours(formattedDate.getUTCHours() + timezone);
49
- return formattedDate;
50
- }
51
- export { parseToDate };