@pairus/product-data 1.0.0 → 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/README.md +325 -94
- package/dist/index.d.mts +354 -2
- package/dist/index.d.ts +354 -2
- package/dist/index.js +247 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +243 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -34,11 +34,15 @@ __export(index_exports, {
|
|
|
34
34
|
DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
|
|
35
35
|
DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES,
|
|
36
36
|
DEFAULT_TIMEOUT_MS: () => DEFAULT_TIMEOUT_MS,
|
|
37
|
+
EmissaoResource: () => EmissaoResource,
|
|
38
|
+
FiscalResource: () => FiscalResource,
|
|
37
39
|
InvalidSignatureError: () => InvalidSignatureError,
|
|
40
|
+
NFSeResource: () => NFSeResource,
|
|
38
41
|
NetworkError: () => NetworkError,
|
|
39
42
|
PairusAPIError: () => PairusAPIError,
|
|
40
43
|
PairusError: () => PairusError,
|
|
41
44
|
PairusProductData: () => PairusProductData,
|
|
45
|
+
ProductsResource: () => ProductsResource,
|
|
42
46
|
RateLimitError: () => RateLimitError,
|
|
43
47
|
Webhooks: () => Webhooks
|
|
44
48
|
});
|
|
@@ -120,10 +124,11 @@ var BaseResource = class {
|
|
|
120
124
|
const reqHeaders = {
|
|
121
125
|
"Accept": "application/json",
|
|
122
126
|
"X-API-Key": this.apiKey,
|
|
123
|
-
"User-Agent": "Pairus-NodeJS-SDK/1.
|
|
127
|
+
"User-Agent": "Pairus-NodeJS-SDK/1.2.0",
|
|
124
128
|
...options.headers || {}
|
|
125
129
|
};
|
|
126
|
-
|
|
130
|
+
const isFormData = typeof FormData !== "undefined" && options.body instanceof FormData;
|
|
131
|
+
if (options.body && !isFormData && !reqHeaders["Content-Type"]) {
|
|
127
132
|
reqHeaders["Content-Type"] = "application/json";
|
|
128
133
|
}
|
|
129
134
|
let lastError = null;
|
|
@@ -131,14 +136,15 @@ var BaseResource = class {
|
|
|
131
136
|
try {
|
|
132
137
|
const controller = new AbortController();
|
|
133
138
|
const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
139
|
+
const bodyData = isFormData ? options.body : options.body ? JSON.stringify(options.body) : void 0;
|
|
134
140
|
const response = await fetch(url, {
|
|
135
141
|
method: options.method,
|
|
136
142
|
headers: reqHeaders,
|
|
137
|
-
body:
|
|
143
|
+
body: bodyData,
|
|
138
144
|
signal: controller.signal
|
|
139
145
|
});
|
|
140
146
|
clearTimeout(timeoutId);
|
|
141
|
-
if (response.ok) {
|
|
147
|
+
if (response.ok || response.status >= 200 && response.status < 300) {
|
|
142
148
|
return await response.json();
|
|
143
149
|
}
|
|
144
150
|
let errData = {};
|
|
@@ -181,6 +187,86 @@ var BaseResource = class {
|
|
|
181
187
|
}
|
|
182
188
|
};
|
|
183
189
|
|
|
190
|
+
// src/resources/emissao.ts
|
|
191
|
+
var EmissaoResource = class extends BaseResource {
|
|
192
|
+
/**
|
|
193
|
+
* Emite uma Nota Fiscal Eletrônica (NF-e Modelo 55) perante a SEFAZ.
|
|
194
|
+
*/
|
|
195
|
+
async emitirNFe(payload) {
|
|
196
|
+
return this.request({
|
|
197
|
+
method: "POST",
|
|
198
|
+
path: "/v1/nfe/emitir",
|
|
199
|
+
body: payload
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Emite uma Nota Fiscal de Consumidor Eletrônica (NFC-e Modelo 65) perante a SEFAZ.
|
|
204
|
+
*/
|
|
205
|
+
async emitirNFCe(payload) {
|
|
206
|
+
return this.request({
|
|
207
|
+
method: "POST",
|
|
208
|
+
path: "/v1/nfce/emitir",
|
|
209
|
+
body: payload
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Simula uma emissão fiscal sem transmitir à SEFAZ (custo ZERO de créditos).
|
|
214
|
+
*/
|
|
215
|
+
async simular(payload) {
|
|
216
|
+
return this.request({
|
|
217
|
+
method: "POST",
|
|
218
|
+
path: "/v1/nfe/simular",
|
|
219
|
+
body: payload
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Homologa o cancelamento oficial de uma NF-e ou NFC-e perante a SEFAZ.
|
|
224
|
+
*/
|
|
225
|
+
async cancelar(params) {
|
|
226
|
+
return this.request({
|
|
227
|
+
method: "POST",
|
|
228
|
+
path: "/v1/nfe/cancelar",
|
|
229
|
+
body: {
|
|
230
|
+
chave_acesso: params.chave_acesso,
|
|
231
|
+
justificativa: params.justificativa,
|
|
232
|
+
protocolo_autorizacao: params.protocolo_autorizacao
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Emite uma Carta de Correção Eletrônica (CC-e) perante a SEFAZ.
|
|
238
|
+
*/
|
|
239
|
+
async cartaCorrecao(params) {
|
|
240
|
+
return this.request({
|
|
241
|
+
method: "POST",
|
|
242
|
+
path: "/v1/nfe/carta-correcao",
|
|
243
|
+
body: {
|
|
244
|
+
chave_acesso: params.chave_acesso,
|
|
245
|
+
correcao: params.correcao,
|
|
246
|
+
sequencia_evento: params.sequencia_evento ?? 1
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Inutiliza uma faixa de numeração quebrada na SEFAZ (Ajuste SINIEF 07/05).
|
|
252
|
+
*/
|
|
253
|
+
async inutilizar(params) {
|
|
254
|
+
return this.request({
|
|
255
|
+
method: "POST",
|
|
256
|
+
path: "/v1/nfe/inutilizar",
|
|
257
|
+
body: {
|
|
258
|
+
cnpj_emitente: params.cnpj_emitente,
|
|
259
|
+
serie: params.serie,
|
|
260
|
+
numero_inicial: params.numero_inicial,
|
|
261
|
+
numero_final: params.numero_final,
|
|
262
|
+
justificativa: params.justificativa,
|
|
263
|
+
ano: params.ano,
|
|
264
|
+
modelo: params.modelo ?? 55
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
|
|
184
270
|
// src/resources/fiscal.ts
|
|
185
271
|
var FiscalResource = class extends BaseResource {
|
|
186
272
|
/**
|
|
@@ -205,19 +291,72 @@ var FiscalResource = class extends BaseResource {
|
|
|
205
291
|
body: payload
|
|
206
292
|
});
|
|
207
293
|
}
|
|
294
|
+
/**
|
|
295
|
+
* Audita e higieniza uma lista de produtos em lote perante as tabelas fiscais vigentes.
|
|
296
|
+
*/
|
|
297
|
+
async sanitize(itens) {
|
|
298
|
+
return this.request({
|
|
299
|
+
method: "POST",
|
|
300
|
+
path: "/v2/fiscal/sanitize",
|
|
301
|
+
body: { itens }
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
// src/resources/nfse.ts
|
|
307
|
+
var NFSeResource = class extends BaseResource {
|
|
308
|
+
/**
|
|
309
|
+
* Emite uma Nota Fiscal de Serviços Eletrônica (NFS-e) perante o SND ou prefeitura.
|
|
310
|
+
*/
|
|
311
|
+
async emitir(payload) {
|
|
312
|
+
return this.request({
|
|
313
|
+
method: "POST",
|
|
314
|
+
path: "/v1/nfse/emitir",
|
|
315
|
+
body: payload
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Simula o cálculo de NFS-e com retenções e apuração tributária (custo ZERO de créditos).
|
|
320
|
+
*/
|
|
321
|
+
async simular(payload) {
|
|
322
|
+
return this.request({
|
|
323
|
+
method: "POST",
|
|
324
|
+
path: "/v1/nfse/simular",
|
|
325
|
+
body: payload
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Homologa o cancelamento oficial de uma NFS-e perante o SND ou prefeitura.
|
|
330
|
+
*/
|
|
331
|
+
async cancelar(payload) {
|
|
332
|
+
return this.request({
|
|
333
|
+
method: "POST",
|
|
334
|
+
path: "/v1/nfse/cancelar",
|
|
335
|
+
body: payload
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Consulta os dados, status e DANFSE de uma NFS-e pelo número ou chave de 50 dígitos.
|
|
340
|
+
*/
|
|
341
|
+
async consultar(chaveOuNumero) {
|
|
342
|
+
return this.request({
|
|
343
|
+
method: "GET",
|
|
344
|
+
path: `/v1/nfse/${chaveOuNumero}`
|
|
345
|
+
});
|
|
346
|
+
}
|
|
208
347
|
};
|
|
209
348
|
|
|
210
349
|
// src/resources/products.ts
|
|
211
350
|
var ProductsResource = class extends BaseResource {
|
|
212
351
|
/**
|
|
213
|
-
* Consulta um produto por código de barras GTIN/EAN.
|
|
352
|
+
* Consulta dados oficiais de um produto por código de barras GTIN/EAN (V1).
|
|
214
353
|
* @param gtin Código numérico de 8 a 14 dígitos.
|
|
215
354
|
*/
|
|
216
355
|
async get(gtin) {
|
|
217
356
|
const gtinLimpo = gtin.replace(/\D/g, "");
|
|
218
357
|
const data = await this.request({
|
|
219
358
|
method: "GET",
|
|
220
|
-
path: `/
|
|
359
|
+
path: `/v1/gtin/${gtinLimpo}`
|
|
221
360
|
});
|
|
222
361
|
const prod = data.produto || data;
|
|
223
362
|
return {
|
|
@@ -234,6 +373,100 @@ var ProductsResource = class extends BaseResource {
|
|
|
234
373
|
quantidadeEmbalagem: Number(prod.quantidade_embalagem || 1)
|
|
235
374
|
};
|
|
236
375
|
}
|
|
376
|
+
/**
|
|
377
|
+
* Consulta dados enriquecidos por IA, com SEO e ficha técnica estruturada (V2).
|
|
378
|
+
* @param gtin Código numérico do produto.
|
|
379
|
+
*/
|
|
380
|
+
async getEnriched(gtin) {
|
|
381
|
+
const gtinLimpo = gtin.replace(/\D/g, "");
|
|
382
|
+
const data = await this.request({
|
|
383
|
+
method: "GET",
|
|
384
|
+
path: `/v2/gtin/${gtinLimpo}`
|
|
385
|
+
});
|
|
386
|
+
const prod = data.produto || data;
|
|
387
|
+
return {
|
|
388
|
+
gtin: prod.GTIN || prod.gtin || gtinLimpo,
|
|
389
|
+
xProd: prod.xProd || prod.descricao || "Descri\xE7\xE3o Indispon\xEDvel",
|
|
390
|
+
descricao_completa: prod.descricao_completa,
|
|
391
|
+
ficha_tecnica: prod.ficha_tecnica,
|
|
392
|
+
palavras_chave: prod.palavras_chave,
|
|
393
|
+
ncm: prod.NCM || prod.ncm,
|
|
394
|
+
cest: prod.CEST || prod.cest,
|
|
395
|
+
marca: prod.marca,
|
|
396
|
+
categoria: prod.categoria,
|
|
397
|
+
imagem_url: prod.imagem_url,
|
|
398
|
+
peso_bruto: prod.peso_bruto ? Number(prod.peso_bruto) : void 0,
|
|
399
|
+
peso_liquido: prod.peso_liquido ? Number(prod.peso_liquido) : void 0,
|
|
400
|
+
dados_tributarios_sugeridos: prod.dados_tributarios_sugeridos
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Executa busca semântica por intenção/linguagem natural (V2).
|
|
405
|
+
* @param query Termo livre de busca (ex: 'refrigerante zero lata').
|
|
406
|
+
*/
|
|
407
|
+
async search(query) {
|
|
408
|
+
const data = await this.request({
|
|
409
|
+
method: "GET",
|
|
410
|
+
path: "/v2/gtin/search",
|
|
411
|
+
params: { q: query }
|
|
412
|
+
});
|
|
413
|
+
const itens = (data.produtos || []).map((item) => ({
|
|
414
|
+
gtin: String(item.GTIN || item.gtin),
|
|
415
|
+
xProd: String(item.xProd || item.descricao),
|
|
416
|
+
marca: item.marca,
|
|
417
|
+
categoria: item.categoria,
|
|
418
|
+
score: item.score !== void 0 ? Number(item.score) : void 0,
|
|
419
|
+
ncm: item.NCM || item.ncm,
|
|
420
|
+
cest: item.CEST || item.cest,
|
|
421
|
+
imagem_url: item.imagem_url
|
|
422
|
+
}));
|
|
423
|
+
return {
|
|
424
|
+
status: data.status || "success",
|
|
425
|
+
provider: data.provider || "PAIRUS",
|
|
426
|
+
total_encontrados: itens.length,
|
|
427
|
+
termo_buscado: query,
|
|
428
|
+
produtos: itens
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Reconhece código de barras por visão computacional a partir de foto JPEG (OCR V2).
|
|
433
|
+
* @param file Blob, Buffer ou FormData com a imagem JPEG.
|
|
434
|
+
*/
|
|
435
|
+
async scan(file) {
|
|
436
|
+
let formData;
|
|
437
|
+
if (typeof FormData !== "undefined" && file instanceof FormData) {
|
|
438
|
+
formData = file;
|
|
439
|
+
} else {
|
|
440
|
+
formData = new FormData();
|
|
441
|
+
if (typeof Blob !== "undefined" && file instanceof Blob) {
|
|
442
|
+
formData.append("file", file, "barcode.jpg");
|
|
443
|
+
} else {
|
|
444
|
+
const blob = new Blob([file], { type: "image/jpeg" });
|
|
445
|
+
formData.append("file", blob, "barcode.jpg");
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
const data = await this.request({
|
|
449
|
+
method: "POST",
|
|
450
|
+
path: "/v2/gtin/scan",
|
|
451
|
+
body: formData
|
|
452
|
+
});
|
|
453
|
+
const prod = data.produto || data;
|
|
454
|
+
return {
|
|
455
|
+
gtin: prod.GTIN || prod.gtin || "",
|
|
456
|
+
xProd: prod.xProd || prod.descricao || "Descri\xE7\xE3o Indispon\xEDvel",
|
|
457
|
+
descricao_completa: prod.descricao_completa,
|
|
458
|
+
ficha_tecnica: prod.ficha_tecnica,
|
|
459
|
+
palavras_chave: prod.palavras_chave,
|
|
460
|
+
ncm: prod.NCM || prod.ncm,
|
|
461
|
+
cest: prod.CEST || prod.cest,
|
|
462
|
+
marca: prod.marca,
|
|
463
|
+
categoria: prod.categoria,
|
|
464
|
+
imagem_url: prod.imagem_url,
|
|
465
|
+
peso_bruto: prod.peso_bruto ? Number(prod.peso_bruto) : void 0,
|
|
466
|
+
peso_liquido: prod.peso_liquido ? Number(prod.peso_liquido) : void 0,
|
|
467
|
+
dados_tributarios_sugeridos: prod.dados_tributarios_sugeridos
|
|
468
|
+
};
|
|
469
|
+
}
|
|
237
470
|
};
|
|
238
471
|
|
|
239
472
|
// src/webhooks.ts
|
|
@@ -290,6 +523,8 @@ var PairusProductData = class {
|
|
|
290
523
|
webhooks = Webhooks;
|
|
291
524
|
products;
|
|
292
525
|
fiscal;
|
|
526
|
+
emissao;
|
|
527
|
+
nfse;
|
|
293
528
|
constructor(options) {
|
|
294
529
|
const apiKey = options?.apiKey || (typeof process !== "undefined" ? process.env.PAIRUS_API_KEY : void 0);
|
|
295
530
|
if (!apiKey) {
|
|
@@ -302,6 +537,8 @@ var PairusProductData = class {
|
|
|
302
537
|
const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
303
538
|
this.products = new ProductsResource(apiKey, baseUrl, timeoutMs, maxRetries);
|
|
304
539
|
this.fiscal = new FiscalResource(apiKey, baseUrl, timeoutMs, maxRetries);
|
|
540
|
+
this.emissao = new EmissaoResource(apiKey, baseUrl, timeoutMs, maxRetries);
|
|
541
|
+
this.nfse = new NFSeResource(apiKey, baseUrl, timeoutMs, maxRetries);
|
|
305
542
|
}
|
|
306
543
|
};
|
|
307
544
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -310,11 +547,15 @@ var PairusProductData = class {
|
|
|
310
547
|
DEFAULT_BASE_URL,
|
|
311
548
|
DEFAULT_MAX_RETRIES,
|
|
312
549
|
DEFAULT_TIMEOUT_MS,
|
|
550
|
+
EmissaoResource,
|
|
551
|
+
FiscalResource,
|
|
313
552
|
InvalidSignatureError,
|
|
553
|
+
NFSeResource,
|
|
314
554
|
NetworkError,
|
|
315
555
|
PairusAPIError,
|
|
316
556
|
PairusError,
|
|
317
557
|
PairusProductData,
|
|
558
|
+
ProductsResource,
|
|
318
559
|
RateLimitError,
|
|
319
560
|
Webhooks
|
|
320
561
|
});
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/errors.ts","../src/resources/base.ts","../src/resources/fiscal.ts","../src/resources/products.ts","../src/webhooks.ts","../src/client.ts"],"sourcesContent":["export { PairusProductData } from './client.js';\r\nexport { Webhooks } from './webhooks.js';\r\nexport * from './errors.js';\r\nexport * from './config.js';\r\nexport * from './types/index.js';\r\n","/**\r\n * Opções de configuração para o cliente PairusProductData.\r\n */\r\n\r\nexport interface PairusClientOptions {\r\n apiKey?: string;\r\n baseUrl?: string;\r\n timeoutMs?: number;\r\n maxRetries?: number;\r\n}\r\n\r\nexport const DEFAULT_BASE_URL = 'https://api.pairus.com.br';\r\nexport const DEFAULT_TIMEOUT_MS = 15000;\r\nexport const DEFAULT_MAX_RETRIES = 3;\r\n","/**\r\n * Classes de erro oficiais do SDK @pairus/product-data.\r\n */\r\n\r\nexport class PairusError extends Error {\r\n constructor(message: string) {\r\n super(message);\r\n this.name = 'PairusError';\r\n }\r\n}\r\n\r\nexport class PairusAPIError extends PairusError {\r\n public readonly statusCode: number;\r\n public readonly cStat: string;\r\n public readonly xMotivo: string;\r\n public readonly details?: any;\r\n\r\n constructor(statusCode: number, cStat?: string, xMotivo?: string, details?: any) {\r\n const code = cStat || String(statusCode);\r\n const reason = xMotivo || details?.detail || `Erro HTTP ${statusCode}`;\r\n super(`[${code}] ${reason}`);\r\n this.name = 'PairusAPIError';\r\n this.statusCode = statusCode;\r\n this.cStat = code;\r\n this.xMotivo = reason;\r\n this.details = details;\r\n }\r\n}\r\n\r\nexport class AuthenticationError extends PairusAPIError {\r\n constructor(cStat = '401', xMotivo = 'Chave de API inválida ou não autorizada.', details?: any) {\r\n super(401, cStat, xMotivo, details);\r\n this.name = 'AuthenticationError';\r\n }\r\n}\r\n\r\nexport class RateLimitError extends PairusAPIError {\r\n public readonly retryAfter?: number;\r\n\r\n constructor(retryAfter?: number, cStat = '429', xMotivo = 'Limite de requisições excedido.', details?: any) {\r\n super(429, cStat, xMotivo, details);\r\n this.name = 'RateLimitError';\r\n this.retryAfter = retryAfter;\r\n }\r\n}\r\n\r\nexport class InvalidSignatureError extends PairusError {\r\n constructor(message = \"A assinatura criptográfica do webhook ('X-Pairus-Signature') é inválida.\") {\r\n super(message);\r\n this.name = 'InvalidSignatureError';\r\n }\r\n}\r\n\r\nexport class NetworkError extends PairusError {\r\n constructor(message: string) {\r\n super(message);\r\n this.name = 'NetworkError';\r\n }\r\n}\r\n","import {\r\n AuthenticationError,\r\n NetworkError,\r\n PairusAPIError,\r\n RateLimitError,\r\n} from '../errors.js';\r\n\r\nexport interface RequestOptions {\r\n method: 'GET' | 'POST' | 'PUT' | 'DELETE';\r\n path: string;\r\n params?: Record<string, string>;\r\n body?: any;\r\n headers?: Record<string, string>;\r\n}\r\n\r\nexport class BaseResource {\r\n protected apiKey: string;\r\n protected baseUrl: string;\r\n protected timeoutMs: number;\r\n protected maxRetries: number;\r\n\r\n constructor(apiKey: string, baseUrl: string, timeoutMs: number, maxRetries: number) {\r\n this.apiKey = apiKey;\r\n this.baseUrl = baseUrl.replace(/\\/+$/, '');\r\n this.timeoutMs = timeoutMs;\r\n this.maxRetries = maxRetries;\r\n }\r\n\r\n protected async request<T>(options: RequestOptions): Promise<T> {\r\n let url = `${this.baseUrl}/${options.path.replace(/^\\/+/, '')}`;\r\n if (options.params) {\r\n const query = new URLSearchParams(options.params).toString();\r\n url = `${url}?${query}`;\r\n }\r\n\r\n const reqHeaders: Record<string, string> = {\r\n 'Accept': 'application/json',\r\n 'X-API-Key': this.apiKey,\r\n 'User-Agent': 'Pairus-NodeJS-SDK/1.0.0',\r\n ...(options.headers || {}),\r\n };\r\n\r\n if (options.body) {\r\n reqHeaders['Content-Type'] = 'application/json';\r\n }\r\n\r\n let lastError: any = null;\r\n\r\n for (let attempt = 0; attempt < this.maxRetries; attempt++) {\r\n try {\r\n const controller = new AbortController();\r\n const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);\r\n\r\n const response = await fetch(url, {\r\n method: options.method,\r\n headers: reqHeaders,\r\n body: options.body ? JSON.stringify(options.body) : undefined,\r\n signal: controller.signal,\r\n });\r\n\r\n clearTimeout(timeoutId);\r\n\r\n if (response.ok) {\r\n return (await response.json()) as T;\r\n }\r\n\r\n let errData: any = {};\r\n try {\r\n errData = await response.json();\r\n } catch {\r\n errData = {};\r\n }\r\n\r\n if (response.status === 401) {\r\n throw new AuthenticationError(errData.cStat, errData.xMotivo, errData);\r\n }\r\n\r\n if (response.status === 429) {\r\n const retryAfterSec = parseFloat(response.headers.get('Retry-After') || '2');\r\n if (attempt < this.maxRetries - 1) {\r\n await new Promise((res) => setTimeout(res, (retryAfterSec + Math.random() * 0.5) * 1000));\r\n continue;\r\n }\r\n throw new RateLimitError(retryAfterSec, errData.cStat, errData.xMotivo, errData);\r\n }\r\n\r\n if ([502, 503, 504].includes(response.status) && attempt < this.maxRetries - 1) {\r\n const delay = Math.pow(2, attempt) * 1000 + Math.random() * 500;\r\n await new Promise((res) => setTimeout(res, delay));\r\n continue;\r\n }\r\n\r\n throw new PairusAPIError(response.status, errData.cStat, errData.xMotivo, errData);\r\n } catch (err: any) {\r\n if (err instanceof PairusAPIError) {\r\n throw err;\r\n }\r\n lastError = err;\r\n if (attempt < this.maxRetries - 1) {\r\n const delay = Math.pow(2, attempt) * 1000 + Math.random() * 500;\r\n await new Promise((res) => setTimeout(res, delay));\r\n continue;\r\n }\r\n break;\r\n }\r\n }\r\n\r\n throw new NetworkError(`Falha de conexão com a API PAIRUS após ${this.maxRetries} tentativas: ${lastError?.message || lastError}`);\r\n }\r\n}\r\n","import { BaseResource } from './base.js';\r\nimport { TaxPredictionParams, TaxPredictionResponse } from '../types/fiscal.js';\r\n\r\nexport class FiscalResource extends BaseResource {\r\n /**\r\n * Executa a predição fiscal completa da Reforma Tributária (IBS/CBS/IS) e NF-e.\r\n */\r\n public async predict(params: TaxPredictionParams): Promise<TaxPredictionResponse> {\r\n const payload: Record<string, any> = {\r\n regime_tributario: params.regimeTributario,\r\n uf_origem: params.ufOrigem,\r\n uf_destino: params.ufDestino || params.ufOrigem,\r\n finalidade: params.finalidade || 'revenda',\r\n destinatario_contribuinte: params.destinatarioContribuinte ?? true,\r\n };\r\n\r\n if (params.xProd) payload.xProd = params.xProd;\r\n if (params.gtin) payload.gtin = params.gtin;\r\n if (params.ncm) payload.ncm = params.ncm;\r\n if (params.cest) payload.cest = params.cest;\r\n if (params.itens) payload.itens = params.itens;\r\n\r\n return this.request<TaxPredictionResponse>({\r\n method: 'POST',\r\n path: '/v2/fiscal/predict',\r\n body: payload,\r\n });\r\n }\r\n}\r\n","import { BaseResource } from './base.js';\r\nimport { ProductDetails, ProductResponse } from '../types/product.js';\r\n\r\nexport class ProductsResource extends BaseResource {\r\n /**\r\n * Consulta um produto por código de barras GTIN/EAN.\r\n * @param gtin Código numérico de 8 a 14 dígitos.\r\n */\r\n public async get(gtin: string): Promise<ProductDetails> {\r\n const gtinLimpo = gtin.replace(/\\D/g, '');\r\n const data = await this.request<ProductResponse>({\r\n method: 'GET',\r\n path: `/api/produtos/${gtinLimpo}`,\r\n });\r\n\r\n const prod: any = data.produto || data;\r\n return {\r\n gtin: prod.GTIN || prod.gtin || gtinLimpo,\r\n xProd: prod.xProd || prod.descricao || 'Descrição Indisponível',\r\n ncm: prod.NCM || prod.ncm,\r\n cest: prod.CEST || prod.cest,\r\n marca: prod.marca,\r\n fabricante: prod.fabricante,\r\n categoria: prod.categoria,\r\n imagemUrl: prod.imagem_url || prod.thumbnail,\r\n pesoBruto: prod.peso_bruto ? Number(prod.peso_bruto) : undefined,\r\n pesoLiquido: prod.peso_liquido ? Number(prod.peso_liquido) : undefined,\r\n quantidadeEmbalagem: Number(prod.quantidade_embalagem || 1),\r\n };\r\n }\r\n}\r\n","import * as crypto from 'crypto';\r\nimport { InvalidSignatureError } from './errors.js';\r\nimport { WebhookEvent } from './types/webhook.js';\r\n\r\nexport class Webhooks {\r\n /**\r\n * Calcula a assinatura HMAC-SHA256 esperada para o payload informado.\r\n */\r\n public static computeSignature(payload: string | Buffer, secret: string): string {\r\n return crypto\r\n .createHmac('sha256', secret)\r\n .update(payload)\r\n .digest('hex');\r\n }\r\n\r\n /**\r\n * Verifica de forma segura (resistente a timing attacks) a assinatura de um webhook.\r\n */\r\n public static verifySignature(\r\n payload: string | Buffer | Record<string, any>,\r\n signature: string | undefined | null,\r\n secret: string\r\n ): boolean {\r\n if (!signature || !secret) {\r\n return false;\r\n }\r\n\r\n let payloadBuffer: Buffer;\r\n if (Buffer.isBuffer(payload)) {\r\n payloadBuffer = payload;\r\n } else if (typeof payload === 'string') {\r\n payloadBuffer = Buffer.from(payload, 'utf-8');\r\n } else {\r\n payloadBuffer = Buffer.from(JSON.stringify(payload), 'utf-8');\r\n }\r\n\r\n const expectedSignature = this.computeSignature(payloadBuffer, secret);\r\n\r\n try {\r\n const sigBuf = Buffer.from(signature.trim(), 'hex');\r\n const expectedBuf = Buffer.from(expectedSignature, 'hex');\r\n\r\n if (sigBuf.length !== expectedBuf.length) {\r\n return false;\r\n }\r\n\r\n return crypto.timingSafeEqual(sigBuf, expectedBuf);\r\n } catch {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Valida a assinatura e converte o payload em objeto tipado WebhookEvent.\r\n */\r\n public static constructEvent<T = Record<string, any>>(\r\n payload: string | Buffer,\r\n signature: string | undefined | null,\r\n secret: string\r\n ): WebhookEvent<T> {\r\n if (!this.verifySignature(payload, signature, secret)) {\r\n throw new InvalidSignatureError(\"Assinatura do webhook ('X-Pairus-Signature') é inválida.\");\r\n }\r\n\r\n const rawStr = Buffer.isBuffer(payload) ? payload.toString('utf-8') : payload;\r\n return JSON.parse(rawStr) as WebhookEvent<T>;\r\n }\r\n}\r\n","import {\r\n DEFAULT_BASE_URL,\r\n DEFAULT_MAX_RETRIES,\r\n DEFAULT_TIMEOUT_MS,\r\n PairusClientOptions,\r\n} from './config.js';\r\nimport { FiscalResource } from './resources/fiscal.js';\r\nimport { ProductsResource } from './resources/products.js';\r\nimport { Webhooks } from './webhooks.js';\r\n\r\nexport class PairusProductData {\r\n public static readonly webhooks = Webhooks;\r\n public readonly webhooks = Webhooks;\r\n\r\n public readonly products: ProductsResource;\r\n public readonly fiscal: FiscalResource;\r\n\r\n constructor(options?: PairusClientOptions) {\r\n const apiKey = options?.apiKey || (typeof process !== 'undefined' ? process.env.PAIRUS_API_KEY : undefined);\r\n if (!apiKey) {\r\n throw new Error(\r\n \"A chave de API da PAIRUS é obrigatória. Passe 'apiKey' no construtor ou defina a variável 'PAIRUS_API_KEY'.\"\r\n );\r\n }\r\n\r\n const baseUrl = options?.baseUrl || (typeof process !== 'undefined' ? process.env.PAIRUS_BASE_URL : undefined) || DEFAULT_BASE_URL;\r\n const timeoutMs = options?.timeoutMs || DEFAULT_TIMEOUT_MS;\r\n const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\r\n\r\n this.products = new ProductsResource(apiKey, baseUrl, timeoutMs, maxRetries);\r\n this.fiscal = new FiscalResource(apiKey, baseUrl, timeoutMs, maxRetries);\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWO,IAAM,mBAAmB;AACzB,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB;;;ACT5B,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,iBAAN,cAA6B,YAAY;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YAAY,YAAoB,OAAgB,SAAkB,SAAe;AAC/E,UAAM,OAAO,SAAS,OAAO,UAAU;AACvC,UAAM,SAAS,WAAW,SAAS,UAAU,aAAa,UAAU;AACpE,UAAM,IAAI,IAAI,KAAK,MAAM,EAAE;AAC3B,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,QAAQ;AACb,SAAK,UAAU;AACf,SAAK,UAAU;AAA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AG,KAAK;AAClD,YAAM,cAAc,OAAO,KAAK,mBAAmB,KAAK;AAExD,UAAI,OAAO,WAAW,YAAY,QAAQ;AACxC,eAAO;AAAA,MACT;AAEA,aAAc,uBAAgB,QAAQ,WAAW;AAAA,IACnD,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,OAAc,eACZ,SACA,WACA,QACiB;AACjB,QAAI,CAAC,KAAK,gBAAgB,SAAS,WAAW,MAAM,GAAG;AACrD,YAAM,IAAI,sBAAsB,gEAA0D;AAAA,IAC5F;AAEA,UAAM,SAAS,OAAO,SAAS,OAAO,IAAI,QAAQ,SAAS,OAAO,IAAI;AACtE,WAAO,KAAK,MAAM,MAAM;AAAA,EAC1B;AACF;;;ACzDO,IAAM,oBAAN,MAAwB;AAAA,EAC7B,OAAuB,WAAW;AAAA,EAClB,WAAW;AAAA,EAEX;AAAA,EACA;AAAA,EAEhB,YAAY,SAA+B;AACzC,UAAM,SAAS,SAAS,WAAW,OAAO,YAAY,cAAc,QAAQ,IAAI,iBAAiB;AACjG,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,UAAU,SAAS,YAAY,OAAO,YAAY,cAAc,QAAQ,IAAI,kBAAkB,WAAc;AAClH,UAAM,YAAY,SAAS,aAAa;AACxC,UAAM,aAAa,SAAS,cAAc;AAE1C,SAAK,WAAW,IAAI,iBAAiB,QAAQ,SAAS,WAAW,UAAU;AAC3E,SAAK,SAAS,IAAI,eAAe,QAAQ,SAAS,WAAW,UAAU;AAAA,EACzE;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/errors.ts","../src/resources/base.ts","../src/resources/emissao.ts","../src/resources/fiscal.ts","../src/resources/nfse.ts","../src/resources/products.ts","../src/webhooks.ts","../src/client.ts"],"sourcesContent":["export { PairusProductData } from './client.js';\r\nexport { Webhooks } from './webhooks.js';\r\nexport { ProductsResource } from './resources/products.js';\r\nexport { FiscalResource } from './resources/fiscal.js';\r\nexport { EmissaoResource } from './resources/emissao.js';\r\nexport { NFSeResource } from './resources/nfse.js';\r\nexport * from './errors.js';\r\nexport * from './config.js';\r\nexport * from './types/index.js';\r\n\r\n","/**\r\n * Opções de configuração para o cliente PairusProductData.\r\n */\r\n\r\nexport interface PairusClientOptions {\r\n apiKey?: string;\r\n baseUrl?: string;\r\n timeoutMs?: number;\r\n maxRetries?: number;\r\n}\r\n\r\nexport const DEFAULT_BASE_URL = 'https://api.pairus.com.br';\r\nexport const DEFAULT_TIMEOUT_MS = 15000;\r\nexport const DEFAULT_MAX_RETRIES = 3;\r\n","/**\r\n * Classes de erro oficiais do SDK @pairus/product-data.\r\n */\r\n\r\nexport class PairusError extends Error {\r\n constructor(message: string) {\r\n super(message);\r\n this.name = 'PairusError';\r\n }\r\n}\r\n\r\nexport class PairusAPIError extends PairusError {\r\n public readonly statusCode: number;\r\n public readonly cStat: string;\r\n public readonly xMotivo: string;\r\n public readonly details?: any;\r\n\r\n constructor(statusCode: number, cStat?: string, xMotivo?: string, details?: any) {\r\n const code = cStat || String(statusCode);\r\n const reason = xMotivo || details?.detail || `Erro HTTP ${statusCode}`;\r\n super(`[${code}] ${reason}`);\r\n this.name = 'PairusAPIError';\r\n this.statusCode = statusCode;\r\n this.cStat = code;\r\n this.xMotivo = reason;\r\n this.details = details;\r\n }\r\n}\r\n\r\nexport class AuthenticationError extends PairusAPIError {\r\n constructor(cStat = '401', xMotivo = 'Chave de API inválida ou não autorizada.', details?: any) {\r\n super(401, cStat, xMotivo, details);\r\n this.name = 'AuthenticationError';\r\n }\r\n}\r\n\r\nexport class RateLimitError extends PairusAPIError {\r\n public readonly retryAfter?: number;\r\n\r\n constructor(retryAfter?: number, cStat = '429', xMotivo = 'Limite de requisições excedido.', details?: any) {\r\n super(429, cStat, xMotivo, details);\r\n this.name = 'RateLimitError';\r\n this.retryAfter = retryAfter;\r\n }\r\n}\r\n\r\nexport class InvalidSignatureError extends PairusError {\r\n constructor(message = \"A assinatura criptográfica do webhook ('X-Pairus-Signature') é inválida.\") {\r\n super(message);\r\n this.name = 'InvalidSignatureError';\r\n }\r\n}\r\n\r\nexport class NetworkError extends PairusError {\r\n constructor(message: string) {\r\n super(message);\r\n this.name = 'NetworkError';\r\n }\r\n}\r\n","import {\r\n AuthenticationError,\r\n NetworkError,\r\n PairusAPIError,\r\n RateLimitError,\r\n} from '../errors.js';\r\n\r\nexport interface RequestOptions {\r\n method: 'GET' | 'POST' | 'PUT' | 'DELETE';\r\n path: string;\r\n params?: Record<string, string>;\r\n body?: any;\r\n headers?: Record<string, string>;\r\n}\r\n\r\nexport class BaseResource {\r\n protected apiKey: string;\r\n protected baseUrl: string;\r\n protected timeoutMs: number;\r\n protected maxRetries: number;\r\n\r\n constructor(apiKey: string, baseUrl: string, timeoutMs: number, maxRetries: number) {\r\n this.apiKey = apiKey;\r\n this.baseUrl = baseUrl.replace(/\\/+$/, '');\r\n this.timeoutMs = timeoutMs;\r\n this.maxRetries = maxRetries;\r\n }\r\n\r\n protected async request<T>(options: RequestOptions): Promise<T> {\r\n let url = `${this.baseUrl}/${options.path.replace(/^\\/+/, '')}`;\r\n if (options.params) {\r\n const query = new URLSearchParams(options.params).toString();\r\n url = `${url}?${query}`;\r\n }\r\n\r\n const reqHeaders: Record<string, string> = {\r\n 'Accept': 'application/json',\r\n 'X-API-Key': this.apiKey,\r\n 'User-Agent': 'Pairus-NodeJS-SDK/1.2.0',\r\n ...(options.headers || {}),\r\n };\r\n\r\n const isFormData = typeof FormData !== 'undefined' && options.body instanceof FormData;\r\n\r\n if (options.body && !isFormData && !reqHeaders['Content-Type']) {\r\n reqHeaders['Content-Type'] = 'application/json';\r\n }\r\n\r\n let lastError: any = null;\r\n\r\n for (let attempt = 0; attempt < this.maxRetries; attempt++) {\r\n try {\r\n const controller = new AbortController();\r\n const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);\r\n\r\n const bodyData = isFormData\r\n ? options.body\r\n : options.body\r\n ? JSON.stringify(options.body)\r\n : undefined;\r\n\r\n const response = await fetch(url, {\r\n method: options.method,\r\n headers: reqHeaders,\r\n body: bodyData,\r\n signal: controller.signal,\r\n });\r\n\r\n clearTimeout(timeoutId);\r\n\r\n if (response.ok || (response.status >= 200 && response.status < 300)) {\r\n return (await response.json()) as T;\r\n }\r\n\r\n let errData: any = {};\r\n try {\r\n errData = await response.json();\r\n } catch {\r\n errData = {};\r\n }\r\n\r\n if (response.status === 401) {\r\n throw new AuthenticationError(errData.cStat, errData.xMotivo, errData);\r\n }\r\n\r\n if (response.status === 429) {\r\n const retryAfterSec = parseFloat(response.headers.get('Retry-After') || '2');\r\n if (attempt < this.maxRetries - 1) {\r\n await new Promise((res) => setTimeout(res, (retryAfterSec + Math.random() * 0.5) * 1000));\r\n continue;\r\n }\r\n throw new RateLimitError(retryAfterSec, errData.cStat, errData.xMotivo, errData);\r\n }\r\n\r\n if ([502, 503, 504].includes(response.status) && attempt < this.maxRetries - 1) {\r\n const delay = Math.pow(2, attempt) * 1000 + Math.random() * 500;\r\n await new Promise((res) => setTimeout(res, delay));\r\n continue;\r\n }\r\n\r\n throw new PairusAPIError(response.status, errData.cStat, errData.xMotivo, errData);\r\n } catch (err: any) {\r\n if (err instanceof PairusAPIError) {\r\n throw err;\r\n }\r\n lastError = err;\r\n if (attempt < this.maxRetries - 1) {\r\n const delay = Math.pow(2, attempt) * 1000 + Math.random() * 500;\r\n await new Promise((res) => setTimeout(res, delay));\r\n continue;\r\n }\r\n break;\r\n }\r\n }\r\n\r\n throw new NetworkError(`Falha de conexão com a API PAIRUS após ${this.maxRetries} tentativas: ${lastError?.message || lastError}`);\r\n }\r\n}\r\n","import { BaseResource } from './base.js';\nimport {\n CancelamentoInput,\n CartaCorrecaoInput,\n EmissaoNFeInput,\n EmissaoNFeResponse,\n EventoNFeResponse,\n InutilizacaoInput,\n} from '../types/emissao.js';\n\nexport class EmissaoResource extends BaseResource {\n /**\n * Emite uma Nota Fiscal Eletrônica (NF-e Modelo 55) perante a SEFAZ.\n */\n public async emitirNFe(payload: EmissaoNFeInput): Promise<EmissaoNFeResponse> {\n return this.request<EmissaoNFeResponse>({\n method: 'POST',\n path: '/v1/nfe/emitir',\n body: payload,\n });\n }\n\n /**\n * Emite uma Nota Fiscal de Consumidor Eletrônica (NFC-e Modelo 65) perante a SEFAZ.\n */\n public async emitirNFCe(payload: EmissaoNFeInput): Promise<EmissaoNFeResponse> {\n return this.request<EmissaoNFeResponse>({\n method: 'POST',\n path: '/v1/nfce/emitir',\n body: payload,\n });\n }\n\n /**\n * Simula uma emissão fiscal sem transmitir à SEFAZ (custo ZERO de créditos).\n */\n public async simular(payload: EmissaoNFeInput): Promise<EmissaoNFeResponse> {\n return this.request<EmissaoNFeResponse>({\n method: 'POST',\n path: '/v1/nfe/simular',\n body: payload,\n });\n }\n\n /**\n * Homologa o cancelamento oficial de uma NF-e ou NFC-e perante a SEFAZ.\n */\n public async cancelar(params: CancelamentoInput): Promise<EventoNFeResponse> {\n return this.request<EventoNFeResponse>({\n method: 'POST',\n path: '/v1/nfe/cancelar',\n body: {\n chave_acesso: params.chave_acesso,\n justificativa: params.justificativa,\n protocolo_autorizacao: params.protocolo_autorizacao,\n },\n });\n }\n\n /**\n * Emite uma Carta de Correção Eletrônica (CC-e) perante a SEFAZ.\n */\n public async cartaCorrecao(params: CartaCorrecaoInput): Promise<EventoNFeResponse> {\n return this.request<EventoNFeResponse>({\n method: 'POST',\n path: '/v1/nfe/carta-correcao',\n body: {\n chave_acesso: params.chave_acesso,\n correcao: params.correcao,\n sequencia_evento: params.sequencia_evento ?? 1,\n },\n });\n }\n\n /**\n * Inutiliza uma faixa de numeração quebrada na SEFAZ (Ajuste SINIEF 07/05).\n */\n public async inutilizar(params: InutilizacaoInput): Promise<EventoNFeResponse> {\n return this.request<EventoNFeResponse>({\n method: 'POST',\n path: '/v1/nfe/inutilizar',\n body: {\n cnpj_emitente: params.cnpj_emitente,\n serie: params.serie,\n numero_inicial: params.numero_inicial,\n numero_final: params.numero_final,\n justificativa: params.justificativa,\n ano: params.ano,\n modelo: params.modelo ?? 55,\n },\n });\n }\n}\n","import { BaseResource } from './base.js';\r\nimport { TaxPredictionParams, TaxPredictionResponse } from '../types/fiscal.js';\r\n\r\nexport class FiscalResource extends BaseResource {\r\n /**\r\n * Executa a predição fiscal completa da Reforma Tributária (IBS/CBS/IS) e NF-e.\r\n */\r\n public async predict(params: TaxPredictionParams): Promise<TaxPredictionResponse> {\r\n const payload: Record<string, any> = {\r\n regime_tributario: params.regimeTributario,\r\n uf_origem: params.ufOrigem,\r\n uf_destino: params.ufDestino || params.ufOrigem,\r\n finalidade: params.finalidade || 'revenda',\r\n destinatario_contribuinte: params.destinatarioContribuinte ?? true,\r\n };\r\n\r\n if (params.xProd) payload.xProd = params.xProd;\r\n if (params.gtin) payload.gtin = params.gtin;\r\n if (params.ncm) payload.ncm = params.ncm;\r\n if (params.cest) payload.cest = params.cest;\r\n if (params.itens) payload.itens = params.itens;\r\n\r\n return this.request<TaxPredictionResponse>({\r\n method: 'POST',\r\n path: '/v2/fiscal/predict',\r\n body: payload,\r\n });\r\n }\r\n\r\n /**\r\n * Audita e higieniza uma lista de produtos em lote perante as tabelas fiscais vigentes.\r\n */\r\n public async sanitize(itens: Array<Record<string, any>>): Promise<any> {\r\n return this.request<any>({\r\n method: 'POST',\r\n path: '/v2/fiscal/sanitize',\r\n body: { itens },\r\n });\r\n }\r\n}\r\n\r\n","import { BaseResource } from './base.js';\nimport {\n CancelamentoNFSeInput,\n CancelamentoNFSeResponse,\n NFSeEmissaoInput,\n NFSeEmissaoResponse,\n} from '../types/nfse.js';\n\nexport class NFSeResource extends BaseResource {\n /**\n * Emite uma Nota Fiscal de Serviços Eletrônica (NFS-e) perante o SND ou prefeitura.\n */\n async emitir(payload: NFSeEmissaoInput | Record<string, any>): Promise<NFSeEmissaoResponse> {\n return this.request<NFSeEmissaoResponse>({\n method: 'POST',\n path: '/v1/nfse/emitir',\n body: payload,\n });\n }\n\n /**\n * Simula o cálculo de NFS-e com retenções e apuração tributária (custo ZERO de créditos).\n */\n async simular(payload: NFSeEmissaoInput | Record<string, any>): Promise<NFSeEmissaoResponse> {\n return this.request<NFSeEmissaoResponse>({\n method: 'POST',\n path: '/v1/nfse/simular',\n body: payload,\n });\n }\n\n /**\n * Homologa o cancelamento oficial de uma NFS-e perante o SND ou prefeitura.\n */\n async cancelar(payload: CancelamentoNFSeInput): Promise<CancelamentoNFSeResponse> {\n return this.request<CancelamentoNFSeResponse>({\n method: 'POST',\n path: '/v1/nfse/cancelar',\n body: payload,\n });\n }\n\n /**\n * Consulta os dados, status e DANFSE de uma NFS-e pelo número ou chave de 50 dígitos.\n */\n async consultar(chaveOuNumero: string): Promise<Record<string, any>> {\n return this.request<Record<string, any>>({\n method: 'GET',\n path: `/v1/nfse/${chaveOuNumero}`,\n });\n }\n}\n\r\n","import { BaseResource } from './base.js';\nimport {\n ProductDetails,\n ProductEnrichedDetails,\n ProductResponse,\n ProductSearchResponse,\n ProductSearchResultItem,\n} from '../types/product.js';\n\nexport class ProductsResource extends BaseResource {\n /**\n * Consulta dados oficiais de um produto por código de barras GTIN/EAN (V1).\n * @param gtin Código numérico de 8 a 14 dígitos.\n */\n public async get(gtin: string): Promise<ProductDetails> {\n const gtinLimpo = gtin.replace(/\\D/g, '');\n const data = await this.request<ProductResponse>({\n method: 'GET',\n path: `/v1/gtin/${gtinLimpo}`,\n });\n\n const prod: any = data.produto || data;\n return {\n gtin: prod.GTIN || prod.gtin || gtinLimpo,\n xProd: prod.xProd || prod.descricao || 'Descrição Indisponível',\n ncm: prod.NCM || prod.ncm,\n cest: prod.CEST || prod.cest,\n marca: prod.marca,\n fabricante: prod.fabricante,\n categoria: prod.categoria,\n imagemUrl: prod.imagem_url || prod.thumbnail,\n pesoBruto: prod.peso_bruto ? Number(prod.peso_bruto) : undefined,\n pesoLiquido: prod.peso_liquido ? Number(prod.peso_liquido) : undefined,\n quantidadeEmbalagem: Number(prod.quantidade_embalagem || 1),\n };\n }\n\n /**\n * Consulta dados enriquecidos por IA, com SEO e ficha técnica estruturada (V2).\n * @param gtin Código numérico do produto.\n */\n public async getEnriched(gtin: string): Promise<ProductEnrichedDetails> {\n const gtinLimpo = gtin.replace(/\\D/g, '');\n const data = await this.request<any>({\n method: 'GET',\n path: `/v2/gtin/${gtinLimpo}`,\n });\n\n const prod = data.produto || data;\n return {\n gtin: prod.GTIN || prod.gtin || gtinLimpo,\n xProd: prod.xProd || prod.descricao || 'Descrição Indisponível',\n descricao_completa: prod.descricao_completa,\n ficha_tecnica: prod.ficha_tecnica,\n palavras_chave: prod.palavras_chave,\n ncm: prod.NCM || prod.ncm,\n cest: prod.CEST || prod.cest,\n marca: prod.marca,\n categoria: prod.categoria,\n imagem_url: prod.imagem_url,\n peso_bruto: prod.peso_bruto ? Number(prod.peso_bruto) : undefined,\n peso_liquido: prod.peso_liquido ? Number(prod.peso_liquido) : undefined,\n dados_tributarios_sugeridos: prod.dados_tributarios_sugeridos,\n };\n }\n\n /**\n * Executa busca semântica por intenção/linguagem natural (V2).\n * @param query Termo livre de busca (ex: 'refrigerante zero lata').\n */\n public async search(query: string): Promise<ProductSearchResponse> {\n const data = await this.request<any>({\n method: 'GET',\n path: '/v2/gtin/search',\n params: { q: query },\n });\n\n const itens: ProductSearchResultItem[] = (data.produtos || []).map((item: any) => ({\n gtin: String(item.GTIN || item.gtin),\n xProd: String(item.xProd || item.descricao),\n marca: item.marca,\n categoria: item.categoria,\n score: item.score !== undefined ? Number(item.score) : undefined,\n ncm: item.NCM || item.ncm,\n cest: item.CEST || item.cest,\n imagem_url: item.imagem_url,\n }));\n\n return {\n status: data.status || 'success',\n provider: data.provider || 'PAIRUS',\n total_encontrados: itens.length,\n termo_buscado: query,\n produtos: itens,\n };\n }\n\n /**\n * Reconhece código de barras por visão computacional a partir de foto JPEG (OCR V2).\n * @param file Blob, Buffer ou FormData com a imagem JPEG.\n */\n public async scan(file: Blob | Buffer | FormData): Promise<ProductEnrichedDetails> {\n let formData: FormData;\n\n if (typeof FormData !== 'undefined' && file instanceof FormData) {\n formData = file;\n } else {\n formData = new FormData();\n if (typeof Blob !== 'undefined' && file instanceof Blob) {\n formData.append('file', file, 'barcode.jpg');\n } else {\n // Node Buffer\n const blob = new Blob([file as any], { type: 'image/jpeg' });\n formData.append('file', blob, 'barcode.jpg');\n }\n }\n\n const data = await this.request<any>({\n method: 'POST',\n path: '/v2/gtin/scan',\n body: formData,\n });\n\n const prod = data.produto || data;\n return {\n gtin: prod.GTIN || prod.gtin || '',\n xProd: prod.xProd || prod.descricao || 'Descrição Indisponível',\n descricao_completa: prod.descricao_completa,\n ficha_tecnica: prod.ficha_tecnica,\n palavras_chave: prod.palavras_chave,\n ncm: prod.NCM || prod.ncm,\n cest: prod.CEST || prod.cest,\n marca: prod.marca,\n categoria: prod.categoria,\n imagem_url: prod.imagem_url,\n peso_bruto: prod.peso_bruto ? Number(prod.peso_bruto) : undefined,\n peso_liquido: prod.peso_liquido ? Number(prod.peso_liquido) : undefined,\n dados_tributarios_sugeridos: prod.dados_tributarios_sugeridos,\n };\n }\n}\r\n","import * as crypto from 'crypto';\r\nimport { InvalidSignatureError } from './errors.js';\r\nimport { WebhookEvent } from './types/webhook.js';\r\n\r\nexport class Webhooks {\r\n /**\r\n * Calcula a assinatura HMAC-SHA256 esperada para o payload informado.\r\n */\r\n public static computeSignature(payload: string | Buffer, secret: string): string {\r\n return crypto\r\n .createHmac('sha256', secret)\r\n .update(payload)\r\n .digest('hex');\r\n }\r\n\r\n /**\r\n * Verifica de forma segura (resistente a timing attacks) a assinatura de um webhook.\r\n */\r\n public static verifySignature(\r\n payload: string | Buffer | Record<string, any>,\r\n signature: string | undefined | null,\r\n secret: string\r\n ): boolean {\r\n if (!signature || !secret) {\r\n return false;\r\n }\r\n\r\n let payloadBuffer: Buffer;\r\n if (Buffer.isBuffer(payload)) {\r\n payloadBuffer = payload;\r\n } else if (typeof payload === 'string') {\r\n payloadBuffer = Buffer.from(payload, 'utf-8');\r\n } else {\r\n payloadBuffer = Buffer.from(JSON.stringify(payload), 'utf-8');\r\n }\r\n\r\n const expectedSignature = this.computeSignature(payloadBuffer, secret);\r\n\r\n try {\r\n const sigBuf = Buffer.from(signature.trim(), 'hex');\r\n const expectedBuf = Buffer.from(expectedSignature, 'hex');\r\n\r\n if (sigBuf.length !== expectedBuf.length) {\r\n return false;\r\n }\r\n\r\n return crypto.timingSafeEqual(sigBuf, expectedBuf);\r\n } catch {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Valida a assinatura e converte o payload em objeto tipado WebhookEvent.\r\n */\r\n public static constructEvent<T = Record<string, any>>(\r\n payload: string | Buffer,\r\n signature: string | undefined | null,\r\n secret: string\r\n ): WebhookEvent<T> {\r\n if (!this.verifySignature(payload, signature, secret)) {\r\n throw new InvalidSignatureError(\"Assinatura do webhook ('X-Pairus-Signature') é inválida.\");\r\n }\r\n\r\n const rawStr = Buffer.isBuffer(payload) ? payload.toString('utf-8') : payload;\r\n return JSON.parse(rawStr) as WebhookEvent<T>;\r\n }\r\n}\r\n","import {\r\n DEFAULT_BASE_URL,\r\n DEFAULT_MAX_RETRIES,\r\n DEFAULT_TIMEOUT_MS,\r\n PairusClientOptions,\r\n} from './config.js';\r\nimport { EmissaoResource } from './resources/emissao.js';\r\nimport { FiscalResource } from './resources/fiscal.js';\r\nimport { NFSeResource } from './resources/nfse.js';\r\nimport { ProductsResource } from './resources/products.js';\r\nimport { Webhooks } from './webhooks.js';\r\n\r\nexport class PairusProductData {\r\n public static readonly webhooks = Webhooks;\r\n public readonly webhooks = Webhooks;\r\n\r\n public readonly products: ProductsResource;\r\n public readonly fiscal: FiscalResource;\r\n public readonly emissao: EmissaoResource;\r\n public readonly nfse: NFSeResource;\r\n\r\n constructor(options?: PairusClientOptions) {\r\n const apiKey = options?.apiKey || (typeof process !== 'undefined' ? process.env.PAIRUS_API_KEY : undefined);\r\n if (!apiKey) {\r\n throw new Error(\r\n \"A chave de API da PAIRUS é obrigatória. Passe 'apiKey' no construtor ou defina a variável 'PAIRUS_API_KEY'.\"\r\n );\r\n }\r\n\r\n const baseUrl = options?.baseUrl || (typeof process !== 'undefined' ? process.env.PAIRUS_BASE_URL : undefined) || DEFAULT_BASE_URL;\r\n const timeoutMs = options?.timeoutMs || DEFAULT_TIMEOUT_MS;\r\n const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\r\n\r\n this.products = new ProductsResource(apiKey, baseUrl, timeoutMs, maxRetries);\r\n this.fiscal = new FiscalResource(apiKey, baseUrl, timeoutMs, maxRetries);\r\n this.emissao = new EmissaoResource(apiKey, baseUrl, timeoutMs, maxRetries);\r\n this.nfse = new NFSeResource(apiKey, baseUrl, timeoutMs, maxRetries);\r\n }\r\n}\r\n\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWO,IAAM,mBAAmB;AACzB,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB;;;ACT5B,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,iBAAN,cAA6B,YAAY;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEhB,YAAY,YAAoB,OAAgB,SAAkB,SAAe;AAC/E,UAAM,OAAO,SAAS,OAAO,UAAU;AACvC,UAAM,SAAS,WAAW,SAAS,UAAU,aAAa,UAAU;AACpE,UAAM,IAAI,IAAI,KAAK,MAAM,EAAE;AAC3B,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,QAAQ;AACb,SAAK,UAAU;AACf,SAAK,UAAU;AAAA,EACjB;AACF;AAEO,IAAM,s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