@trindtech/utils 1.3.0 → 1.5.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.
package/src/s3/index.ts DELETED
@@ -1,241 +0,0 @@
1
- import {
2
- S3Client,
3
- DeleteObjectCommand,
4
- HeadObjectCommand,
5
- } from "@aws-sdk/client-s3";
6
- import { PutObjectCommand, GetObjectCommand } from "@aws-sdk/client-s3";
7
- import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
8
-
9
- // ─── Tipos ────────────────────────────────────────────────────────────────────
10
-
11
- export interface S3Config {
12
- bucket: string;
13
- region: string;
14
- credentials: {
15
- accessKeyId: string;
16
- secretAccessKey: string;
17
- };
18
- }
19
-
20
- export interface PresignedUploadOptions {
21
- key: string;
22
- contentType: string;
23
- maxSizeBytes?: number;
24
- expiresIn?: number;
25
- }
26
-
27
- export interface PresignedReadOptions {
28
- key: string;
29
- expiresIn?: number;
30
- }
31
-
32
- const ALLOWED_IMAGE_TYPES = [
33
- "image/jpeg",
34
- "image/png",
35
- "image/webp",
36
- "image/gif",
37
- ];
38
- const ALLOWED_DOCUMENT_TYPES = ["application/pdf"];
39
- const ALLOWED_VIDEO_TYPES = ["video/mp4", "video/webm", "video/quicktime"];
40
-
41
- export const ALLOWED_CONTENT_TYPES = [
42
- ...ALLOWED_IMAGE_TYPES,
43
- ...ALLOWED_DOCUMENT_TYPES,
44
- ...ALLOWED_VIDEO_TYPES,
45
- ];
46
-
47
- const DEFAULT_MAX_SIZES: Record<string, number> = {
48
- "image/jpeg": 10 * 1024 * 1024, // 10MB
49
- "image/png": 10 * 1024 * 1024, // 10MB
50
- "image/webp": 10 * 1024 * 1024, // 10MB
51
- "image/gif": 10 * 1024 * 1024, // 10MB
52
- "application/pdf": 50 * 1024 * 1024, // 50MB
53
- "video/mp4": 500 * 1024 * 1024, // 500MB
54
- "video/webm": 500 * 1024 * 1024, // 500MB
55
- "video/quicktime": 500 * 1024 * 1024, // 500MB
56
- };
57
-
58
- // ─── Client ───────────────────────────────────────────────────────────────────
59
-
60
- /**
61
- * Cria e retorna um cliente S3 configurado.
62
- * O bucket deve ser privado — todos os acessos são feitos via presigned URLs.
63
- */
64
- export function createS3Client(config: S3Config) {
65
- const client = new S3Client({
66
- region: config.region,
67
- credentials: {
68
- accessKeyId: config.credentials.accessKeyId,
69
- secretAccessKey: config.credentials.secretAccessKey,
70
- },
71
- });
72
-
73
- // ─── Validação ──────────────────────────────────────────────────────────────
74
-
75
- function validateContentType(contentType: string): void {
76
- if (!ALLOWED_CONTENT_TYPES.includes(contentType)) {
77
- throw new Error(
78
- `Tipo de arquivo não permitido: ${contentType}. ` +
79
- `Permitidos: ${ALLOWED_CONTENT_TYPES.join(", ")}`
80
- );
81
- }
82
- }
83
-
84
- function validateKey(key: string): void {
85
- // Previne path traversal
86
- if (key.includes("..") || key.startsWith("/")) {
87
- throw new Error("Chave de arquivo inválida.");
88
- }
89
- }
90
-
91
- // ─── Presigned Upload URL ───────────────────────────────────────────────────
92
-
93
- /**
94
- * Gera uma URL pré-assinada para upload direto no S3 (PUT).
95
- * A URL expira em 15 minutos por padrão.
96
- *
97
- * @param options.key - Caminho do arquivo no bucket (ex: "avatars/user-123.jpg")
98
- * @param options.contentType - MIME type do arquivo (ex: "image/jpeg")
99
- * @param options.maxSizeBytes - Tamanho máximo em bytes (usa padrão por tipo se omitido)
100
- * @param options.expiresIn - Tempo de expiração em segundos (padrão: 900 = 15min)
101
- *
102
- * @example
103
- * const { url, key } = await s3.getPresignedUploadUrl({
104
- * key: 'avatars/user-123.jpg',
105
- * contentType: 'image/jpeg',
106
- * })
107
- * // Frontend faz PUT para url com o arquivo no body
108
- */
109
- async function getPresignedUploadUrl(
110
- options: PresignedUploadOptions
111
- ): Promise<{
112
- url: string;
113
- key: string;
114
- expiresIn: number;
115
- }> {
116
- const { key, contentType, expiresIn = 900 } = options;
117
-
118
- validateKey(key);
119
- validateContentType(contentType);
120
-
121
- const maxSize = options.maxSizeBytes ?? DEFAULT_MAX_SIZES[contentType];
122
-
123
- const command = new PutObjectCommand({
124
- Bucket: config.bucket,
125
- Key: key,
126
- ContentType: contentType,
127
- ContentLengthRange: maxSize ? [1, maxSize] : undefined,
128
- } as ConstructorParameters<typeof PutObjectCommand>[0]);
129
-
130
- const url = await getSignedUrl(client, command, { expiresIn });
131
-
132
- return { url, key, expiresIn };
133
- }
134
-
135
- // ─── Presigned Read URL ─────────────────────────────────────────────────────
136
-
137
- /**
138
- * Gera uma URL pré-assinada para leitura de arquivo privado (GET).
139
- * A URL expira em 1 hora por padrão.
140
- *
141
- * @param options.key - Caminho do arquivo no bucket
142
- * @param options.expiresIn - Tempo de expiração em segundos (padrão: 3600 = 1h)
143
- *
144
- * @example
145
- * const { url } = await s3.getPresignedReadUrl({ key: 'avatars/user-123.jpg' })
146
- */
147
- async function getPresignedReadUrl(options: PresignedReadOptions): Promise<{
148
- url: string;
149
- key: string;
150
- expiresIn: number;
151
- }> {
152
- const { key, expiresIn = 3600 } = options;
153
-
154
- validateKey(key);
155
-
156
- const command = new GetObjectCommand({
157
- Bucket: config.bucket,
158
- Key: key,
159
- });
160
-
161
- const url = await getSignedUrl(client, command, { expiresIn });
162
-
163
- return { url, key, expiresIn };
164
- }
165
-
166
- // ─── Delete ─────────────────────────────────────────────────────────────────
167
-
168
- /**
169
- * Remove um arquivo do bucket.
170
- *
171
- * @param key - Caminho do arquivo no bucket
172
- *
173
- * @example
174
- * await s3.remove('avatars/user-123.jpg')
175
- */
176
- async function remove(key: string): Promise<void> {
177
- validateKey(key);
178
-
179
- await client.send(
180
- new DeleteObjectCommand({
181
- Bucket: config.bucket,
182
- Key: key,
183
- })
184
- );
185
- }
186
-
187
- // ─── Exists ─────────────────────────────────────────────────────────────────
188
-
189
- /**
190
- * Verifica se um arquivo existe no bucket.
191
- *
192
- * @param key - Caminho do arquivo no bucket
193
- *
194
- * @example
195
- * const exists = await s3.exists('avatars/user-123.jpg')
196
- */
197
- async function exists(key: string): Promise<boolean> {
198
- validateKey(key);
199
-
200
- try {
201
- await client.send(
202
- new HeadObjectCommand({
203
- Bucket: config.bucket,
204
- Key: key,
205
- })
206
- );
207
- return true;
208
- } catch {
209
- return false;
210
- }
211
- }
212
-
213
- // ─── Generate Key ───────────────────────────────────────────────────────────
214
-
215
- /**
216
- * Gera uma chave única para o arquivo no bucket.
217
- * Formato: {folder}/{uuid}-{timestamp}.{ext}
218
- *
219
- * @param folder - Pasta no bucket (ex: "avatars", "documentos")
220
- * @param filename - Nome original do arquivo (ex: "foto.jpg")
221
- *
222
- * @example
223
- * const key = s3.generateKey('avatars', 'foto.jpg')
224
- * // "avatars/a1b2c3d4-1234567890.jpg"
225
- */
226
- function generateKey(folder: string, filename: string): string {
227
- const ext = filename.split(".").pop()?.toLowerCase() ?? "bin";
228
- const uuid = crypto.randomUUID();
229
- const timestamp = Date.now();
230
- return `${folder}/${uuid}-${timestamp}.${ext}`;
231
- }
232
-
233
- return {
234
- getPresignedUploadUrl,
235
- getPresignedReadUrl,
236
- remove,
237
- exists,
238
- generateKey,
239
- ALLOWED_CONTENT_TYPES,
240
- };
241
- }
@@ -1,94 +0,0 @@
1
- export interface Country {
2
- name: string;
3
- code: string;
4
- dialCode: string;
5
- flag: string;
6
- format: string;
7
- }
8
-
9
- export const countries: Country[] = [
10
- {
11
- name: "Brasil",
12
- code: "BR",
13
- dialCode: "+55",
14
- flag: "🇧🇷",
15
- format: "(##) #####-####",
16
- },
17
- {
18
- name: "Portugal",
19
- code: "PT",
20
- dialCode: "+351",
21
- flag: "🇵🇹",
22
- format: "### ### ###",
23
- },
24
- {
25
- name: "Estados Unidos",
26
- code: "US",
27
- dialCode: "+1",
28
- flag: "🇺🇸",
29
- format: "(###) ###-####",
30
- },
31
- {
32
- name: "Espanha",
33
- code: "ES",
34
- dialCode: "+34",
35
- flag: "🇪🇸",
36
- format: "### ### ###",
37
- },
38
- {
39
- name: "Reino Unido",
40
- code: "GB",
41
- dialCode: "+44",
42
- flag: "🇬🇧",
43
- format: "#### ######",
44
- },
45
- {
46
- name: "Alemanha",
47
- code: "DE",
48
- dialCode: "+49",
49
- flag: "🇩🇪",
50
- format: "### #######",
51
- },
52
- {
53
- name: "França",
54
- code: "FR",
55
- dialCode: "+33",
56
- flag: "🇫🇷",
57
- format: "# ## ## ## ##",
58
- },
59
- {
60
- name: "Itália",
61
- code: "IT",
62
- dialCode: "+39",
63
- flag: "🇮🇹",
64
- format: "### #######",
65
- },
66
- {
67
- name: "Argentina",
68
- code: "AR",
69
- dialCode: "+54",
70
- flag: "🇦🇷",
71
- format: "(###) ###-####",
72
- },
73
- {
74
- name: "México",
75
- code: "MX",
76
- dialCode: "+52",
77
- flag: "🇲🇽",
78
- format: "(###) ###-####",
79
- },
80
- {
81
- name: "Chile",
82
- code: "CL",
83
- dialCode: "+56",
84
- flag: "🇨🇱",
85
- format: "# #### ####",
86
- },
87
- {
88
- name: "Colômbia",
89
- code: "CO",
90
- dialCode: "+57",
91
- flag: "🇨🇴",
92
- format: "### #######",
93
- },
94
- ];
@@ -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
- }