@trindtech/utils 1.3.0 → 1.4.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.
@@ -1,257 +0,0 @@
1
- import { countries } from "./countries";
2
-
3
- // ─── CPF ──────────────────────────────────────────────────────────────────────
4
-
5
- /**
6
- * Valida um CPF brasileiro (aceita com ou sem formatação).
7
- */
8
- export function isValidCPF(cpf: string): boolean {
9
- const digits = cpf.replace(/\D/g, "");
10
- if (digits.length !== 11 || /^(\d)\1+$/.test(digits)) return false;
11
-
12
- const calc = (mod: number) => {
13
- let sum = 0;
14
- for (let i = 0; i < mod - 1; i++) sum += parseInt(digits[i]) * (mod - i);
15
- const rest = (sum * 10) % 11;
16
- return rest === 10 || rest === 11 ? 0 : rest;
17
- };
18
-
19
- return calc(10) === parseInt(digits[9]) && calc(11) === parseInt(digits[10]);
20
- }
21
-
22
- /**
23
- * Formata um CPF para exibição (ex: "12345678909" → "123.456.789-09").
24
- */
25
- export function formatCPF(cpf: string): string {
26
- const d = cpf.replace(/\D/g, "");
27
- return d.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4");
28
- }
29
-
30
- // ─── CNPJ ─────────────────────────────────────────────────────────────────────
31
-
32
- /**
33
- * Valida um CNPJ brasileiro (aceita com ou sem formatação).
34
- */
35
- export function isValidCNPJ(cnpj: string): boolean {
36
- const digits = cnpj.replace(/\D/g, "");
37
- if (digits.length !== 14 || /^(\d)\1+$/.test(digits)) return false;
38
-
39
- const calc = (size: number) => {
40
- let sum = 0;
41
- let pos = size - 7;
42
- for (let i = size; i >= 1; i--) {
43
- sum += parseInt(digits[size - i]) * pos--;
44
- if (pos < 2) pos = 9;
45
- }
46
- const rest = sum % 11;
47
- return rest < 2 ? 0 : 11 - rest;
48
- };
49
-
50
- return calc(12) === parseInt(digits[12]) && calc(13) === parseInt(digits[13]);
51
- }
52
-
53
- /**
54
- * Formata um CNPJ para exibição (ex: "11222333000181" → "11.222.333/0001-81").
55
- */
56
- export function formatCNPJ(cnpj: string): string {
57
- const d = cnpj.replace(/\D/g, "");
58
- return d.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, "$1.$2.$3/$4-$5");
59
- }
60
-
61
- // ─── RG ───────────────────────────────────────────────────────────────────────
62
-
63
- /**
64
- * Valida um RG brasileiro (7 a 9 dígitos).
65
- */
66
- export function isValidRG(rg: string): boolean {
67
- const digits = rg.replace(/\D/g, "");
68
- return digits.length >= 7 && digits.length <= 9;
69
- }
70
-
71
- // ─── CEP ──────────────────────────────────────────────────────────────────────
72
-
73
- /**
74
- * Valida um CEP brasileiro.
75
- */
76
- export function isValidCEP(cep: string): boolean {
77
- const digits = cep.replace(/\D/g, "");
78
- return /^\d{8}$/.test(digits);
79
- }
80
-
81
- /**
82
- * Formata um CEP para exibição (ex: "01310100" → "01310-100").
83
- */
84
- export function formatCEP(cep: string): string {
85
- const d = cep.replace(/\D/g, "");
86
- return d.replace(/(\d{5})(\d{3})/, "$1-$2");
87
- }
88
-
89
- /**
90
- * Busca endereço completo pelo CEP via ViaCEP.
91
- */
92
- interface ViaCEPResponse {
93
- cep: string;
94
- logradouro: string;
95
- bairro: string;
96
- localidade: string;
97
- uf: string;
98
- erro?: boolean;
99
- }
100
-
101
- export async function fetchAddressByCEP(cep: string): Promise<{
102
- cep: string;
103
- logradouro: string;
104
- bairro: string;
105
- cidade: string;
106
- estado: string;
107
- } | null> {
108
- const digits = cep.replace(/\D/g, "");
109
- if (!isValidCEP(digits)) return null;
110
-
111
- const res = await fetch(`https://viacep.com.br/ws/${digits}/json/`);
112
- const data = (await res.json()) as ViaCEPResponse;
113
-
114
- if (data.erro) return null;
115
-
116
- return {
117
- cep: data.cep,
118
- logradouro: data.logradouro,
119
- bairro: data.bairro,
120
- cidade: data.localidade,
121
- estado: data.uf,
122
- };
123
- }
124
-
125
- // ─── TELEFONE ─────────────────────────────────────────────────────────────────
126
-
127
- /**
128
- * Aplica máscara de telefone de acordo com o país.
129
- * @param phone - Telefone somente com dígitos
130
- * @param countryCode - Código do país (ex: "BR", "US", "PT")
131
- */
132
- export function maskPhone(phone: string, countryCode: string = "BR"): string {
133
- const digits = phone.replace(/\D/g, "");
134
- const country = countries.find((c) => c.code === countryCode.toUpperCase());
135
- const format = country?.format ?? "(##) #####-####";
136
-
137
- let i = 0;
138
- return format.replace(/#/g, () => digits[i++] ?? "");
139
- }
140
-
141
- /**
142
- * Remove a máscara de um telefone, retornando só os dígitos.
143
- */
144
- export function unmaskPhone(phone: string): string {
145
- return phone.replace(/\D/g, "");
146
- }
147
-
148
- /**
149
- * Valida se é um telefone celular brasileiro (começa com 9 após o DDD).
150
- */
151
- export function isBrazilianMobile(phone: string): boolean {
152
- const digits = phone.replace(/\D/g, "");
153
- return /^(\d{2})9\d{8}$/.test(digits);
154
- }
155
-
156
- /**
157
- * Retorna a lista de países disponíveis para seleção de telefone.
158
- */
159
- export { countries };
160
- export type { Country } from "./countries";
161
-
162
- // ─── MOEDA ────────────────────────────────────────────────────────────────────
163
-
164
- /**
165
- * Formata um número como moeda.
166
- * @param value - Valor numérico
167
- * @param currency - Código da moeda (ex: "BRL", "EUR", "USD")
168
- * @param locale - Locale para formatação (ex: "pt-BR", "en-US")
169
- */
170
- export function formatCurrency(
171
- value: number,
172
- currency: string = "BRL",
173
- locale: string = "pt-BR"
174
- ): string {
175
- return new Intl.NumberFormat(locale, {
176
- style: "currency",
177
- currency,
178
- }).format(value);
179
- }
180
-
181
- /**
182
- * Converte um valor entre moedas usando taxa de câmbio em tempo real (AwesomeAPI).
183
- * @param amount - Valor a converter
184
- * @param from - Moeda de origem (ex: "BRL", "USD")
185
- * @param to - Moeda de destino (ex: "EUR", "USD")
186
- */
187
-
188
- interface AwesomeAPIResponse {
189
- [key: string]: {
190
- bid: string;
191
- ask: string;
192
- high: string;
193
- low: string;
194
- };
195
- }
196
-
197
- export async function convertCurrency(
198
- amount: number,
199
- from: string,
200
- to: string
201
- ): Promise<{
202
- from: string;
203
- to: string;
204
- amount: number;
205
- converted: number;
206
- rate: number;
207
- }> {
208
- const pair = `${from.toUpperCase()}-${to.toUpperCase()}`;
209
- const res = await fetch(`https://economia.awesomeapi.com.br/last/${pair}`);
210
- const data = (await res.json()) as AwesomeAPIResponse;
211
-
212
- const key = `${from.toUpperCase()}${to.toUpperCase()}`;
213
- const rate = parseFloat(data[key].bid);
214
- const converted = parseFloat((amount * rate).toFixed(2));
215
-
216
- return { from, to, amount, converted, rate };
217
- }
218
-
219
- // ─── DATA ─────────────────────────────────────────────────────────────────────
220
-
221
- /**
222
- * Formata uma data para o padrão brasileiro (dd/mm/yyyy).
223
- */
224
- export function formatDateBR(date: Date | string): string {
225
- const d = new Date(date);
226
- return d.toLocaleDateString("pt-BR");
227
- }
228
-
229
- /**
230
- * Converte data no formato BR (dd/mm/yyyy) para ISO (yyyy-mm-dd).
231
- */
232
- export function brDateToISO(date: string): string {
233
- const [day, month, year] = date.split("/");
234
- return `${year}-${month}-${day}`;
235
- }
236
-
237
- /**
238
- * Valida se uma string é uma data válida.
239
- */
240
- export function isValidDate(date: string): boolean {
241
- const d = new Date(date);
242
- return !isNaN(d.getTime());
243
- }
244
-
245
- // ─── NÚMERO ───────────────────────────────────────────────────────────────────
246
-
247
- /**
248
- * Formata um número com separadores de milhar e decimais no padrão BR.
249
- * @param value - Valor numérico
250
- * @param decimals - Casas decimais (padrão: 2)
251
- */
252
- export function formatNumber(value: number, decimals: number = 2): string {
253
- return new Intl.NumberFormat("pt-BR", {
254
- minimumFractionDigits: decimals,
255
- maximumFractionDigits: decimals,
256
- }).format(value);
257
- }
package/tsconfig.json DELETED
@@ -1,18 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "commonjs",
5
- "lib": ["ES2020", "DOM", "DOM.Iterable"],
6
- "jsx": "react-jsx",
7
- "declaration": true,
8
- "declarationMap": true,
9
- "sourceMap": true,
10
- "strict": true,
11
- "esModuleInterop": true,
12
- "skipLibCheck": true,
13
- "outDir": "./dist",
14
- "rootDir": "./src"
15
- },
16
- "include": ["src"],
17
- "exclude": ["node_modules", "dist"]
18
- }