@useinvio/nfse-sdk 1.0.2 → 1.0.3

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 CHANGED
@@ -439,6 +439,14 @@ const baseUrl = resolveSefinBaseUrl('restrita');
439
439
 
440
440
  ---
441
441
 
442
+ ## Observabilidade da SEFIN
443
+
444
+ O SDK pode emitir métricas de latência das chamadas mTLS feitas contra a SEFIN, incluindo `p50Ms`, `p95Ms` e `p99Ms` por operação e ambiente. Essas métricas medem o round-trip externo da SEFIN, separado da latência total da sua API.
445
+
446
+ Leia o guia completo em [docs/METRICS.md](./docs/METRICS.md).
447
+
448
+ ---
449
+
442
450
  ## Referência da API
443
451
 
444
452
  ### Funções principais
@@ -450,6 +458,8 @@ const baseUrl = resolveSefinBaseUrl('restrita');
450
458
  | `consultarNfse(chaveAcesso, pfx, ambiente?)` | Consulta uma NFS-e pela chave de acesso. |
451
459
  | `enviarEvento(xmlGzipB64, pfx, chaveAcesso, ambiente?)` | Envia evento fiscal (cancelamento, etc.). |
452
460
  | `buildDpsFromJson(nota)` | Monta o XML da DPS sem assinar nem enviar. |
461
+ | `setSefinRequestObserver(observer)` | Registra um hook para observar latência/status das chamadas à SEFIN. |
462
+ | `createSefinLatencyTracker(options?)` | Agrega amostras recentes e calcula `p50Ms`, `p95Ms` e `p99Ms`. |
453
463
 
454
464
  ### Certificado
455
465
 
package/dist/index.d.ts CHANGED
@@ -6,8 +6,8 @@
6
6
  */
7
7
  export { SEFIN_BASE_URL, TP_AMB, DEFAULT_AMBIENTE, resolveSefinBaseUrl } from './config.js';
8
8
  export type { Ambiente } from './config.js';
9
- export { consultarNfse, enviarEvento, extrairErros } from './sefinClient.js';
10
- export type { SefinErro, SefinResposta } from './sefinClient.js';
9
+ export { consultarNfse, createSefinLatencyTracker, enviarEvento, extrairErros, getSefinRequestObserver, setSefinRequestObserver, } from './sefinClient.js';
10
+ export type { SefinErro, SefinLatencySeriesSnapshot, SefinLatencySnapshot, SefinLatencyTracker, SefinLatencyTrackerOptions, SefinOperation, SefinRequestMetric, SefinRequestObserver, SefinResposta, } from './sefinClient.js';
11
11
  export { buildDpsFromJson, buildDpsId } from './dpsJson.js';
12
12
  export type { BuiltDps, ComExt, DpsJsonInput, DpsJsonRequest, EventoServico, Intermediario, Obra, PrestadorProfile, ServicoProfile, Tomador, TotTrib, TribFed, TribMun, TribNac, Valores, } from './dpsJson.js';
13
13
  export { DpsFiscalValidationError, validateDpsJsonRequest } from './fiscalValidation.js';
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * No database, no tenants, no business rules.
6
6
  */
7
7
  export { SEFIN_BASE_URL, TP_AMB, DEFAULT_AMBIENTE, resolveSefinBaseUrl } from './config.js';
8
- export { consultarNfse, enviarEvento, extrairErros } from './sefinClient.js';
8
+ export { consultarNfse, createSefinLatencyTracker, enviarEvento, extrairErros, getSefinRequestObserver, setSefinRequestObserver, } from './sefinClient.js';
9
9
  export { buildDpsFromJson, buildDpsId } from './dpsJson.js';
10
10
  export { DpsFiscalValidationError, validateDpsJsonRequest } from './fiscalValidation.js';
11
11
  export { EmitirNotaError, emitirNfse } from './emissaoNota.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAG5F,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAG7E,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAmB5D,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAEzF,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAG/D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAUzC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAExD,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAEzF,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAG5F,OAAO,EACL,aAAa,EACb,yBAAyB,EACzB,YAAY,EACZ,YAAY,EACZ,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,kBAAkB,CAAC;AAa1B,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAmB5D,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAEzF,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAG/D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAUzC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAExD,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAEzF,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC"}
