@useinvio/nfse-sdk 2.2.0 → 3.1.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.
Files changed (66) hide show
  1. package/JSON_MAPPING.md +30 -17
  2. package/README.md +145 -67
  3. package/dist/agent.d.ts +86 -0
  4. package/dist/agent.js +235 -0
  5. package/dist/agent.js.map +1 -0
  6. package/dist/certificate.d.ts +96 -0
  7. package/dist/certificate.js +218 -0
  8. package/dist/certificate.js.map +1 -0
  9. package/dist/certificateValidation.d.ts +12 -5
  10. package/dist/certificateValidation.js +25 -9
  11. package/dist/certificateValidation.js.map +1 -1
  12. package/dist/client.d.ts +8 -3
  13. package/dist/client.js +8 -7
  14. package/dist/client.js.map +1 -1
  15. package/dist/decimal.d.ts +7 -0
  16. package/dist/decimal.js +24 -0
  17. package/dist/decimal.js.map +1 -0
  18. package/dist/dpsJson.js +15 -45
  19. package/dist/dpsJson.js.map +1 -1
  20. package/dist/dpsJsonSchema.d.ts +17 -0
  21. package/dist/dpsJsonSchema.js +184 -0
  22. package/dist/dpsJsonSchema.js.map +1 -0
  23. package/dist/dpsNormalization.d.ts +10 -0
  24. package/dist/dpsNormalization.js +85 -0
  25. package/dist/dpsNormalization.js.map +1 -0
  26. package/dist/emissaoNota.d.ts +4 -4
  27. package/dist/emissaoNota.js +27 -8
  28. package/dist/emissaoNota.js.map +1 -1
  29. package/dist/fiscalDomains.d.ts +22 -0
  30. package/dist/fiscalDomains.js +99 -0
  31. package/dist/fiscalDomains.js.map +1 -0
  32. package/dist/fiscalValidation.d.ts +1 -0
  33. package/dist/fiscalValidation.js +119 -88
  34. package/dist/fiscalValidation.js.map +1 -1
  35. package/dist/index.d.ts +9 -4
  36. package/dist/index.js +5 -3
  37. package/dist/index.js.map +1 -1
  38. package/dist/jsonSchemaCheck.d.ts +12 -0
  39. package/dist/jsonSchemaCheck.js +70 -0
  40. package/dist/jsonSchemaCheck.js.map +1 -0
  41. package/dist/loadPfx.d.ts +2 -0
  42. package/dist/loadPfx.js +2 -1
  43. package/dist/loadPfx.js.map +1 -1
  44. package/dist/sefinClient.d.ts +10 -4
  45. package/dist/sefinClient.js +22 -4
  46. package/dist/sefinClient.js.map +1 -1
  47. package/dist/signXml.d.ts +3 -3
  48. package/dist/signXml.js +8 -6
  49. package/dist/signXml.js.map +1 -1
  50. package/dist/xmlInspection.d.ts +6 -0
  51. package/dist/xmlInspection.js +62 -0
  52. package/dist/xmlInspection.js.map +1 -0
  53. package/dist/xsdValidation.d.ts +17 -5
  54. package/dist/xsdValidation.js +75 -67
  55. package/dist/xsdValidation.js.map +1 -1
  56. package/docs/CORRECOES_EMISSAO.md +55 -0
  57. package/docs/FISCAL_MATRIX.md +11 -0
  58. package/docs/REGRAS_NEGOCIO_EMISSAO.md +317 -0
  59. package/examples/README.md +4 -1
  60. package/examples/client-resource.ts +8 -44
  61. package/examples/emit-homologation.ts +4 -40
  62. package/examples/generate-dps-xml.ts +3 -40
  63. package/examples/handle-errors.ts +6 -5
  64. package/examples/payloads.ts +36 -0
  65. package/llms.txt +22 -7
  66. package/package.json +9 -4
package/llms.txt CHANGED
@@ -20,10 +20,13 @@ It is not a fiscal decision engine. Do not infer tax codes, accounting rules, te
20
20
  - `emitirNfse(input, pfx, options?)`: issue an invoice from a DPS XML string or `DpsJsonRequest`.
