@trindtech/utils 1.2.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/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/mailer/index.d.ts +21 -0
- package/dist/mailer/index.d.ts.map +1 -0
- package/dist/mailer/index.js +57 -0
- package/dist/mailer/index.js.map +1 -0
- package/dist/mailer/templates.d.ts +3 -0
- package/dist/mailer/templates.d.ts.map +1 -0
- package/dist/mailer/templates.js +49 -0
- package/dist/mailer/templates.js.map +1 -0
- package/dist/s3/index.d.ts +40 -0
- package/dist/s3/index.d.ts.map +1 -0
- package/dist/s3/index.js +174 -0
- package/dist/s3/index.js.map +1 -0
- package/dist/validators/countries.d.ts +9 -0
- package/dist/validators/countries.d.ts.map +1 -0
- package/dist/validators/countries.js +90 -0
- package/dist/validators/countries.js.map +1 -0
- package/dist/validators/index.d.ts +88 -0
- package/dist/validators/index.d.ts.map +1 -0
- package/dist/validators/index.js +196 -0
- package/dist/validators/index.js.map +1 -0
- package/package.json +23 -0
- package/src/index.ts +3 -0
- package/src/mailer/index.ts +87 -0
- package/src/mailer/templates.ts +48 -0
- package/src/s3/index.ts +241 -0
- package/src/validators/countries.ts +94 -0
- package/src/validators/index.ts +257 -0
- package/tsconfig.json +17 -0
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.countries = void 0;
|
|
4
|
+
exports.isValidCPF = isValidCPF;
|
|
5
|
+
exports.formatCPF = formatCPF;
|
|
6
|
+
exports.isValidCNPJ = isValidCNPJ;
|
|
7
|
+
exports.formatCNPJ = formatCNPJ;
|
|
8
|
+
exports.isValidRG = isValidRG;
|
|
9
|
+
exports.isValidCEP = isValidCEP;
|
|
10
|
+
exports.formatCEP = formatCEP;
|
|
11
|
+
exports.fetchAddressByCEP = fetchAddressByCEP;
|
|
12
|
+
exports.maskPhone = maskPhone;
|
|
13
|
+
exports.unmaskPhone = unmaskPhone;
|
|
14
|
+
exports.isBrazilianMobile = isBrazilianMobile;
|
|
15
|
+
exports.formatCurrency = formatCurrency;
|
|
16
|
+
exports.convertCurrency = convertCurrency;
|
|
17
|
+
exports.formatDateBR = formatDateBR;
|
|
18
|
+
exports.brDateToISO = brDateToISO;
|
|
19
|
+
exports.isValidDate = isValidDate;
|
|
20
|
+
exports.formatNumber = formatNumber;
|
|
21
|
+
const countries_1 = require("./countries");
|
|
22
|
+
Object.defineProperty(exports, "countries", { enumerable: true, get: function () { return countries_1.countries; } });
|
|
23
|
+
// ─── CPF ──────────────────────────────────────────────────────────────────────
|
|
24
|
+
/**
|
|
25
|
+
* Valida um CPF brasileiro (aceita com ou sem formatação).
|
|
26
|
+
*/
|
|
27
|
+
function isValidCPF(cpf) {
|
|
28
|
+
const digits = cpf.replace(/\D/g, "");
|
|
29
|
+
if (digits.length !== 11 || /^(\d)\1+$/.test(digits))
|
|
30
|
+
return false;
|
|
31
|
+
const calc = (mod) => {
|
|
32
|
+
let sum = 0;
|
|
33
|
+
for (let i = 0; i < mod - 1; i++)
|
|
34
|
+
sum += parseInt(digits[i]) * (mod - i);
|
|
35
|
+
const rest = (sum * 10) % 11;
|
|
36
|
+
return rest === 10 || rest === 11 ? 0 : rest;
|
|
37
|
+
};
|
|
38
|
+
return calc(10) === parseInt(digits[9]) && calc(11) === parseInt(digits[10]);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Formata um CPF para exibição (ex: "12345678909" → "123.456.789-09").
|
|
42
|
+
*/
|
|
43
|
+
function formatCPF(cpf) {
|
|
44
|
+
const d = cpf.replace(/\D/g, "");
|
|
45
|
+
return d.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4");
|
|
46
|
+
}
|
|
47
|
+
// ─── CNPJ ─────────────────────────────────────────────────────────────────────
|
|
48
|
+
/**
|
|
49
|
+
* Valida um CNPJ brasileiro (aceita com ou sem formatação).
|
|
50
|
+
*/
|
|
51
|
+
function isValidCNPJ(cnpj) {
|
|
52
|
+
const digits = cnpj.replace(/\D/g, "");
|
|
53
|
+
if (digits.length !== 14 || /^(\d)\1+$/.test(digits))
|
|
54
|
+
return false;
|
|
55
|
+
const calc = (size) => {
|
|
56
|
+
let sum = 0;
|
|
57
|
+
let pos = size - 7;
|
|
58
|
+
for (let i = size; i >= 1; i--) {
|
|
59
|
+
sum += parseInt(digits[size - i]) * pos--;
|
|
60
|
+
if (pos < 2)
|
|
61
|
+
pos = 9;
|
|
62
|
+
}
|
|
63
|
+
const rest = sum % 11;
|
|
64
|
+
return rest < 2 ? 0 : 11 - rest;
|
|
65
|
+
};
|
|
66
|
+
return calc(12) === parseInt(digits[12]) && calc(13) === parseInt(digits[13]);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Formata um CNPJ para exibição (ex: "11222333000181" → "11.222.333/0001-81").
|
|
70
|
+
*/
|
|
71
|
+
function formatCNPJ(cnpj) {
|
|
72
|
+
const d = cnpj.replace(/\D/g, "");
|
|
73
|
+
return d.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, "$1.$2.$3/$4-$5");
|
|
74
|
+
}
|
|
75
|
+
// ─── RG ───────────────────────────────────────────────────────────────────────
|
|
76
|
+
/**
|
|
77
|
+
* Valida um RG brasileiro (7 a 9 dígitos).
|
|
78
|
+
*/
|
|
79
|
+
function isValidRG(rg) {
|
|
80
|
+
const digits = rg.replace(/\D/g, "");
|
|
81
|
+
return digits.length >= 7 && digits.length <= 9;
|
|
82
|
+
}
|
|
83
|
+
// ─── CEP ──────────────────────────────────────────────────────────────────────
|
|
84
|
+
/**
|
|
85
|
+
* Valida um CEP brasileiro.
|
|
86
|
+
*/
|
|
87
|
+
function isValidCEP(cep) {
|
|
88
|
+
const digits = cep.replace(/\D/g, "");
|
|
89
|
+
return /^\d{8}$/.test(digits);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Formata um CEP para exibição (ex: "01310100" → "01310-100").
|
|
93
|
+
*/
|
|
94
|
+
function formatCEP(cep) {
|
|
95
|
+
const d = cep.replace(/\D/g, "");
|
|
96
|
+
return d.replace(/(\d{5})(\d{3})/, "$1-$2");
|
|
97
|
+
}
|
|
98
|
+
async function fetchAddressByCEP(cep) {
|
|
99
|
+
const digits = cep.replace(/\D/g, "");
|
|
100
|
+
if (!isValidCEP(digits))
|
|
101
|
+
return null;
|
|
102
|
+
const res = await fetch(`https://viacep.com.br/ws/${digits}/json/`);
|
|
103
|
+
const data = (await res.json());
|
|
104
|
+
if (data.erro)
|
|
105
|
+
return null;
|
|
106
|
+
return {
|
|
107
|
+
cep: data.cep,
|
|
108
|
+
logradouro: data.logradouro,
|
|
109
|
+
bairro: data.bairro,
|
|
110
|
+
cidade: data.localidade,
|
|
111
|
+
estado: data.uf,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
// ─── TELEFONE ─────────────────────────────────────────────────────────────────
|
|
115
|
+
/**
|
|
116
|
+
* Aplica máscara de telefone de acordo com o país.
|
|
117
|
+
* @param phone - Telefone somente com dígitos
|
|
118
|
+
* @param countryCode - Código do país (ex: "BR", "US", "PT")
|
|
119
|
+
*/
|
|
120
|
+
function maskPhone(phone, countryCode = "BR") {
|
|
121
|
+
const digits = phone.replace(/\D/g, "");
|
|
122
|
+
const country = countries_1.countries.find((c) => c.code === countryCode.toUpperCase());
|
|
123
|
+
const format = country?.format ?? "(##) #####-####";
|
|
124
|
+
let i = 0;
|
|
125
|
+
return format.replace(/#/g, () => digits[i++] ?? "");
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Remove a máscara de um telefone, retornando só os dígitos.
|
|
129
|
+
*/
|
|
130
|
+
function unmaskPhone(phone) {
|
|
131
|
+
return phone.replace(/\D/g, "");
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Valida se é um telefone celular brasileiro (começa com 9 após o DDD).
|
|
135
|
+
*/
|
|
136
|
+
function isBrazilianMobile(phone) {
|
|
137
|
+
const digits = phone.replace(/\D/g, "");
|
|
138
|
+
return /^(\d{2})9\d{8}$/.test(digits);
|
|
139
|
+
}
|
|
140
|
+
// ─── MOEDA ────────────────────────────────────────────────────────────────────
|
|
141
|
+
/**
|
|
142
|
+
* Formata um número como moeda.
|
|
143
|
+
* @param value - Valor numérico
|
|
144
|
+
* @param currency - Código da moeda (ex: "BRL", "EUR", "USD")
|
|
145
|
+
* @param locale - Locale para formatação (ex: "pt-BR", "en-US")
|
|
146
|
+
*/
|
|
147
|
+
function formatCurrency(value, currency = "BRL", locale = "pt-BR") {
|
|
148
|
+
return new Intl.NumberFormat(locale, {
|
|
149
|
+
style: "currency",
|
|
150
|
+
currency,
|
|
151
|
+
}).format(value);
|
|
152
|
+
}
|
|
153
|
+
async function convertCurrency(amount, from, to) {
|
|
154
|
+
const pair = `${from.toUpperCase()}-${to.toUpperCase()}`;
|
|
155
|
+
const res = await fetch(`https://economia.awesomeapi.com.br/last/${pair}`);
|
|
156
|
+
const data = (await res.json());
|
|
157
|
+
const key = `${from.toUpperCase()}${to.toUpperCase()}`;
|
|
158
|
+
const rate = parseFloat(data[key].bid);
|
|
159
|
+
const converted = parseFloat((amount * rate).toFixed(2));
|
|
160
|
+
return { from, to, amount, converted, rate };
|
|
161
|
+
}
|
|
162
|
+
// ─── DATA ─────────────────────────────────────────────────────────────────────
|
|
163
|
+
/**
|
|
164
|
+
* Formata uma data para o padrão brasileiro (dd/mm/yyyy).
|
|
165
|
+
*/
|
|
166
|
+
function formatDateBR(date) {
|
|
167
|
+
const d = new Date(date);
|
|
168
|
+
return d.toLocaleDateString("pt-BR");
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Converte data no formato BR (dd/mm/yyyy) para ISO (yyyy-mm-dd).
|
|
172
|
+
*/
|
|
173
|
+
function brDateToISO(date) {
|
|
174
|
+
const [day, month, year] = date.split("/");
|
|
175
|
+
return `${year}-${month}-${day}`;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Valida se uma string é uma data válida.
|
|
179
|
+
*/
|
|
180
|
+
function isValidDate(date) {
|
|
181
|
+
const d = new Date(date);
|
|
182
|
+
return !isNaN(d.getTime());
|
|
183
|
+
}
|
|
184
|
+
// ─── NÚMERO ───────────────────────────────────────────────────────────────────
|
|
185
|
+
/**
|
|
186
|
+
* Formata um número com separadores de milhar e decimais no padrão BR.
|
|
187
|
+
* @param value - Valor numérico
|
|
188
|
+
* @param decimals - Casas decimais (padrão: 2)
|
|
189
|
+
*/
|
|
190
|
+
function formatNumber(value, decimals = 2) {
|
|
191
|
+
return new Intl.NumberFormat("pt-BR", {
|
|
192
|
+
minimumFractionDigits: decimals,
|
|
193
|
+
maximumFractionDigits: decimals,
|
|
194
|
+
}).format(value);
|
|
195
|
+
}
|
|
196
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/validators/index.ts"],"names":[],"mappings":";;;AAOA,gCAYC;AAKD,8BAGC;AAOD,kCAgBC;AAKD,gCAGC;AAOD,8BAGC;AAOD,gCAGC;AAKD,8BAGC;AAcD,8CAsBC;AASD,8BAOC;AAKD,kCAEC;AAKD,8CAGC;AAgBD,wCASC;AAkBD,0CAoBC;AAOD,oCAGC;AAKD,kCAGC;AAKD,kCAGC;AASD,oCAKC;AAhQD,2CAAwC;AA8J/B,0FA9JA,qBAAS,OA8JA;AA5JlB,iFAAiF;AAEjF;;GAEG;AACH,SAAgB,UAAU,CAAC,GAAW;IACpC,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACtC,IAAI,MAAM,CAAC,MAAM,KAAK,EAAE,IAAI,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC;QAAE,OAAO,KAAK,CAAC;IAEnE,MAAM,IAA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CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAEzD,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAC/C,CAAC;AAED,iFAAiF;AAEjF;;GAEG;AACH,SAAgB,YAAY,CAAC,IAAmB;IAC9C,MAAM,CAAC,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;IACzB,OAAO,CAAC,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC;AACvC,CAAC;AAED;;GAEG;AACH,SAAgB,WAAW,CAAC,IAAY;IACtC,MAAM,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC3C,OAAO,GAAG,IAAI,IAAI,KAAK,IAAI,GAAG,EAAE,CAAC;AACnC,CAAC;AAED;;GAEG;AACH,SAAgB,WAAW,CAAC,IAAY;IACtC,MAAM,CAAC,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;IACzB,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;AAC7B,CAAC;AAED,iFAAiF;AAEjF;;;;GAIG;AACH,SAAgB,YAAY,CAAC,KAAa,EAAE,WAAmB,CAAC;IAC9D,OAAO,IAAI,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE;QACpC,qBAAqB,EAAE,QAAQ;QAC/B,qBAAqB,EAAE,QAAQ;KAChC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACnB,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@trindtech/utils",
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"main": "./dist/index.js",
|
|
5
|
+
"types": "./dist/index.d.ts",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"registry": "https://registry.npmjs.org",
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "tsc",
|
|
12
|
+
"dev": "tsc --watch"
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@aws-sdk/client-s3": "^3.1003.0",
|
|
16
|
+
"@aws-sdk/client-ses": "^3.1002.0",
|
|
17
|
+
"@aws-sdk/s3-request-presigner": "^3.1003.0"
|
|
18
|
+
},
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"@types/node": "^25.3.3",
|
|
21
|
+
"typescript": "^5.9.3"
|
|
22
|
+
}
|
|
23
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { SESClient, SendEmailCommand } from "@aws-sdk/client-ses";
|
|
2
|
+
import { verificationTemplate, resetPasswordTemplate } from "./templates";
|
|
3
|
+
|
|
4
|
+
export interface MailerCredentials {
|
|
5
|
+
accessKeyId: string;
|
|
6
|
+
secretAccessKey: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface MailerConfig {
|
|
10
|
+
region: string;
|
|
11
|
+
from: string;
|
|
12
|
+
appName: string;
|
|
13
|
+
credentials: MailerCredentials;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface SendOptions {
|
|
17
|
+
to: string;
|
|
18
|
+
subject: string;
|
|
19
|
+
html: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createMailer(config: MailerConfig) {
|
|
23
|
+
const client = new SESClient({
|
|
24
|
+
region: config.region,
|
|
25
|
+
credentials: {
|
|
26
|
+
accessKeyId: config.credentials.accessKeyId,
|
|
27
|
+
secretAccessKey: config.credentials.secretAccessKey,
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
async function send({ to, subject, html }: SendOptions): Promise<void> {
|
|
32
|
+
const command = new SendEmailCommand({
|
|
33
|
+
Source: config.from,
|
|
34
|
+
Destination: {
|
|
35
|
+
ToAddresses: [to],
|
|
36
|
+
},
|
|
37
|
+
Message: {
|
|
38
|
+
Subject: {
|
|
39
|
+
Data: subject,
|
|
40
|
+
Charset: "UTF-8",
|
|
41
|
+
},
|
|
42
|
+
Body: {
|
|
43
|
+
Html: {
|
|
44
|
+
Data: html,
|
|
45
|
+
Charset: "UTF-8",
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
await client.send(command);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function sendVerificationEmail(
|
|
55
|
+
to: string,
|
|
56
|
+
code: string,
|
|
57
|
+
customTemplate?: (code: string, appName: string) => string
|
|
58
|
+
): Promise<void> {
|
|
59
|
+
const html = customTemplate
|
|
60
|
+
? customTemplate(code, config.appName)
|
|
61
|
+
: verificationTemplate(code, config.appName);
|
|
62
|
+
|
|
63
|
+
await send({
|
|
64
|
+
to,
|
|
65
|
+
subject: `Seu código de verificação — ${config.appName}`,
|
|
66
|
+
html,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function sendResetPasswordEmail(
|
|
71
|
+
to: string,
|
|
72
|
+
resetUrl: string,
|
|
73
|
+
customTemplate?: (resetUrl: string, appName: string) => string
|
|
74
|
+
): Promise<void> {
|
|
75
|
+
const html = customTemplate
|
|
76
|
+
? customTemplate(resetUrl, config.appName)
|
|
77
|
+
: resetPasswordTemplate(resetUrl, config.appName);
|
|
78
|
+
|
|
79
|
+
await send({
|
|
80
|
+
to,
|
|
81
|
+
subject: `Redefinição de senha — ${config.appName}`,
|
|
82
|
+
html,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return { send, sendVerificationEmail, sendResetPasswordEmail };
|
|
87
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export function verificationTemplate(code: string, appName: string): string {
|
|
2
|
+
return `
|
|
3
|
+
<div style="font-family: sans-serif; max-width: 480px; margin: 0 auto;">
|
|
4
|
+
<h2>Verifique seu e-mail — ${appName}</h2>
|
|
5
|
+
<p>Use o código abaixo para confirmar seu cadastro:</p>
|
|
6
|
+
<div style="
|
|
7
|
+
font-size: 32px;
|
|
8
|
+
font-weight: bold;
|
|
9
|
+
letter-spacing: 8px;
|
|
10
|
+
padding: 16px;
|
|
11
|
+
background: #f4f4f4;
|
|
12
|
+
border-radius: 8px;
|
|
13
|
+
text-align: center;
|
|
14
|
+
">
|
|
15
|
+
${code}
|
|
16
|
+
</div>
|
|
17
|
+
<p style="color: #666; font-size: 13px; margin-top: 16px;">
|
|
18
|
+
Este código expira em 60 minutos. Não compartilhe com ninguém.
|
|
19
|
+
</p>
|
|
20
|
+
</div>
|
|
21
|
+
`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function resetPasswordTemplate(
|
|
25
|
+
resetUrl: string,
|
|
26
|
+
appName: string
|
|
27
|
+
): string {
|
|
28
|
+
return `
|
|
29
|
+
<div style="font-family: sans-serif; max-width: 480px; margin: 0 auto;">
|
|
30
|
+
<h2>Redefinição de senha — ${appName}</h2>
|
|
31
|
+
<p>Clique no botão abaixo para redefinir sua senha:</p>
|
|
32
|
+
<a href="${resetUrl}" style="
|
|
33
|
+
display: inline-block;
|
|
34
|
+
padding: 12px 24px;
|
|
35
|
+
background: #000;
|
|
36
|
+
color: #fff;
|
|
37
|
+
text-decoration: none;
|
|
38
|
+
border-radius: 6px;
|
|
39
|
+
margin: 16px 0;
|
|
40
|
+
">
|
|
41
|
+
Redefinir senha
|
|
42
|
+
</a>
|
|
43
|
+
<p style="color: #666; font-size: 13px;">
|
|
44
|
+
Este link expira em 1 hora. Se você não solicitou isso, ignore este e-mail.
|
|
45
|
+
</p>
|
|
46
|
+
</div>
|
|
47
|
+
`;
|
|
48
|
+
}
|
package/src/s3/index.ts
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
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
|
+
}
|