@@ -10,6 +10,52 @@ export interface SefinResposta {
10
10
  /** Corpo bruto parseado (JSON) */
11
11
  body: any;
12
12
  }
13
+ export type SefinOperation = 'transmitir_dps' | 'consultar_nfse' | 'enviar_evento';
14
+ export interface SefinRequestMetric {
15
+ operation: SefinOperation;
16
+ ambiente?: Ambiente;
17
+ method: 'GET' | 'POST';
18
+ pathTemplate: string;
19
+ durationMs: number;
20
+ status?: number;
21
+ success: boolean;
22
+ errorName?: string;
23
+ errorMessage?: string;
24
+ }
25
+ export type SefinRequestObserver = (metric: SefinRequestMetric) => void;
26
+ export interface SefinLatencyTrackerOptions {
27
+ /**
28
+ * Maximum number of recent latency samples kept for each operation/environment
29
+ * series. P99 is calculated over this rolling window.
30
+ */
31
+ maxSamplesPerSeries?: number;
32
+ }
33
+ export interface SefinLatencySeriesSnapshot {
34
+ operation: SefinOperation;
35
+ ambiente?: Ambiente;
36
+ count: number;
37
+ successCount: number;
38
+ errorCount: number;
39
+ sampleCount: number;
40
+ minMs: number;
41
+ maxMs: number;
42
+ avgMs: number;
43
+ p50Ms: number;
44
+ p95Ms: number;
45
+ p99Ms: number;
46
+ }
47
+ export interface SefinLatencySnapshot {
48
+ generatedAt: string;
49
+ series: SefinLatencySeriesSnapshot[];
50
+ }
51
+ export interface SefinLatencyTracker {
52
+ observe(metric: SefinRequestMetric): void;
53
+ snapshot(): SefinLatencySnapshot;
54
+ reset(): void;
55
+ }
56
+ export declare function setSefinRequestObserver(observer: SefinRequestObserver | undefined): void;
57
+ export declare function getSefinRequestObserver(): SefinRequestObserver | undefined;
58
+ export declare function createSefinLatencyTracker(options?: SefinLatencyTrackerOptions): SefinLatencyTracker;
13
59
  /** Normaliza a lista de erros retornada pelo SEFIN em diferentes formatos. */
14
60
  export declare function extrairErros(body: any): SefinErro[];
15
61
  /** SefinNacional · POST /nfse — transporte baixo nivel de DPS ja compactada em GZip+Base64. */
@@ -1,12 +1,94 @@
1
1
  import https from 'node:https';
2
+ import { performance } from 'node:perf_hooks';
2
3
  import { resolveSefinBaseUrl } from './config.js';
3
4
  /** Evita que uma conexao travada com o SEFIN prenda um worker indefinidamente. */
4
5
  const SEFIN_REQUEST_TIMEOUT_MS = 60_000;