21
21
  - `buildDpsFromJson(input)`: build unsigned DPS XML from declarative JSON.
22
22
  - `buildDpsId(prestador, nDPS, serie?)`: derive the 45-character DPS Id.
23
- - `loadPfx(...)` and `loadPfxFromBuffer(...)`: extract key/certificate material from an A1/PFX certificate.
23
+ - `NfseCertificate`: opaque A1 certificate for signing and mTLS (`fromEnv`, `fromFile`, `fromBase64`, `fromPfx`, `fromPem`). Exposes only metadata (CNPJ/CPF, validity, fingerprint); the private key lives outside the object and never appears in logs or JSON. Env convention: `NFSE_CERT_PATH` or `NFSE_CERT_BASE64`, plus `NFSE_CERT_PASSWORD` or `NFSE_CERT_PASSWORD_FILE`.
24
+ - `loadPfx(...)` and `loadPfxFromBuffer(...)`: legacy loaders that return the key as PEM; prefer `NfseCertificate`.
24
25
  - `consultarNfse(...)`, `enviarEvento(...)`, `extrairErros(...)`: lower-level SEFIN helpers.
25
26
  - `setSefinRequestObserver(...)` and `createSefinLatencyTracker(...)`: observe SEFIN round-trip latency when `NFSE_SEFIN_LATENCY_METRICS` is enabled; percentiles require `includePercentiles: true`.
26
27
  - `gzipBase64(...)`, `gunzipBase64(...)`, `signDps(...)`, `verifyDps(...)`: protocol utilities for custom flows.
28
+ - `DPS_JSON_REQUEST_SCHEMA`: JSON Schema 2020-12 for the canonical `DpsJsonRequest` (formats and code domains; cross-field rules stay in `validateDpsJsonRequest`).
29
+ - `@useinvio/nfse-sdk/agent`: framework-neutral agent/MCP tools (`validate_dps`, `build_dps_xml`, `get_nfse`) and `toAgentIssues(error)`. Certificate and environment come from the host context, never from tool input.
27
30
 
28
31
  ## File Map
29
32
 
@@ -33,9 +36,15 @@ It is not a fiscal decision engine. Do not infer tax codes, accounting rules, te
33
36
  - `fiscalValidation.ts`: structural and layout-oriented validation for the JSON input. This intentionally rejects unsupported or ambiguous fiscal shapes.
34
37
  - `sefinClient.ts`: HTTPS mTLS requests to SEFIN, latency observation, response parsing, error normalization, invoice query, issue transport, and event transport.
35
38
  - `config.ts`: SEFIN base URLs, environment names, and `tpAmb` mapping.
36
- - `loadPfx.ts`: PFX/A1 certificate decoding with `node-forge`.
39
+ - `certificate.ts`: `NfseCertificate`, ICP-Brasil CNPJ/CPF extraction, env loading, per-certificate mTLS agent, and the internal `resolveCredentials` used by signing and transport.
40
+ - `loadPfx.ts`: PFX/A1 certificate decoding with `node-forge` (shared parser plus legacy loaders).
41
+ - `xsdValidation.ts`: in-process XSD validation with libxml2 compiled to WebAssembly; schemas compiled once per process.
37
42
  - `signXml.ts`: XMLDSIG signing and verification helpers.
38
43
  - `gzipB64.ts`: GZip/Base64 helpers.
44
+ - `fiscalDomains.ts`: code domains shared by the validator and the JSON Schema.
45
+ - `dpsJsonSchema.ts`: JSON Schema for `DpsJsonRequest`; `satisfies` checks fail the build when a type gains a field the schema does not describe.
46
+ - `jsonSchemaCheck.ts`: internal validator for the portable keyword subset the schema may use.
47
+ - `agent.ts`: agent tool definitions, unified `NfseAgentIssue` shape, and error mapping.
39
48
 
40
49
  ## Core Data Shape
41
50
 
@@ -55,20 +64,26 @@ Keep values as strings when they represent fiscal codes, identifiers, decimals,
55
64
  - `DEFAULT_AMBIENTE` is `restrita`; `NfseClient` also accepts `sandbox` and `production` aliases.
