@12-apps/fiscal 1.0.0 → 1.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 (140) hide show
  1. package/README.md +152 -7
  2. package/dist/chunk-27B4HNO6.js +574 -0
  3. package/dist/chunk-27B4HNO6.js.map +1 -0
  4. package/dist/chunk-3SDXLSG4.js +24 -0
  5. package/dist/chunk-3SDXLSG4.js.map +1 -0
  6. package/dist/chunk-ALABGVPO.js +247 -0
  7. package/dist/chunk-ALABGVPO.js.map +1 -0
  8. package/dist/chunk-FOFIN5M7.js +14 -0
  9. package/dist/chunk-FOFIN5M7.js.map +1 -0
  10. package/dist/chunk-HQ2NXSTX.js +85 -0
  11. package/dist/chunk-HQ2NXSTX.js.map +1 -0
  12. package/dist/chunk-PNTKG3DZ.js +47 -0
  13. package/dist/chunk-PNTKG3DZ.js.map +1 -0
  14. package/dist/chunk-RRFKYVLZ.js +192 -0
  15. package/dist/chunk-RRFKYVLZ.js.map +1 -0
  16. package/dist/chunk-V5ZQAAJT.js +210 -0
  17. package/dist/chunk-V5ZQAAJT.js.map +1 -0
  18. package/dist/chunk-X6MRDUYH.js +21 -0
  19. package/dist/chunk-X6MRDUYH.js.map +1 -0
  20. package/dist/chunk-XQGW5HUG.js +30 -0
  21. package/dist/chunk-XQGW5HUG.js.map +1 -0
  22. package/dist/context-ChnWR4Kb.d.ts +455 -0
  23. package/dist/danfe/en-US.d.ts +12 -0
  24. package/dist/danfe/en-US.js +51 -0
  25. package/dist/danfe/en-US.js.map +1 -0
  26. package/dist/danfe/index.d.ts +50 -0
  27. package/dist/danfe/index.js +18 -0
  28. package/dist/danfe/index.js.map +1 -0
  29. package/dist/danfe/pt-BR.d.ts +11 -0
  30. package/dist/danfe/pt-BR.js +51 -0
  31. package/dist/danfe/pt-BR.js.map +1 -0
  32. package/dist/documents/index.d.ts +169 -0
  33. package/dist/documents/index.js +1228 -0
  34. package/dist/documents/index.js.map +1 -0
  35. package/dist/engine/index.d.ts +3 -246
  36. package/dist/http.d.ts +73 -0
  37. package/dist/http.js +16 -0
  38. package/dist/http.js.map +1 -0
  39. package/dist/issuer/index.d.ts +43 -0
  40. package/dist/issuer/index.js +131 -0
  41. package/dist/issuer/index.js.map +1 -0
  42. package/dist/jobs.d.ts +74 -0
  43. package/dist/jobs.js +22 -0
  44. package/dist/jobs.js.map +1 -0
  45. package/dist/labels-BNvflT0h.d.ts +44 -0
  46. package/dist/manifest/index.d.ts +30 -16
  47. package/dist/manifest/index.js +11 -17
  48. package/dist/manifest/index.js.map +1 -1
  49. package/dist/manifest/server.d.ts +57 -0
  50. package/dist/manifest/server.js +25 -0
  51. package/dist/manifest/server.js.map +1 -0
  52. package/dist/notifications.d.ts +93 -0
  53. package/dist/notifications.js +41 -0
  54. package/dist/notifications.js.map +1 -0
  55. package/dist/port-DpRFK56U.d.ts +238 -0
  56. package/dist/sale/index.d.ts +243 -0
  57. package/dist/sale/index.js +1 -0
  58. package/dist/sale/index.js.map +1 -0
  59. package/dist/service-KTjH7AxW.d.ts +139 -0
  60. package/dist/sidecar/index.d.ts +216 -0
  61. package/dist/sidecar/index.js +8 -0
  62. package/dist/sidecar/index.js.map +1 -0
  63. package/dist/types-B1b8LIWX.d.ts +247 -0
  64. package/package.json +63 -5
  65. package/prisma/fiscal.prisma +158 -0
  66. package/prisma/migrations/20261113220000_fiscal_documents/migration.sql +201 -0
  67. package/sidecar/.dockerignore +5 -0
  68. package/sidecar/Dockerfile +68 -0
  69. package/sidecar/README.md +149 -0
  70. package/sidecar/composer.json +30 -0
  71. package/sidecar/composer.lock +2224 -0
  72. package/sidecar/docker/apache.conf +14 -0
  73. package/sidecar/docker/icp-brasil.pem +8031 -0
  74. package/sidecar/docker/mpm.conf +17 -0
  75. package/sidecar/docker/openssl.cnf +16 -0
  76. package/sidecar/docker/php.ini +19 -0
  77. package/sidecar/public/index.php +15 -0
  78. package/sidecar/schema/sale-for-document.schema.json +401 -0
  79. package/sidecar/src/ErrorClass.php +31 -0
  80. package/sidecar/src/Http/Request.php +48 -0
  81. package/sidecar/src/Http/Response.php +32 -0
  82. package/sidecar/src/Http/Router.php +59 -0
  83. package/sidecar/src/Kernel.php +99 -0
  84. package/sidecar/src/Module.php +31 -0
  85. package/sidecar/src/Nfe/Classifier.php +89 -0
  86. package/sidecar/src/Nfe/Credentials.php +52 -0
  87. package/sidecar/src/Nfe/DocumentMapper.php +383 -0
  88. package/sidecar/src/Nfe/DocumentSchema.php +39 -0
  89. package/sidecar/src/Nfe/Input.php +125 -0
  90. package/sidecar/src/Nfe/Model.php +17 -0
  91. package/sidecar/src/Nfe/NfeModule.php +62 -0
  92. package/sidecar/src/Nfe/NfeService.php +504 -0
  93. package/sidecar/src/Nfe/Sefaz.php +49 -0
  94. package/sidecar/src/Nfe/SefazReply.php +81 -0
  95. package/sidecar/src/Nfe/Transport/CurlTransport.php +198 -0
  96. package/sidecar/src/Nfe/Transport/SoapAdapter.php +57 -0
  97. package/sidecar/src/Nfe/Transport/Transport.php +20 -0
  98. package/sidecar/src/Nfe/Transport/TransportFailure.php +42 -0
  99. package/sidecar/src/RequestLog.php +54 -0
  100. package/sidecar/src/ServiceError.php +69 -0
  101. package/src/danfe/en-US.ts +53 -0
  102. package/src/danfe/index.ts +11 -0
  103. package/src/danfe/labels.ts +49 -0
  104. package/src/danfe/pt-BR.ts +52 -0
  105. package/src/danfe/render.ts +265 -0
  106. package/src/danfe/xml.ts +45 -0
  107. package/src/documents/context.ts +260 -0
  108. package/src/documents/errors.ts +41 -0
  109. package/src/documents/helpers.ts +128 -0
  110. package/src/documents/index.ts +39 -0
  111. package/src/documents/lines.ts +63 -0
  112. package/src/documents/machine-steps.ts +260 -0
  113. package/src/documents/machine.ts +128 -0
  114. package/src/documents/memory.ts +138 -0
  115. package/src/documents/nfe-proc.ts +51 -0
  116. package/src/documents/ports.ts +130 -0
  117. package/src/documents/profile-input.ts +168 -0
  118. package/src/documents/profile.ts +98 -0
  119. package/src/documents/service-profile.ts +104 -0
  120. package/src/documents/service.ts +296 -0
  121. package/src/documents/settle.ts +121 -0
  122. package/src/documents/signing.ts +61 -0
  123. package/src/documents/sql-rows.ts +180 -0
  124. package/src/documents/sql-store.ts +242 -0
  125. package/src/documents/sql.ts +18 -0
  126. package/src/documents/steps.ts +173 -0
  127. package/src/documents/tests/integration/pglite.ts +73 -0
  128. package/src/documents/types.ts +193 -0
  129. package/src/http.ts +264 -0
  130. package/src/issuer/index.ts +9 -0
  131. package/src/issuer/port.ts +109 -0
  132. package/src/issuer/sidecar.ts +171 -0
  133. package/src/jobs.ts +115 -0
  134. package/src/manifest/index.ts +25 -16
  135. package/src/manifest/server.ts +20 -0
  136. package/src/notifications.ts +120 -0
  137. package/src/sale/index.ts +8 -0
  138. package/src/sale/types.ts +292 -0
  139. package/src/sidecar/index.ts +9 -0
  140. package/src/sidecar/types.ts +243 -0