6
+ let sefinRequestObserver;
7
+ export function setSefinRequestObserver(observer) {
8
+ sefinRequestObserver = observer;
9
+ }
10
+ export function getSefinRequestObserver() {
11
+ return sefinRequestObserver;
12
+ }
13
+ function notifySefinRequestObserver(metric) {
14
+ try {
15
+ sefinRequestObserver?.(metric);
16
+ }
17
+ catch {
18
+ // Observability hooks must not change SDK transport behavior.
19
+ }
20
+ }
21
+ function percentile(sortedValues, quantile) {
22
+ if (!sortedValues.length)
23
+ return 0;
24
+ const index = Math.min(sortedValues.length - 1, Math.max(0, Math.ceil(sortedValues.length * quantile) - 1));
25
+ return sortedValues[index];
26
+ }
27
+ function trackerKey(metric) {
28
+ return `${metric.operation}:${metric.ambiente ?? 'default'}`;
29
+ }
30
+ export function createSefinLatencyTracker(options = {}) {
31
+ const maxSamplesPerSeries = Math.max(1, Math.floor(options.maxSamplesPerSeries ?? 1_000));
32
+ const series = new Map();
33
+ return {
34
+ observe(metric) {
35
+ const key = trackerKey(metric);
36
+ let bucket = series.get(key);
37
+ if (!bucket) {
38
+ bucket = {
39
+ operation: metric.operation,
40
+ ambiente: metric.ambiente,
41
+ count: 0,
42
+ successCount: 0,
43
+ errorCount: 0,
44
+ durations: [],
45
+ };
46
+ series.set(key, bucket);
47
+ }
48
+ bucket.count += 1;
49
+ if (metric.success)
50
+ bucket.successCount += 1;
51
+ else
52
+ bucket.errorCount += 1;
53
+ bucket.durations.push(metric.durationMs);
54
+ if (bucket.durations.length > maxSamplesPerSeries) {
55
+ bucket.durations.splice(0, bucket.durations.length - maxSamplesPerSeries);
56
+ }
57
+ },
58
+ snapshot() {
59
+ return {
60
+ generatedAt: new Date().toISOString(),
61
+ series: Array.from(series.values()).map((bucket) => {
62
+ const sortedDurations = [...bucket.durations].sort((a, b) => a - b);
63
+ const total = sortedDurations.reduce((sum, value) => sum + value, 0);
64
+ return {
65
+ operation: bucket.operation,
66
+ ambiente: bucket.ambiente,
67
+ count: bucket.count,
68
+ successCount: bucket.successCount,
69
+ errorCount: bucket.errorCount,
70
+ sampleCount: sortedDurations.length,
71
+ minMs: sortedDurations[0] ?? 0,
72
+ maxMs: sortedDurations.at(-1) ?? 0,
73
+ avgMs: sortedDurations.length ? total / sortedDurations.length : 0,
74
+ p50Ms: percentile(sortedDurations, 0.50),
75
+ p95Ms: percentile(sortedDurations, 0.95),
76
+ p99Ms: percentile(sortedDurations, 0.99),
77
+ };
78
+ }).sort((a, b) => (a.operation.localeCompare(b.operation) ||
79
+ (a.ambiente ?? '').localeCompare(b.ambiente ?? ''))),
80
+ };
81
+ },
82
+ reset() {
83
+ series.clear();
84
+ },
85
+ };
86
+ }
5
87
  /**
6
88
  * Requisição mTLS de baixo nível ao SefinNacional, retornando o corpo bruto (Buffer).
7
89
  * Usa key+cert PEM no handshake (o .pfx legado ICP-Brasil é rejeitado pelo TLS do Node).
8
90
  */