56
65
  - `buildDpsFromJson` validates first via `validateDpsJsonRequest`.
57
66
  - 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`.
67
+ - The JSON validator restricts `totTrib` by regime: non-Simples requires all three percentage totals; MEI requires `indTotTrib="0"`; ME/EPP requires `pTotTribSN`. Value totals remain typed but are rejected by the current regime matrix.
59
68
  - `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.
69
+ - `emitirNfse` checks certificate validity before signing and again before transmission. Holder matching is an explicit `assertCertificateForProvider` call, not an automatic requirement.
70
+ - JSON environment precedence is options > request > restricted; external XML derives its environment from `tpAmb` and rejects explicit conflicts.
71
+ - `client.invoices.get(key, { ambiente })` supports an explicit environment; otherwise defaults.ambiente > constructor. It does not remember the last emission.
72
+ - Currency discrepancies are warnings; explicit values retain priority. Service amounts must remain positive after rounding; all foreign amounts are serialized with two decimals.
73
+ - `validateDpsJsonRequest` returns independent normalized data, errors in `issues`, and non-blocking `warnings`.
74
+ - `EmitirNotaError` covers SEFIN rejection and incomplete/invalid HTTP 2xx authorization responses, including missing/invalid/conflicting 50-digit access keys. Reconcile before retrying; the SDK never retries automatically.
75
+ - `sefinClient.ts` uses a per-certificate `https.Agent` (from `NfseCertificate`) or PEM key/cert (legacy `PfxMaterial`) for mTLS, never the raw PFX in the Node TLS handshake. Access keys are validated as 50 digits before any request (`ChaveAcessoInvalidaError`).
76
+ - XSD validation needs no system `xmllint`; it runs in WebAssembly. `XmllintUnavailableError` is a deprecated alias of `XsdEngineUnavailableError`.
62
77
  - SEFIN latency metrics are off by default, enabled through `NFSE_SEFIN_LATENCY_METRICS`, and emitted for the external request only; keep them separate from API route latency when integrating observability.
63
78
 
64
79
  ## Change Guidance for LLMs
65
80
 
66
81
  - Preserve the public API names exported by `index.ts` unless the task explicitly asks for a breaking change.
67
82
  - 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.
83
+ - When adding support for a new NFS-e layout field, update the TypeScript interface, validation rules, JSON Schema (`dpsJsonSchema.ts`), builder output, docs/examples, and tests together.
69
84
  - Do not add fiscal assumptions to make examples pass. Required fiscal choices should stay explicit in user input.
70
85
  - 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.
86
+ - Do not hand-wave certificate handling. Accept `CertificateInput` (`NfseCertificate | PfxMaterial`) and go through `resolveCredentials`; never log, serialize, or return key material, the PFX bytes, or the password.
72
87
  - Network calls to SEFIN should stay isolated in `sefinClient.ts` so tests can mock transport boundaries.
73
88
 
74
89
  ## Useful Commands
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@useinvio/nfse-sdk",
3
- "version": "2.2.0",
3
+ "version": "3.1.0",
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",
@@ -10,6 +10,10 @@
10
10
  "types": "./dist/index.d.ts",
11
11
  "import": "./dist/index.js"
12
12
  },
13
+ "./agent": {
14
+ "types": "./dist/agent.d.ts",
15
+ "import": "./dist/agent.js"
16
+ },
13
17
  "./package.json": "./package.json"
14
18
  },
15
19
  "files": [
@@ -62,9 +66,10 @@
62
66
  "access": "public"
63
67
  },
64
68
  "dependencies": {
65
- "@xmldom/xmldom": "^0.8.13",
66
- "node-forge": "^1.3.1",
67
- "xml-crypto": "^6.0.0"
69
+ "@xmldom/xmldom": "^0.8.15",
70
+ "libxml2-wasm": "^0.7.2",
71
+ "node-forge": "^1.4.3",
72
+ "xml-crypto": "^6.4.0"
68
73
  },
69
74
  "devDependencies": {
70
75
  "@types/node": "^22.13.14",