@@ -0,0 +1,139 @@
1
+ import { F as FiscalDocumentModel, h as FiscalDocument, d as IssuerFailure, i as FiscalDocumentEvent } from './port-DpRFK56U.js';
2
+ import { T as TaxRegime } from './types-B1b8LIWX.js';
3
+ import { IssuerTaxRegime, Address } from './sale/index.js';
4
+ import { SefazEnvironment, LookedUpDocument } from './sidecar/index.js';
5
+ import { f as DocumentPolicy, S as SigningIdentityKind, g as FiscalDocumentsConfig, C as Cipher, E as EmitterProfile, I as IssuingPoint } from './context-ChnWR4Kb.js';
6
+
7
+ /**
8
+ * Reading the emitter profile and the certificate upload off a request body:
9
+ * every field required (an absent value is `null`), unknown keys refused, and
10
+ * every refusal a {@link FiscalDocumentError} `INVALID_INPUT` naming the
11
+ * field — never its value, since the certificate upload carries secrets.
12
+ */
13
+
14
+ /** The profile fields a host writes; the secrets arrive through their own calls. */
15
+ interface EmitterProfileInput {
16
+ readonly cnpj: string;
17
+ readonly stateRegistration: string;
18
+ readonly municipalRegistration: string | null;
19
+ readonly cnae: string | null;
20
+ readonly legalName: string;
21
+ readonly tradeName: string | null;
22
+ readonly taxRegime: IssuerTaxRegime;
23
+ readonly regime: TaxRegime;
24
+ readonly regimeEffectiveFrom: string;
25
+ readonly restaurantRegime: boolean;
26
+ readonly address: Address & {
27
+ readonly postalCode: string;
28
+ };
29
+ readonly environment: SefazEnvironment;
30
+ readonly documentPolicy: DocumentPolicy;
31
+ readonly signingIdentity: SigningIdentityKind;
32
+ readonly cscId: string | null;
33
+ /** The CSC token in clear, encrypted on arrival; `null` keeps the stored one. */
34
+ readonly cscToken: string | null;
35
+ readonly consentRecordedAt: string | null;
36
+ }
37
+ interface CertificateUpload {
38
+ readonly pfxBase64: string;
39
+ readonly password: string;
40
+ }
41
+ interface IssuingPointInput {
42
+ readonly id: string;
43
+ readonly model: FiscalDocumentModel;
44
+ readonly onlineSeries: number;
45
+ readonly contingencySeries: number | null;
46
+ readonly firstOnlineNumber: number;
47
+ readonly firstContingencyNumber: number;
48
+ }
49
+ declare function parseProfileInput(value: unknown): EmitterProfileInput;
50
+ declare function parseCertificateUpload(value: unknown): CertificateUpload;
51
+ declare function parseIssuingPointInput(value: unknown): IssuingPointInput;
52
+
53
+ /**
54
+ * The profile half of the document service: the emitter profile, the
55
+ * certificate upload and the issuing points. A secret is encrypted through the
56
+ * host's cipher the moment it arrives, and only its ciphertext is stored.
57
+ */
58
+
59
+ /** What the host learns from an A1 without this package parsing PKCS#12. */
60
+ interface CertificateFacts {
61
+ /** `notAfter`, ISO 8601. */
62
+ readonly expiresAt: string;
63
+ }
64
+ interface FiscalDocumentsServiceConfig extends FiscalDocumentsConfig {
65
+ /** Encrypts the certificate, its password and the CSC on arrival. */
66
+ readonly cipher: Cipher;
67
+ /**
68
+ * Reads the expiry out of an uploaded A1; throws when the file does not
69
+ * open with the password. The host's: Node's crypto cannot open every A1
70
+ * (most issued before 2023 use RC2-40), and this package adds no parser.
71
+ */
72
+ readonly readCertificate: (certificate: CertificateUpload) => Promise<CertificateFacts>;
73
+ }
74
+
75
+ interface SweepReport {
76
+ readonly advanced: Array<{
77
+ readonly documentId: string;
78
+ readonly status: FiscalDocument["status"];
79
+ }>;
80
+ readonly failures: Array<{
81
+ readonly documentId: string;
82
+ readonly message: string;
83
+ }>;
84
+ }
85
+ interface IssueInput {
86
+ readonly ownerId: string;
87
+ readonly subjectId: string;
88
+ readonly issuingPointId: string;
89
+ readonly model: FiscalDocumentModel;
90
+ }
91
+ /** How long an NFC-e may wait in contingency before it must be transmitted (24 h); the warning goes out at 20 h. */
92
+ declare const CONTINGENCY_WARNING_AFTER_MS: number;
93
+ declare function createFiscalDocuments(config: FiscalDocumentsServiceConfig): {
94
+ getProfile: (ownerId: string) => Promise<EmitterProfile | null>;
95
+ saveProfile: (ownerId: string, input: EmitterProfileInput) => Promise<EmitterProfile>;
96
+ uploadCertificate: (ownerId: string, certificate: CertificateUpload) => Promise<EmitterProfile>;
97
+ listIssuingPoints: (ownerId: string) => Promise<IssuingPoint[]>;
98
+ createIssuingPoint: (ownerId: string, input: IssuingPointInput) => Promise<IssuingPoint>;
99
+ /** Issue the subject's document, or answer the live one it has. A rejection is final; anything SEFAZ may still answer is the sweep's. */
100
+ issue: (input: IssueInput) => Promise<FiscalDocument>;
101
+ issueOffline: (input: Omit<IssueInput, "model">) => Promise<FiscalDocument>;
102
+ resendContingency: (input: {
103
+ ownerId: string;
104
+ documentId: string;
105
+ }) => Promise<FiscalDocument>;
106
+ /** Cancel an authorised document. A refusal (late, say) answers the issuer's failure and changes nothing. */
107
+ cancel: (input: {
108
+ ownerId: string;
109
+ documentId: string;
110
+ reason: string;
111
+ }) => Promise<{
112
+ document: FiscalDocument;
113
+ failure: IssuerFailure | null;
114
+ }>;
115
+ /** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
116
+ lookup: (input: {
117
+ ownerId: string;
118
+ documentId: string;
119
+ }) => Promise<{
120
+ document: FiscalDocument;
121
+ answer: LookedUpDocument | null;
122
+ failure: IssuerFailure | null;
123
+ }>;
124
+ /** A person takes a document back from `attention`; the sweep tries it again. */
125
+ release(input: {
126
+ ownerId: string;
127
+ documentId: string;
128
+ }): Promise<FiscalDocument>;
129
+ getDocument: (ownerId: string, documentId: string) => Promise<FiscalDocument>;
130
+ listBySubject: (ownerId: string, subjectId: string, model: FiscalDocumentModel) => Promise<FiscalDocument[]>;
131
+ listEvents(ownerId: string, documentId: string): Promise<FiscalDocumentEvent[]>;
132
+ /** One pass of the retry sweep: PENDING/SUBMITTED documents and owed numbers whose next attempt has come. */
133
+ sweep: (limit: number) => Promise<SweepReport>;
134
+ /** One pass of the contingency transmission, then the 20-hour deadline warnings. */
135
+ transmitContingency(limit: number): Promise<SweepReport>;
136
+ };
137
+ type FiscalDocuments = ReturnType<typeof createFiscalDocuments>;
138
+
139
+ export { CONTINGENCY_WARNING_AFTER_MS as C, type EmitterProfileInput as E, type FiscalDocuments as F, type IssueInput as I, type SweepReport as S, type CertificateFacts as a, type CertificateUpload as b, type FiscalDocumentsServiceConfig as c, type IssuingPointInput as d, createFiscalDocuments as e, parseIssuingPointInput as f, parseProfileInput as g, parseCertificateUpload as p };
@@ -0,0 +1,216 @@
1
+ import { SaleForDocument } from '../sale/index.js';
2
+
3
+ /**
4
+ * The wire contract of the fiscal service (`sidecar/` in this package): a
5
+ * stateless HTTP door in front of sped-nfe. JSON in, JSON out.
6
+ *
7
+ * Stateless means every call carries what it needs: the signing certificate
8
+ * (an A1 `.pfx` as base64 and its password) and, for an NFC-e, the CSC. The
9
+ * service keeps nothing between calls, writes nothing to disk and never logs
10
+ * any of the three.
11
+ */
12
+
13
+ /** The path segment of a document model: `nfe` is model 55, `nfce` model 65. */
14
+ type DocumentModelPath = "nfe" | "nfce";
15
+ /** The SEFAZ environment (`tpAmb` 2 and 1). */
16
+ type SefazEnvironment = "homologacao" | "producao";
17
+ /** The A1 certificate, per call. */
18
+ interface SigningCertificate {
19
+ /** The `.pfx` (PKCS#12) bytes, base64. */
20
+ readonly pfxBase64: string;
21
+ readonly password: string;
22
+ }
23
+ /** The NFC-e's Código de Segurança do Contribuinte and its id. */
24
+ interface Csc {
25
+ readonly id: string;
26
+ readonly token: string;
27
+ }
28
+ interface Authenticated {
29
+ readonly environment: SefazEnvironment;
30
+ readonly certificate: SigningCertificate;
31
+ }
32
+ /**
33
+ * `POST /<model>/issue`: builds, signs and transmits. `csc` is required for
34
+ * `nfce` and refused for `nfe`.
35
+ */
36
+ interface IssueRequest extends Authenticated {
37
+ readonly csc: Csc | null;
38
+ readonly document: SaleForDocument;
39
+ }
40
+ /** Why and since when the caixa issues offline (`dhCont`, `xJust`). */
41
+ interface ContingencyEntry {
42
+ /** ISO 8601 with the UTC offset. */
43
+ readonly since: string;
44
+ /** 15–256 characters. */
45
+ readonly reason: string;
46
+ }
47
+ /** `POST /nfce/sign-contingency`: builds and signs with `tpEmis = 9`; does NOT transmit. */
48
+ interface SignContingencyRequest extends IssueRequest {
49
+ readonly contingency: ContingencyEntry;
50
+ }
51
+ /** `POST /<model>/transmit`: an already signed XML (from `/nfce/sign-contingency`, say). */
52
+ interface TransmitRequest extends Authenticated {
53
+ readonly signedXml: string;
54
+ }
55
+ /** `POST /<model>/cancel`: the UF and the issuer come from the access key. */
56
+ interface CancelRequest extends Authenticated {
57
+ readonly accessKey: string;
58
+ /** The authorisation protocol (`nProt`). */
59
+ readonly protocol: string;
60
+ /** 15–255 characters. */
61
+ readonly reason: string;
62
+ }
63
+ /**
64
+ * `POST /nfce/cancel-substitution`: the NFC-e "cancelamento por substituição"
65
+ * (event 110112) — an online NFC-e found authorised after its sale was issued
66
+ * again in contingency, cancelled naming the substitute. Answers as `/cancel`.
67
+ */
68
+ interface CancelBySubstitutionRequest extends CancelRequest {
69
+ /** The contingency document that replaced it (`chNFeRef`). */
70
+ readonly substituteAccessKey: string;
71
+ }
72
+ /** `POST /<model>/lookup`. */
73
+ interface LookupRequest extends Authenticated {
74
+ readonly accessKey: string;
75
+ }
76
+ /** `POST /inutilize`: voids a range of unused numbers. */
77
+ interface InutilizeRequest extends Authenticated {
78
+ readonly model: DocumentModelPath;
79
+ readonly uf: string;
80
+ readonly cnpj: string;
81
+ /** The year of the numbers, four digits. */
82
+ readonly year: number;
83
+ readonly series: number;
84
+ readonly from: number;
85
+ readonly to: number;
86
+ /** 15–255 characters. */
87
+ readonly reason: string;
88
+ }
89
+ /** What SEFAZ answered, as the service read it. */
90
+ interface SefazAnswer {
91
+ /** `cStat`. */
92
+ readonly statusCode: string;
93
+ /** `xMotivo`. */
94
+ readonly statusReason: string;
95
+ /** The SOAP body SEFAZ returned, verbatim. */
96
+ readonly sefazReply: string;
97
+ }
98
+ /**
99
+ * `/issue` and `/transmit`: SEFAZ's final answer on the document.
100
+ *
101
+ * - `AUTHORIZED` (100, 120, 150).
102
+ * - `DENIED` (110, 301, 302, 303): a denial of use. The number is SPENT and
103
+ * the denial is kept like an authorisation (its `authorizedXml` carries the
104
+ * denial protocol); it is not a rejection, which leaves the number free.
105
+ *
106
+ * A retried call answers the same: SEFAZ's "already authorised" (204) and
107
+ * "already denied" (205), and a request sent with no answer, are settled by
108
+ * looking the key up, so a retry never turns an authorised document into an error.
109
+ */
110
+ interface IssuedDocument extends SefazAnswer {
111
+ readonly status: "AUTHORIZED" | "DENIED";
112
+ readonly accessKey: string;
113
+ readonly protocol: string;
114
+ /** `dhRecbto` of the protocol. */
115
+ readonly authorizedAt: string;
116
+ readonly signedXml: string;
117
+ /** The `nfeProc`: the signed XML with its protocol (of authorisation or of denial), what is stored. */
118
+ readonly authorizedXml: string;
119
+ }
120
+ /** `/nfce/sign-contingency`. */
121
+ interface ContingencySignedDocument {
122
+ readonly status: "SIGNED";
123
+ readonly accessKey: string;
124
+ /** Carries `tpEmis = 9` and the QR code; transmit it later through `/nfce/transmit`. */
125
+ readonly signedXml: string;
126
+ }
127
+ /**
128
+ * `/cancel`. A retried cancel (SEFAZ's 218 "already cancelled" or 573
129
+ * "duplicate event", or a cancel sent with no answer) is settled by looking
130
+ * the key up, and answers CANCELLED with what the lookup carries: the event's
131
+ * protocol and XML when SEFAZ returns them, `null` when it does not.
132
+ */
133
+ interface CancelledDocument extends SefazAnswer {
134
+ readonly status: "CANCELLED";
135
+ readonly accessKey: string;
136
+ /** The event's protocol. */
137
+ readonly protocol: string | null;
138
+ readonly registeredAt: string | null;
139
+ /** The `procEventoNFe`. */
140
+ readonly eventXml: string | null;
141
+ }
142
+ /** `/lookup`: what SEFAZ knows of the key. `NOT_FOUND` is an answer, not an error. */
143
+ interface LookedUpDocument extends SefazAnswer {
144
+ readonly status: "AUTHORIZED" | "CANCELLED" | "DENIED" | "NOT_FOUND";
145
+ readonly accessKey: string;
146
+ readonly protocol: string | null;
147
+ }
148
+ /**
149
+ * `/inutilize`. A retried inutilização (563, "a request for the same range
150
+ * already exists") answers INUTILIZED too, with `protocol` and
151
+ * `inutilizationXml` `null`: the range is void at SEFAZ, and SEFAZ offers no
152
+ * query that would return the first protocol.
153
+ */
154
+ interface InutilizedRange extends SefazAnswer {
155
+ readonly status: "INUTILIZED";
156
+ readonly protocol: string | null;
157
+ readonly registeredAt: string | null;
158
+ /** The signed request with its reply (`procInutNFe`). */
159
+ readonly inutilizationXml: string | null;
160
+ }
161
+ /**
162
+ * How a failed call is classified — the issuer port's own classes:
163
+ *
164
+ * - `REJECTED`: SEFAZ refused the document or the event; `code` is its `cStat`.
165
+ * The number is NOT spent (a denial is not an error: it answers `DENIED`).
166
+ * - `RETRYABLE`: try the same call again later. When `outcomeUnknown` is true
167
+ * the request went out and neither it nor the lookup that would settle it
168
+ * was answered: look the key up before sending it again.
169
+ * - `CONTINGENCY`: SEFAZ is unavailable. For an NFC-e being issued, nothing
170
+ * reached SEFAZ (or the lookup after an unanswered request could not reach
171
+ * it): go offline through `/nfce/sign-contingency`. For an NF-e (model 55)
172
+ * the service has no offline path (no SVC, no EPEC): treat it as RETRYABLE.
173
+ * - `AUTH`: the certificate is unreadable, the password wrong, the certificate
174
+ * expired, or SEFAZ refused it.
175
+ * - `INVALID`: the request itself is malformed (the schema, a missing CSC, an
176
+ * XML the layout refuses, a document the layout version cannot express).
177
+ * Fix the input; never retry it as is.
178
+ * - `INTERNAL`: a defect of the service, or a 4xx other than 403/408/429 from
179
+ * the verified SEFAZ host (a wrong web-service address). A retry would only repeat it.
180
+ */
181
+ type SidecarErrorClass = "REJECTED" | "RETRYABLE" | "CONTINGENCY" | "AUTH" | "INVALID" | "INTERNAL";
182
+ declare const SIDECAR_ERROR_CLASSES: readonly SidecarErrorClass[];
183
+ /** The body of every non-2xx answer. */
184
+ interface SidecarErrorBody {
185
+ readonly error: {
186
+ readonly class: SidecarErrorClass;
187
+ /**
188
+ * The SEFAZ `cStat` when SEFAZ answered (always for `REJECTED`); for
189
+ * `INVALID`, a named code where one applies (`NT_2026_008_NOT_SUPPORTED`:
190
+ * a document issued on or after 2027-01-01, which needs NT 2026.008's
191
+ * `vProdLiq`); `null` otherwise.
192
+ */
193
+ readonly code: string | null;
194
+ readonly message: string;
195
+ /** Per-field problems of an `INVALID` request. */
196
+ readonly details: readonly string[];
197
+ /** When the call got as far as building and signing: keep it, the key is now spoken for. */
198
+ readonly accessKey: string | null;
199
+ readonly signedXml: string | null;
200
+ readonly sefazReply: string | null;
201
+ /** The request went out and its outcome is still unknown: look the key up before sending it again. */
202
+ readonly outcomeUnknown: boolean;
203
+ };
204
+ }
205
+ /** `GET /health`. */
206
+ interface SidecarHealth {
207
+ readonly status: "ok";
208
+ /** The libraries the service runs, by name, with the version installed. */
209
+ readonly libraries: Readonly<Record<string, string>>;
210
+ /** The schema package the NF-e layout is validated against. */
211
+ readonly nfeSchemas: string;
212
+ /** Whether SEFAZ's server certificate is verified; `false` only with `FISCAL_SEFAZ_TLS_VERIFY=off`. */
213
+ readonly sefazTlsVerify: boolean;
214
+ }
215
+
216
+ export { type CancelBySubstitutionRequest, type CancelRequest, type CancelledDocument, type ContingencyEntry, type ContingencySignedDocument, type Csc, type DocumentModelPath, type InutilizeRequest, type InutilizedRange, type IssueRequest, type IssuedDocument, type LookedUpDocument, type LookupRequest, SIDECAR_ERROR_CLASSES, type SefazAnswer, type SefazEnvironment, type SidecarErrorBody, type SidecarErrorClass, type SidecarHealth, type SignContingencyRequest, type SigningCertificate, type TransmitRequest };
@@ -0,0 +1,8 @@
1
+ import {
2
+ SIDECAR_ERROR_CLASSES
3
+ } from "../chunk-FOFIN5M7.js";
4
+ import "../chunk-7QVYU63E.js";
5
+ export {
6
+ SIDECAR_ERROR_CLASSES
7
+ };
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,247 @@
1
+ /**
2
+ * The engine's vocabulary. Money is integer CENTS, rates are integer BASIS
3
+ * POINTS (1 bp = 0.01%), dates are ISO calendar days (`YYYY-MM-DD`) in the
4
+ * seller's own clock — the fato gerador is the local day of the supply, and the
5
+ * host, which owns the clock, says which day that was.
6
+ *
7
+ * Nothing here has a default. Every field is required, and a value the engine
8
+ * cannot read is refused with a `FiscalEngineError`, never guessed.
9
+ */
10
+ /** An ISO calendar day, `YYYY-MM-DD`. */
11
+ type IsoDate = string;
12
+ /**
13
+ * The seller's IBS/CBS regime (LC 214/2025 art. 41).
14
+ *
15
+ * - `REGIME_REGULAR` — Lucro Presumido/Real: the full breakdown, "por fora".
16
+ * - `SIMPLES_IBS_CBS_REGULAR` — the Simples híbrido (art. 41 §3): a Simples
17
+ * optant that applies the regime regular to IBS/CBS; full breakdown.
18
+ * - `SIMPLES` — inside the DAS (art. 41 §2): an `INFORMATIVE` breakdown, with
19
+ * the figures a regime store would show and no amount charged "por fora".
20
+ * - `MEI` and `NAO_CONTRIBUINTE` — no IBS/CBS on the document: zero.
21
+ */
22
+ type TaxRegime = "REGIME_REGULAR" | "SIMPLES_IBS_CBS_REGULAR" | "SIMPLES" | "MEI" | "NAO_CONTRIBUINTE";
23
+ /** The special regimes the engine applies. */
24
+ type RegimeEspecifico = "BARES_RESTAURANTES";
25
+ /** What the treatment of the seller's regime is on the date of the supply. */
26
+ type TaxTreatment = "FULL" | "INFORMATIVE" | "NONE";
27
+ /** The two codes an NF-e item carries for its IBS/CBS classification. */
28
+ interface TaxClassCode {
29
+ readonly cClassTrib: string;
30
+ readonly cstIbsCbs: string;
31
+ }
32
+ /**
33
+ * A line's tax class, as the host classified the item. `cClassTrib` and
34
+ * `cstIbsCbs` are carried opaque into the snapshot (the classification table
35
+ * is the host's data, Informe Técnico 2025.002).
36
+ *
37
+ * `regimeEspecifico: "BARES_RESTAURANTES"` marks prepared food and
38
+ * non-alcoholic drinks prepared on the premises (art. 273 caput, §1; the
39
+ * official class is 200047). Alcohol, even prepared on the premises, and food
40
+ * or drink bought from third parties and resold as-is are OUT (art. 273 §2)
41
+ * and must carry `null`.
42
+ */
43
+ interface TaxClass extends TaxClassCode {
44
+ readonly regimeEspecifico: RegimeEspecifico | null;
45
+ /** The class's own rate reduction (a listed-food reduction, say), 0–10000. */
46
+ readonly reductionBp: number;
47
+ }
48
+ /** One priced line of the supply. */
49
+ interface TaxLineInput {
50
+ /** The host's id, echoed on the output line; unique within the input. */
51
+ readonly id: string;
52
+ /**
53
+ * What the line costs the buyer, every unit, AFTER its allocated discount
54
+ * (an unconditional discount is outside the base, art. 12 §2 III). It is
55
+ * the price the shopper sees, so in a period whose table says
56
+ * `taxInsidePrice` the IBS/CBS are INSIDE it and the engine takes them out;
57
+ * otherwise it is the base itself and the tax is computed on top of it.
58
+ */
59
+ readonly valueCents: number;
60
+ /** Units (`qCom`): positive, at most four decimals (weighed goods). */
61
+ readonly quantity: number;
62
+ /**
63
+ * Whether the line is food or drink — what the gorjeta's 15% ceiling is
64
+ * measured against (art. 274 par. único I). A delivery fee is not.
65
+ */
66
+ readonly foodAndDrink: boolean;
67
+ readonly taxClass: TaxClass;
68
+ }
69
+ /** Who sells, and under which regime since when. */
70
+ interface SellerProfile {
71
+ readonly regime: TaxRegime;
72
+ /** The first day `regime` applies. A supply before it is refused. */
73
+ readonly regimeEffectiveFrom: IsoDate;
74
+ /** Whether the bares e restaurantes regime (arts. 273–276) applies. */
75
+ readonly restaurantRegime: boolean;
76
+ }
77
+ /** The service charge (taxa de serviço / gorjeta) on the supply. */
78
+ interface ServiceChargeInput {
79
+ /** Echoed as the service-charge line's id; unique within the input. */
80
+ readonly id: string;
81
+ readonly amountCents: number;
82
+ /** Whether the charge is passed in full to the staff. */
83
+ readonly passedToStaff: boolean;
84
+ /** The class the WHOLE charge is taxed at when it is not excluded. */
85
+ readonly taxClass: TaxClass;
86
+ }
87
+ /** What a digital platform retained for delivery and intermediation. */
88
+ interface RetainedIntermediationInput {
89
+ /** Echoed as the excluded line's id; unique within the input. */
90
+ readonly id: string;
91
+ /** Never passed to the restaurant; NOT included in any line's value. */
92
+ readonly amountCents: number;
93
+ }
94
+ /**
95
+ * The amounts the restaurant regime keeps out of the base (art. 274 par.
96
+ * único), each segregated on the document as its own item (RCBS art. 399 §2:
97
+ * without the segregation the base is the full value, §4).
98
+ */
99
+ interface TaxExclusions {
100
+ /**
101
+ * Excluded (its own line, the table's gorjeta class) only when the store is
102
+ * in the restaurant regime, the charge is passed in full to the staff AND it
103
+ * is at most 15% of the food and drink. Otherwise the whole charge is a
104
+ * taxed line under its own class — never a partial exclusion.
105
+ */
106
+ readonly serviceCharge: ServiceChargeInput | null;
107
+ /** Restaurant regime only (art. 274 par. único II); refused elsewhere. */
108
+ readonly retainedIntermediation: RetainedIntermediationInput | null;
109
+ }
110
+ /** The IBS share of one sphere in one period: the reference and the overrides. */
111
+ interface IbsSphereRates {
112
+ /** The reference rate, which applies wherever no own rate is listed. */
113
+ readonly referenceBp: number;
114
+ }
115
+ interface IbsUfRates extends IbsSphereRates {
116
+ /** State rates keyed by the 2-digit IBGE state code. */
117
+ readonly byUf: Readonly<Record<string, number>>;
118
+ }
119
+ interface IbsMunRates extends IbsSphereRates {
120
+ /** Municipal rates keyed by the 7-digit IBGE municipality code. */
121
+ readonly byMunicipality: Readonly<Record<string, number>>;
122
+ }
123
+ /** One stretch of time with one set of rates. */
124
+ interface RatePeriod {
125
+ readonly from: IsoDate;
126
+ /** Inclusive; `null` is open-ended. */
127
+ readonly to: IsoDate | null;
128
+ /** `ESTIMATE` stamps every result computed on it `provisional`. */
129
+ readonly status: "LAW" | "ESTIMATE";
130
+ readonly source: string;
131
+ /** The test year: highlighted, payment waived (art. 348 §1). */
132
+ readonly informative: boolean;
133
+ /** `false` in 2026: the test rates are not applied to Simples optants (art. 348 III "c"). */
134
+ readonly appliesToSimplesNacional: boolean;
135
+ /**
136
+ * Whether the IBS/CBS sit INSIDE the item's value on the document (they
137
+ * compose `vProd` and the price without tax travels in `vProdLiq`) — from
138
+ * 2027 by the NF-e layout. When true, a line's `valueCents` is the
139
+ * tax-inclusive price.
140
+ */
141
+ readonly taxInsidePrice: boolean;
142
+ readonly cbsBp: number;
143
+ readonly ibsUf: IbsUfRates;
144
+ readonly ibsMun: IbsMunRates;
145
+ }
146
+ /** A versioned rate table: DATA, loaded by the host, stamped on every result. */
147
+ interface RateTables {
148
+ readonly version: string;
149
+ readonly notes?: readonly string[];
150
+ /** The gorjeta's ceiling as a share of food and drink: 1500 (art. 274 par. único I). */
151
+ readonly gorjetaCapBp: number;
152
+ readonly gorjetaCapSource?: string;
153
+ /** The classes the excluded items are segregated under (410019, 410020). */
154
+ readonly exclusionClasses: {
155
+ readonly GORJETA: TaxClassCode;
156
+ readonly INTERMEDIATION: TaxClassCode;
157
+ readonly source?: string;
158
+ };
159
+ readonly specialRegimes: Readonly<Record<RegimeEspecifico, {
160
+ readonly reductionBp: number;
161
+ readonly source: string;
162
+ }>>;
163
+ readonly periods: readonly RatePeriod[];
164
+ }
165
+ /** Everything one computation needs. */
166
+ interface TaxInput {
167
+ readonly lines: readonly TaxLineInput[];
168
+ readonly seller: SellerProfile;
169
+ /**
170
+ * The 7-digit IBGE code of the place the IBS goes to: the establishment,
171
+ * or for a delivered good the place of delivery (art. 11 I).
172
+ */
173
+ readonly destinationIbge: string;
174
+ readonly exclusions: TaxExclusions;
175
+ readonly tables: RateTables;
176
+ /** The day of the supply; the rate is the rate of that day. */
177
+ readonly supplyDate: IsoDate;
178
+ }
179
+ /** Where an output line came from. */
180
+ type LineSource = "LINE" | "SERVICE_CHARGE" | "GORJETA_EXCLUDED" | "INTERMEDIATION_EXCLUDED";
181
+ /** The per-tax figures of one line. Rates are nominal; `reductionBp` applies to all three. */
182
+ interface LineFigures {
183
+ readonly reductionBp: number;
184
+ readonly cbsRateBp: number;
185
+ readonly cbsCents: number;
186
+ readonly ibsUfRateBp: number;
187
+ readonly ibsUfCents: number;
188
+ readonly ibsMunRateBp: number;
189
+ readonly ibsMunCents: number;
190
+ }
191
+ /** One output line — one NF-e item. */
192
+ interface LineTax extends LineFigures {
193
+ readonly lineId: string;
194
+ readonly source: LineSource;
195
+ readonly quantity: number;
196
+ /** The value as given (`vProd`). */
197
+ readonly valueCents: number;
198
+ /** The base the taxes are computed on (`vBC`): 0 on an excluded line. */
199
+ readonly taxBaseCents: number;
200
+ /** CBS + IBS-UF + IBS-Mun of the line. */
201
+ readonly taxCents: number;
202
+ /**
203
+ * The value without tax (`vProdLiq` = value − tax) in a `taxInsidePrice`
204
+ * period; `null` when the tax is not inside the value.
205
+ */
206
+ readonly netValueCents: number | null;
207
+ /**
208
+ * The unit value without tax (`vUnComLiq`), in reais with ten decimals as
209
+ * the layout writes it, within ±0,01 of `vProdLiq / qCom` (rule I11c-20);
210
+ * `null` when `netValueCents` is.
211
+ */
212
+ readonly netUnitValue: string | null;
213
+ /** The class snapshot (the table's exclusion class on an excluded line). */
214
+ readonly taxClass: TaxClass;
215
+ }
216
+ /** The breakdown of one supply. Every order figure is the sum of its rounded lines. */
217
+ interface TaxBreakdown {
218
+ readonly lines: readonly LineTax[];
219
+ readonly valueCents: number;
220
+ readonly taxBaseCents: number;
221
+ readonly cbsCents: number;
222
+ readonly ibsUfCents: number;
223
+ readonly ibsMunCents: number;
224
+ readonly ibsCents: number;
225
+ readonly totalTaxCents: number;
226
+ /** Σ `netValueCents` (`vProdLiqTot`), or `null` when the tax is not inside the values. */
227
+ readonly netValueCents: number | null;
228
+ readonly gorjetaExcludedCents: number;
229
+ readonly intermediationExcludedCents: number;
230
+ readonly regime: TaxRegime;
231
+ readonly treatment: TaxTreatment;
232
+ /**
233
+ * True when the figures are shown but not charged "por fora": the test year
234
+ * (2026), or a Simples store inside the DAS. False for a `NONE` treatment,
235
+ * which shows nothing.
236
+ */
237
+ readonly informative: boolean;
238
+ /** True when the period's figures are estimates, not law. */
239
+ readonly provisional: boolean;
240
+ /** Whether the line values were taken as tax-inclusive. */
241
+ readonly taxInsidePrice: boolean;
242
+ readonly supplyDate: IsoDate;
243
+ readonly destinationIbge: string;
244
+ readonly tablesVersion: string;
245
+ }
246
+
247
+ export type { IbsMunRates as I, LineFigures as L, RatePeriod as R, SellerProfile as S, TaxRegime as T, TaxBreakdown as a, TaxInput as b, RateTables as c, IbsSphereRates as d, IbsUfRates as e, IsoDate as f, LineSource as g, LineTax as h, RegimeEspecifico as i, RetainedIntermediationInput as j, ServiceChargeInput as k, TaxClass as l, TaxClassCode as m, TaxExclusions as n, TaxLineInput as o, TaxTreatment as p };