9
- function sefinRequest(opts, pfx, baseOverride) {
91
+ function sefinRequest(opts, pfx, metricOpts, baseOverride) {
10
92
  const url = new URL(`${baseOverride ?? resolveSefinBaseUrl()}${opts.path}`);
11
93
  const payload = opts.jsonBody != null ? JSON.stringify(opts.jsonBody) : undefined;
12
94
  const headers = {
@@ -28,16 +110,49 @@ function sefinRequest(opts, pfx, baseOverride) {
28
110
  timeout: SEFIN_REQUEST_TIMEOUT_MS,
29
111
  };
30
112
  return new Promise((resolve, reject) => {
113
+ const startedAt = performance.now();
114
+ let metricSent = false;
115
+ const emitMetric = (metric) => {
116
+ if (metricSent)
117
+ return;
118
+ metricSent = true;
119
+ notifySefinRequestObserver({
120
+ ...metric,
121
+ durationMs: performance.now() - startedAt,
122
+ });
123
+ };
31
124
  const req = https.request(options, (res) => {
32
125
  const chunks = [];
33
126
  res.on('data', (c) => chunks.push(c));
34
- res.on('end', () => resolve({
35
- status: res.statusCode ?? 0,
36
- contentType: String(res.headers['content-type'] ?? ''),
37
- buffer: Buffer.concat(chunks),
38
- }));
127
+ res.on('end', () => {
128
+ const status = res.statusCode ?? 0;
129
+ emitMetric({
130
+ operation: metricOpts.operation,
131
+ ambiente: metricOpts.ambiente,
132
+ method: opts.method,
133
+ pathTemplate: metricOpts.pathTemplate,
134
+ status,
135
+ success: status >= 200 && status < 300,
136
+ });
137
+ resolve({
138
+ status,
139
+ contentType: String(res.headers['content-type'] ?? ''),
140
+ buffer: Buffer.concat(chunks),
141
+ });
142
+ });
143
+ });
144
+ req.on('error', (error) => {
145
+ emitMetric({
146
+ operation: metricOpts.operation,
147
+ ambiente: metricOpts.ambiente,
148
+ method: opts.method,
149
+ pathTemplate: metricOpts.pathTemplate,
150
+ success: false,
151
+ errorName: error.name,
152
+ errorMessage: error.message,
153
+ });
154
+ reject(error);
39
155
  });
40
- req.on('error', reject);
41
156
  req.on('timeout', () => {
42
157
  req.destroy(new Error(`SEFIN request timed out after ${SEFIN_REQUEST_TIMEOUT_MS}ms`));
43
158
  });
@@ -104,12 +219,12 @@ export function extrairErros(body) {
104
219
  /** SefinNacional · POST /nfse — transporte baixo nivel de DPS ja compactada em GZip+Base64. */
105
220
  export async function transmitirDpsCompactada(dpsXmlGZipB64, pfx, ambiente) {
106
221
  const base = ambiente ? resolveSefinBaseUrl(ambiente) : undefined;
107
- return parseJson(await sefinRequest({ method: 'POST', path: '/nfse', jsonBody: { dpsXmlGZipB64 } }, pfx, base));
222
+ return parseJson(await sefinRequest({ method: 'POST', path: '/nfse', jsonBody: { dpsXmlGZipB64 } }, pfx, { operation: 'transmitir_dps', ambiente, pathTemplate: '/nfse' }, base));
108
223
  }
109
224
  /** SefinNacional · GET /nfse/{chave} — consulta a NFS-e pela chave de acesso (50 dígitos). */
110
225
  export async function consultarNfse(chave, pfx, ambiente) {
111
226
  const base = ambiente ? resolveSefinBaseUrl(ambiente) : undefined;
112
- return parseJson(await sefinRequest({ method: 'GET', path: `/nfse/${chave}` }, pfx, base));
227
+ return parseJson(await sefinRequest({ method: 'GET', path: `/nfse/${chave}` }, pfx, { operation: 'consultar_nfse', ambiente, pathTemplate: '/nfse/{chave}' }, base));
113
228
  }
114
229
  /** SefinNacional · POST /nfse/{chave}/eventos — registra evento fiscal da NFS-e. */
115
230
  export async function enviarEvento(pedRegXmlGZipB64, pfx, chaveAcesso, ambiente) {
@@ -118,6 +233,6 @@ export async function enviarEvento(pedRegXmlGZipB64, pfx, chaveAcesso, ambiente)
118
233
  method: 'POST',
119
234
  path: `/nfse/${chaveAcesso}/eventos`,
120
235
  jsonBody: { pedRegXmlGZipB64 },
121
- }, pfx, base));
236
+ }, pfx, { operation: 'enviar_evento', ambiente, pathTemplate: '/nfse/{chave}/eventos' }, base));
122
237
  }
123
238
  //# sourceMappingURL=sefinClient.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sefinClient.js","sourceRoot":"","sources":["../sefinClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,YAAY,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAIlD,kFAAkF;AAClF,MAAM,wBAAwB,GAAG,MAAM,CAAC;AA2BxC;;;GAGG;AACH,SAAS,YAAY,CAAC,IAAiB,EAAE,GAAgB,EAAE,YAAqB;IAC9E,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,YAAY,IAAI,mBAAmB,EAAE,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IAC5E,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAElF,MAAM,OAAO,GAAoC;QAC/C,MAAM,EAAE,kBAAkB;KAC3B,CAAC;IACF,IAAI,OAAO,IAAI,IAAI,EAAE,CAAC;QACpB,OAAO,CAAC,cAAc,CAAC,GAAG,kBAAkB,CAAC;QAC7C,OAAO,CAAC,gBAAgB,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACzD,CAAC;IAED,MAAM,OAAO,GAAyB;QACpC,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,QAAQ,EAAE,GAAG,CAAC,QAAQ;QACtB,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,GAAG;Q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AAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAClE,OAAO,SAAS,CAAC,MAAM,YAAY,CACjC,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,KAAK,EAAE,EAAE,EACzC,GAAG,EACH,EAAE,SAAS,EAAE,gBAAgB,EAAE,QAAQ,EAAE,YAAY,EAAE,eAAe,EAAE,EACxE,IAAI,CACL,CAAC,CAAC;AACL,CAAC;AAED,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,gBAAwB,EACxB,GAAgB,EAChB,WAAmB,EACnB,QAAmB;IAEnB,MAAM,IAAI,GAAG,QAAQ,CAAC,CAAC,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAClE,OAAO,SAAS,CACd,MAAM,YAAY,CAChB;QACE,MAAM,EAAE,MAAM;QACd,IAAI,EAAE,SAAS,WAAW,UAAU;QACpC,QAAQ,EAAE,EAAE,gBAAgB,EAAE;KAC/B,EACD,GAAG,EACH,EAAE,SAAS,EAAE,eAAe,EAAE,QAAQ,EAAE,YAAY,EAAE,uBAAuB,EAAE,EAC/E,IAAI,CACL,CACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,205 @@
1
+ # Metricas da SEFIN
2
+
3
+ O SDK pode medir a latencia das chamadas mTLS feitas contra a SEFIN Nacional. Essas metricas ajudam a responder perguntas como:
4
+
5
+ - qual e o P99 de `POST /nfse` no ambiente restrito?
6
+ - as consultas por chave estao ficando lentas?
7
+ - quantas chamadas externas falharam no processo atual?
8
+ - a lentidao vem da SEFIN ou da minha API?
9
+
10
+ As metricas sao emitidas pelo SDK, mas nao sao enviadas para nenhum servico automaticamente. A aplicacao que usa o SDK decide se quer guardar em memoria, registrar em logs, exportar para Prometheus, enviar para Datadog/New Relic/Grafana, ou expor em um endpoint interno.
11
+
12
+ ## O que e medido
13
+
14
+ Cada chamada externa feita pelo `sefinClient.ts` pode emitir um evento com:
15
+
16
+ | Campo | Descricao |
17
+ |---|---|
18
+ | `operation` | Operacao logica do SDK. |
19
+ | `ambiente` | `restrita` ou `producao`, quando informado. |
20
+ | `method` | Metodo HTTP usado contra a SEFIN. |
21
+ | `pathTemplate` | Caminho sem dados sensiveis, por exemplo `/nfse/{chave}`. |
22
+ | `durationMs` | Tempo total do round-trip externo em milissegundos. |
23
+ | `status` | Status HTTP retornado pela SEFIN, quando houve resposta. |
24
+ | `success` | `true` para HTTP 2xx; `false` para HTTP nao 2xx, timeout ou erro de rede. |
25
+ | `errorName` | Nome do erro local, quando a chamada falha antes de uma resposta HTTP. |
26
+ | `errorMessage` | Mensagem do erro local, quando aplicavel. |
27
+
28
+ Operacoes emitidas:
29
+
30
+ | Operacao | Endpoint SEFIN |
31
+ |---|---|
32
+ | `transmitir_dps` | `POST /nfse` |
33
+ | `consultar_nfse` | `GET /nfse/{chave}` |
34
+ | `enviar_evento` | `POST /nfse/{chave}/eventos` |
35
+
36
+ ## O que nao e medido
37
+
38
+ Essas metricas nao medem a latencia total da sua API. Elas medem apenas a dependencia externa SEFIN.
39
+
40
+ Exemplo:
41
+
42
+ ```txt
43
+ Cliente -> sua API: 20ms
44
+ sua API -> SEFIN -> sua API: 4200ms
45
+ sua API -> banco/logs/outros: 80ms
46
+ latencia total da sua API: 4300ms
47
+ latencia SEFIN medida pelo SDK: 4200ms
48
+ ```
49
+
50
+ Tambem nao ha persistencia automatica. O agregador em memoria zera quando o processo Node reinicia.
51
+
52
+ ## Uso basico
53
+
54
+ Registre um observer uma vez na inicializacao da aplicacao, antes de fazer chamadas como `emitirNfse`, `consultarNfse` ou `enviarEvento`.
55
+
56
+ ```ts
57
+ import {
58
+ createSefinLatencyTracker,
59
+ setSefinRequestObserver,
60
+ } from '@useinvio/nfse-sdk';
61
+
62
+ export const sefinLatency = createSefinLatencyTracker({
63
+ maxSamplesPerSeries: 1000,
64
+ });
65
+
66
+ setSefinRequestObserver((metric) => {
67
+ sefinLatency.observe(metric);
68
+ });
69
+ ```
70
+
71
+ Depois, leia o snapshot onde fizer sentido para sua aplicacao:
72
+
73
+ ```ts
74
+ const snapshot = sefinLatency.snapshot();
75
+
76
+ console.log(snapshot.series);
77
+ ```
78
+
79
+ Exemplo de retorno:
80
+
81
+ ```ts
82
+ {
83
+ generatedAt: '2026-07-09T12:00:00.000Z',
84
+ series: [
85
+ {
86
+ operation: 'transmitir_dps',
87
+ ambiente: 'restrita',
88
+ count: 120,
89
+ successCount: 118,
90
+ errorCount: 2,
91
+ sampleCount: 120,
92
+ minMs: 180,
93
+ maxMs: 8100,
94
+ avgMs: 940.2,
95
+ p50Ms: 430,
96
+ p95Ms: 2200,
97
+ p99Ms: 5100
98
+ }
99
+ ]
100
+ }
101
+ ```
102
+
103
+ ## Como interpretar P99
104
+
105
+ `p99Ms` significa que 99% das chamadas observadas naquela serie foram mais rapidas ou iguais a esse valor.
106
+
107
+ Se `transmitir_dps` em `restrita` tem `p99Ms = 5100`, a leitura pratica e:
108
+
109
+ ```txt
110
+ 99% das transmissoes de DPS para a SEFIN restrita responderam em ate 5100ms.
111
+ ```
112
+
113
+ Um `p99Ms` alto com `p50Ms` baixo indica cauda longa: a maioria das chamadas e rapida, mas uma pequena parte fica muito lenta. Em integracoes fiscais isso costuma aparecer por fila, instabilidade, timeout, validacao pesada ou oscilacao da dependencia externa.
114
+
115
+ ## Series
116
+
117
+ O tracker agrega por:
118
+
119
+ ```txt
120
+ operation + ambiente
121
+ ```
122
+
123
+ Assim, `transmitir_dps` em `restrita` nao se mistura com `consultar_nfse` em `producao`.
124
+
125
+ ## Janela movel
126
+
127
+ `maxSamplesPerSeries` controla quantas duracoes recentes ficam guardadas por serie.
128
+
129
+ ```ts
130
+ const sefinLatency = createSefinLatencyTracker({
131
+ maxSamplesPerSeries: 5000,
132
+ });
133
+ ```
134
+
135
+ Com `5000`, cada combinacao `operation + ambiente` calcula os percentis usando no maximo as ultimas 5000 amostras daquela serie. O contador `count` continua acumulando o total observado desde o ultimo `reset`, mas `p50Ms`, `p95Ms`, `p99Ms`, `minMs`, `maxMs` e `avgMs` usam a janela de amostras mantida em memoria.
136
+
137
+ ## Logs estruturados
138
+
139
+ Voce pode registrar cada chamada em log e tambem alimentar o tracker:
140
+
141
+ ```ts
142
+ setSefinRequestObserver((metric) => {
143
+ sefinLatency.observe(metric);
144
+
145
+ logger.info({
146
+ event: 'sefin_request',
147
+ operation: metric.operation,
148
+ ambiente: metric.ambiente,
149
+ status: metric.status,
150
+ success: metric.success,
151
+ durationMs: metric.durationMs,
152
+ errorName: metric.errorName,
153
+ });
154
+ });
155
+ ```
156
+
157
+ Evite registrar payload fiscal, XML, certificado, chave privada ou dados sensiveis. O SDK ja usa `pathTemplate` para evitar colocar a chave de acesso no nome da serie.
158
+
159
+ ## Endpoint interno na sua API
160
+
161
+ Se quiser consultar essas metricas pela sua API, crie um endpoint protegido que retorne o snapshot:
162
+
163
+ ```ts
164
+ import { sefinLatency } from './observability/sefinMetrics.js';
165
+
166
+ app.get('/internal/metrics/sefin', async (_request, reply) => {
167
+ return reply.send(sefinLatency.snapshot());
168
+ });
169
+ ```
170
+
171
+ Esse endpoint deve ser interno ou protegido por autenticacao forte. As metricas nao carregam XML nem certificado, mas podem revelar volume, estabilidade e comportamento operacional do seu sistema.
172
+
173
+ ## Prometheus e outros coletores
174
+
175
+ O SDK nao depende de Prometheus. Para Prometheus, voce pode converter o snapshot para o formato esperado pela sua biblioteca de metricas.
176
+
177
+ Exemplo conceitual:
178
+
179
+ ```txt
180
+ sefin_request_duration_p99_ms{operation="transmitir_dps",ambiente="restrita"} 5100
181
+ sefin_request_success_total{operation="transmitir_dps",ambiente="restrita"} 118
182
+ sefin_request_error_total{operation="transmitir_dps",ambiente="restrita"} 2
183
+ ```
184
+
185
+ Se voce ja usa OpenTelemetry, Datadog, New Relic, Grafana Cloud ou outro coletor, use `setSefinRequestObserver` como ponto de saida e envie `durationMs`, `operation`, `ambiente`, `status` e `success`.
186
+
187
+ ## Reset
188
+
189
+ O tracker pode ser zerado:
190
+
191
+ ```ts
192
+ sefinLatency.reset();
193
+ ```
194
+
195
+ Isso remove as series e amostras em memoria. Use com cuidado em producao, porque o snapshot perde a janela atual de percentis.
196
+
197
+ ## Cuidados
198
+
199
+ - Registre o observer uma unica vez por processo.
200
+ - Nao crie um tracker novo a cada request HTTP.
201
+ - Use `maxSamplesPerSeries` conforme o volume esperado e a memoria disponivel.
202
+ - Lembre que processos diferentes tem snapshots diferentes. Em varios containers/replicas, cada processo enxerga apenas as chamadas que ele executou.
203
+ - Para historico entre deploys/restarts, envie as metricas para um sistema externo.
204
+ - Para saber os erros oficiais mais comuns da SEFIN, use a resposta de negocio e `extrairErros(body)` no seu fluxo. As metricas de latencia focam em tempo, status e sucesso/falha da chamada externa.
205
+
package/llms.txt ADDED
@@ -0,0 +1,80 @@
1
+ # @useinvio/nfse-sdk LLM Guide
2
+
3
+ This is a TypeScript SDK for Brazil's NFS-e Nacional (SEFIN). It handles the protocol layer for issuing and querying national service invoices: DPS JSON/XML generation, XMLDSIG signing, GZip/Base64 compression, mTLS transport, and structured SEFIN rejection extraction.
4
+
5
+ It is not a fiscal decision engine. Do not infer tax codes, accounting rules, tenant state, invoice numbering policy, or legal advice from this SDK.
6
+
7
+ ## Start Here
8
+
9
+ - `README.md`: primary Portuguese documentation and examples.
10
+ - `ENGLISH.md`: English documentation with the same conceptual flow.
11
+ - `docs/METRICS.md`: detailed SEFIN latency metrics guide, including observer setup, P99 interpretation, in-memory snapshots, and export guidance.
12
+ - `index.ts`: public exports. Treat this as the supported API surface.
13
+ - `examples/`: runnable usage examples.
14
+ - `JSON_MAPPING.md`: mapping notes for the declarative JSON input.
15
+ - `test/`: behavior examples and regression coverage.
16
+
17
+ ## Public Entry Points
18
+
19
+ - `NfseClient`: resource-oriented client. Configure certificate, environment, and defaults once, then use `client.invoices.create(...)`, `client.invoices.buildDpsJson(...)`, and `client.invoices.get(...)`.
20
+ - `emitirNfse(input, pfx, options?)`: issue an invoice from a DPS XML string or `DpsJsonRequest`.
21
+ - `buildDpsFromJson(input)`: build unsigned DPS XML from declarative JSON.
22
+ - `buildDpsId(prestador, nDPS, serie?)`: derive the 45-character DPS Id.
23
+ - `loadPfx(...)` and `loadPfxFromBuffer(...)`: extract key/certificate material from an A1/PFX certificate.
24
+ - `consultarNfse(...)`, `enviarEvento(...)`, `extrairErros(...)`: lower-level SEFIN helpers.
25
+ - `setSefinRequestObserver(...)` and `createSefinLatencyTracker(...)`: observe SEFIN round-trip latency and compute rolling `p50Ms`/`p95Ms`/`p99Ms` by operation/environment.
26
+ - `gzipBase64(...)`, `gunzipBase64(...)`, `signDps(...)`, `verifyDps(...)`: protocol utilities for custom flows.
27
+
28
+ ## File Map
29
+
30
+ - `client.ts`: friendly client API and default merging.
31
+ - `emissaoNota.ts`: central issue flow: prepare input, sign DPS, gzip/base64, transmit, unzip authorized XML, normalize errors.
32
+ - `dpsJson.ts`: JSON-to-DPS XML builder, XML escaping, DPS Id generation, value formatting, and XML block assembly.
33
+ - `fiscalValidation.ts`: structural and layout-oriented validation for the JSON input. This intentionally rejects unsupported or ambiguous fiscal shapes.
34
+ - `sefinClient.ts`: HTTPS mTLS requests to SEFIN, latency observation, response parsing, error normalization, invoice query, issue transport, and event transport.
35
+ - `config.ts`: SEFIN base URLs, environment names, and `tpAmb` mapping.
36
+ - `loadPfx.ts`: PFX/A1 certificate decoding with `node-forge`.
37
+ - `signXml.ts`: XMLDSIG signing and verification helpers.
38
+ - `gzipB64.ts`: GZip/Base64 helpers.
39
+
40
+ ## Core Data Shape
41
+
42
+ Declarative issuing uses `DpsJsonRequest`:
43
+
44
+ - `ambiente`: optional, `restrita` or `producao`; defaults to `restrita`.
45
+ - `prestador`: issuer profile such as `cnpj`, `cLocEmi`, `serie`, `opSimpNac`, and `regEspTrib`.
46
+ - `servico`: service defaults such as `cTribNac`, `xDescServ`, `cLocPrestacao`, and optional `cNBS`.
47
+ - `emissao`: invoice-specific data such as `nDPS`, dates, `valores`, optional parties, municipal/federal taxation blocks, and `totTrib`.
48
+
49
+ Keep values as strings when they represent fiscal codes, identifiers, decimals, or exact XML values. Many fields are numeric-looking but must preserve leading zeroes.
50
+
51
+ ## Important Invariants
52
+
53
+ - Node.js >= 20 and ESM are expected.
54
+ - Public imports should come from the package root (`index.ts` exports), not internal files, unless you are editing the SDK itself.
55
+ - `DEFAULT_AMBIENTE` is `restrita`; `NfseClient` also accepts `sandbox` and `production` aliases.
56
+ - `buildDpsFromJson` validates first via `validateDpsJsonRequest`.
57
+ - The SDK intentionally avoids silent fiscal defaults for required tax fields such as `tributacaoMunicipal` and `totTrib`.
58
+ - `emissao.totTrib` follows an `xs:choice`: provide exactly one branch among value totals, percentage totals, `indTotTrib`, or `pTotTribSN`.
59
+ - `buildDpsId` must return a 45-character Id beginning with `DPS`.
60
+ - `emitirNfse` signs the DPS before transport and throws `EmitirNotaError` when SEFIN rejects or no authorized XML is returned.
61
+ - `sefinClient.ts` uses PEM key/cert material for mTLS, not the raw PFX in the Node TLS handshake.
62
+ - SEFIN latency metrics are emitted for the external request only; keep them separate from API route latency when integrating observability.
63
+
64
+ ## Change Guidance for LLMs
65
+
66
+ - Preserve the public API names exported by `index.ts` unless the task explicitly asks for a breaking change.
67
+ - Prefer adding or adjusting focused tests in `test/` when changing XML generation, validation, signing, transport parsing, or client defaults.
68
+ - When adding support for a new NFS-e layout field, update the TypeScript interface, validation rules, builder output, docs/examples, and tests together.
69
+ - Do not add fiscal assumptions to make examples pass. Required fiscal choices should stay explicit in user input.
70
+ - Be careful with XML ordering. The generated order should follow the SEFIN schema, and tests may compare XML snippets.
71
+ - Do not hand-wave certificate handling. PFX content may arrive as a `Buffer` or base64 string.
72
+ - Network calls to SEFIN should stay isolated in `sefinClient.ts` so tests can mock transport boundaries.
73
+
74
+ ## Useful Commands
75
+
76
+ ```bash
77
+ npm run build
78
+ npm run typecheck
79
+ npm test
80
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@useinvio/nfse-sdk",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "TypeScript SDK for Brazil's national NFS-e: JSON to DPS/XML, XMLDSIG, GZip/Base64, mTLS and SEFIN errors.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -21,6 +21,7 @@
21
21
  "examples/README.md",
22
22
  "README.md",
23
23
  "JSON_MAPPING.md",
24
+ "llms.txt",
24
25
  "LICENSE"
25
26
  ],
26
27
  "scripts": {