@12-apps/fiscal 0.0.0-stage → 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 (155) hide show
  1. package/README.md +269 -2
  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-7QVYU63E.js +7 -0
  7. package/dist/chunk-7QVYU63E.js.map +1 -0
  8. package/dist/chunk-ALABGVPO.js +247 -0
  9. package/dist/chunk-ALABGVPO.js.map +1 -0
  10. package/dist/chunk-FOFIN5M7.js +14 -0
  11. package/dist/chunk-FOFIN5M7.js.map +1 -0
  12. package/dist/chunk-HQ2NXSTX.js +85 -0
  13. package/dist/chunk-HQ2NXSTX.js.map +1 -0
  14. package/dist/chunk-PNTKG3DZ.js +47 -0
  15. package/dist/chunk-PNTKG3DZ.js.map +1 -0
  16. package/dist/chunk-RRFKYVLZ.js +192 -0
  17. package/dist/chunk-RRFKYVLZ.js.map +1 -0
  18. package/dist/chunk-V5ZQAAJT.js +210 -0
  19. package/dist/chunk-V5ZQAAJT.js.map +1 -0
  20. package/dist/chunk-X6MRDUYH.js +21 -0
  21. package/dist/chunk-X6MRDUYH.js.map +1 -0
  22. package/dist/chunk-XQGW5HUG.js +30 -0
  23. package/dist/chunk-XQGW5HUG.js.map +1 -0
  24. package/dist/context-ChnWR4Kb.d.ts +455 -0
  25. package/dist/danfe/en-US.d.ts +12 -0
  26. package/dist/danfe/en-US.js +51 -0
  27. package/dist/danfe/en-US.js.map +1 -0
  28. package/dist/danfe/index.d.ts +50 -0
  29. package/dist/danfe/index.js +18 -0
  30. package/dist/danfe/index.js.map +1 -0
  31. package/dist/danfe/pt-BR.d.ts +11 -0
  32. package/dist/danfe/pt-BR.js +51 -0
  33. package/dist/danfe/pt-BR.js.map +1 -0
  34. package/dist/documents/index.d.ts +169 -0
  35. package/dist/documents/index.js +1228 -0
  36. package/dist/documents/index.js.map +1 -0
  37. package/dist/engine/index.d.ts +118 -0
  38. package/dist/engine/index.js +591 -0
  39. package/dist/engine/index.js.map +1 -0
  40. package/dist/http.d.ts +73 -0
  41. package/dist/http.js +16 -0
  42. package/dist/http.js.map +1 -0
  43. package/dist/issuer/index.d.ts +43 -0
  44. package/dist/issuer/index.js +131 -0
  45. package/dist/issuer/index.js.map +1 -0
  46. package/dist/jobs.d.ts +74 -0
  47. package/dist/jobs.js +22 -0
  48. package/dist/jobs.js.map +1 -0
  49. package/dist/labels-BNvflT0h.d.ts +44 -0
  50. package/dist/manifest/index.d.ts +97 -0
  51. package/dist/manifest/index.js +27 -0
  52. package/dist/manifest/index.js.map +1 -0
  53. package/dist/manifest/server.d.ts +57 -0
  54. package/dist/manifest/server.js +25 -0
  55. package/dist/manifest/server.js.map +1 -0
  56. package/dist/notifications.d.ts +93 -0
  57. package/dist/notifications.js +41 -0
  58. package/dist/notifications.js.map +1 -0
  59. package/dist/port-DpRFK56U.d.ts +238 -0
  60. package/dist/sale/index.d.ts +243 -0
  61. package/dist/sale/index.js +1 -0
  62. package/dist/sale/index.js.map +1 -0
  63. package/dist/service-KTjH7AxW.d.ts +139 -0
  64. package/dist/sidecar/index.d.ts +216 -0
  65. package/dist/sidecar/index.js +8 -0
  66. package/dist/sidecar/index.js.map +1 -0
  67. package/dist/types-B1b8LIWX.d.ts +247 -0
  68. package/package.json +126 -4
  69. package/prisma/fiscal.prisma +158 -0
  70. package/prisma/migrations/20261113220000_fiscal_documents/migration.sql +201 -0
  71. package/sidecar/.dockerignore +5 -0
  72. package/sidecar/Dockerfile +68 -0
  73. package/sidecar/README.md +149 -0
  74. package/sidecar/composer.json +30 -0
  75. package/sidecar/composer.lock +2224 -0
  76. package/sidecar/docker/apache.conf +14 -0
  77. package/sidecar/docker/icp-brasil.pem +8031 -0
  78. package/sidecar/docker/mpm.conf +17 -0
  79. package/sidecar/docker/openssl.cnf +16 -0
  80. package/sidecar/docker/php.ini +19 -0
  81. package/sidecar/public/index.php +15 -0
  82. package/sidecar/schema/sale-for-document.schema.json +401 -0
  83. package/sidecar/src/ErrorClass.php +31 -0
  84. package/sidecar/src/Http/Request.php +48 -0
  85. package/sidecar/src/Http/Response.php +32 -0
  86. package/sidecar/src/Http/Router.php +59 -0
  87. package/sidecar/src/Kernel.php +99 -0
  88. package/sidecar/src/Module.php +31 -0
  89. package/sidecar/src/Nfe/Classifier.php +89 -0
  90. package/sidecar/src/Nfe/Credentials.php +52 -0
  91. package/sidecar/src/Nfe/DocumentMapper.php +383 -0
  92. package/sidecar/src/Nfe/DocumentSchema.php +39 -0
  93. package/sidecar/src/Nfe/Input.php +125 -0
  94. package/sidecar/src/Nfe/Model.php +17 -0
  95. package/sidecar/src/Nfe/NfeModule.php +62 -0
  96. package/sidecar/src/Nfe/NfeService.php +504 -0
  97. package/sidecar/src/Nfe/Sefaz.php +49 -0
  98. package/sidecar/src/Nfe/SefazReply.php +81 -0
  99. package/sidecar/src/Nfe/Transport/CurlTransport.php +198 -0
  100. package/sidecar/src/Nfe/Transport/SoapAdapter.php +57 -0
  101. package/sidecar/src/Nfe/Transport/Transport.php +20 -0
  102. package/sidecar/src/Nfe/Transport/TransportFailure.php +42 -0
  103. package/sidecar/src/RequestLog.php +54 -0
  104. package/sidecar/src/ServiceError.php +69 -0
  105. package/src/danfe/en-US.ts +53 -0
  106. package/src/danfe/index.ts +11 -0
  107. package/src/danfe/labels.ts +49 -0
  108. package/src/danfe/pt-BR.ts +52 -0
  109. package/src/danfe/render.ts +265 -0
  110. package/src/danfe/xml.ts +45 -0
  111. package/src/documents/context.ts +260 -0
  112. package/src/documents/errors.ts +41 -0
  113. package/src/documents/helpers.ts +128 -0
  114. package/src/documents/index.ts +39 -0
  115. package/src/documents/lines.ts +63 -0
  116. package/src/documents/machine-steps.ts +260 -0
  117. package/src/documents/machine.ts +128 -0
  118. package/src/documents/memory.ts +138 -0
  119. package/src/documents/nfe-proc.ts +51 -0
  120. package/src/documents/ports.ts +130 -0
  121. package/src/documents/profile-input.ts +168 -0
  122. package/src/documents/profile.ts +98 -0
  123. package/src/documents/service-profile.ts +104 -0
  124. package/src/documents/service.ts +296 -0
  125. package/src/documents/settle.ts +121 -0
  126. package/src/documents/signing.ts +61 -0
  127. package/src/documents/sql-rows.ts +180 -0
  128. package/src/documents/sql-store.ts +242 -0
  129. package/src/documents/sql.ts +18 -0
  130. package/src/documents/steps.ts +173 -0
  131. package/src/documents/tests/integration/pglite.ts +73 -0
  132. package/src/documents/types.ts +193 -0
  133. package/src/engine/compare.ts +68 -0
  134. package/src/engine/compute.ts +40 -0
  135. package/src/engine/errors.ts +28 -0
  136. package/src/engine/index.ts +20 -0
  137. package/src/engine/oracle.ts +81 -0
  138. package/src/engine/plan.ts +268 -0
  139. package/src/engine/rounding.ts +81 -0
  140. package/src/engine/types.ts +270 -0
  141. package/src/engine/validate.ts +222 -0
  142. package/src/http.ts +264 -0
  143. package/src/issuer/index.ts +9 -0
  144. package/src/issuer/port.ts +109 -0
  145. package/src/issuer/sidecar.ts +171 -0
  146. package/src/jobs.ts +115 -0
  147. package/src/manifest/index.ts +46 -0
  148. package/src/manifest/permissions.ts +28 -0
  149. package/src/manifest/server.ts +20 -0
  150. package/src/notifications.ts +120 -0
  151. package/src/sale/index.ts +8 -0
  152. package/src/sale/types.ts +292 -0
  153. package/src/sidecar/index.ts +9 -0
  154. package/src/sidecar/types.ts +243 -0
  155. package/tables/ibs-cbs-2026-11-13.json +156 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/engine/errors.ts","../../src/engine/rounding.ts","../../src/engine/validate.ts","../../src/engine/plan.ts","../../src/engine/compute.ts","../../src/engine/oracle.ts","../../src/engine/compare.ts"],"sourcesContent":["/**\n * Every refusal the engine makes. A refusal is a THROW, on purpose: the\n * engine has no fallback for an input it cannot read, and a figure computed\n * from a guess would be printed on a fiscal document as a confession of the\n * tax due (LC 214/2025 art. 60 §1).\n */\n\nexport type FiscalEngineErrorCode =\n /** A field is missing, out of range or of the wrong shape. */\n | \"INVALID_INPUT\"\n /** The rate table is malformed: a bad rate, a bad date, overlapping periods. */\n | \"INVALID_TABLES\"\n /** No period of the table covers the date of the supply. */\n | \"NO_RATE_PERIOD\"\n /** The supply precedes the seller's `regimeEffectiveFrom`. */\n | \"REGIME_NOT_IN_EFFECT\"\n /** The official calculator answered something that is not integer cents and basis points. */\n | \"INVALID_ORACLE_ANSWER\";\n\nexport class FiscalEngineError extends Error {\n readonly code: FiscalEngineErrorCode;\n\n constructor(code: FiscalEngineErrorCode, message: string) {\n super(`[fiscal/engine] ${code}: ${message}`);\n this.name = \"FiscalEngineError\";\n this.code = code;\n }\n}\n","/**\n * The NF-e per-item rounding: each tax of each item is rounded to whole cents\n * on its own, and a document total is the sum of its rounded items. The mode\n * is HALF-EVEN (ABNT NBR 5891), the official calculator's: R$ 5,00 × 0,9% =\n * 0,045 → 0,04 and R$ 25,00 × 0,9% = 0,225 → 0,22, recorded from the\n * calculator in `__tests__/fixtures/calculator/half-cent.*`. Never a floor.\n *\n * The reduction applies to the RATE (the layout's `pAliqEfet = pAliq × (1 −\n * pRedAliq)`), and the product is computed exactly in integers: cents × bp ×\n * bp needs up to 10^17 for a large order, past `Number.MAX_SAFE_INTEGER`, so\n * the arithmetic is BigInt and nothing is rounded before the end.\n */\n\nconst BP = 10_000n;\n/** The denominator of an effective rate: bp × bp. */\nconst RATE_SCALE = BP * BP;\n\n/** round_half_even(numerator / denominator) for a non-negative numerator. */\nfunction roundHalfEven(numerator: bigint, denominator: bigint): bigint {\n const quotient = numerator / denominator;\n const twice = (numerator - quotient * denominator) * 2n;\n if (twice > denominator) return quotient + 1n;\n if (twice < denominator) return quotient;\n return quotient % 2n === 0n ? quotient : quotient + 1n;\n}\n\n/** The effective rate's numerator over `RATE_SCALE`: rateBp × (10⁴ − reductionBp). */\nexport function effectiveRate(rateBp: number, reductionBp: number): bigint {\n return BigInt(rateBp) * (BP - BigInt(reductionBp));\n}\n\n/** round_half_even(baseCents × rateBp/10⁴ × (1 − reductionBp/10⁴)), in cents. */\nexport function roundTaxCents(baseCents: number, rateBp: number, reductionBp: number): number {\n return Number(roundHalfEven(BigInt(baseCents) * effectiveRate(rateBp, reductionBp), RATE_SCALE));\n}\n\nfunction taxesOn(base: bigint, rates: readonly bigint[]): bigint[] {\n return rates.map((rate) => roundHalfEven(base * rate, RATE_SCALE));\n}\n\n/**\n * Take the taxes OUT of a tax-inclusive price. The base (`vBC`) is the\n * largest whole-cent amount whose own rounded taxes, added back, do not pass\n * the price — the exact `price / (1 + Σ rates)` or the cent below it. The\n * taxes are each rounded on that base (so `vBC × pAliqEfet` holds per tax),\n * and the net value (`vProdLiq`) is the\n * price less them, so `net + Σ taxes = price` to the cent.\n */\nexport function splitTaxInclusivePrice(\n priceCents: number,\n rates: readonly bigint[],\n): { baseCents: number; taxCents: number[]; netCents: number } {\n const price = BigInt(priceCents);\n const total = rates.reduce((sum, rate) => sum + rate, 0n);\n // Three cents above the exact base: f(b) = b + Σ round(b × r) ≥ b(1 + r) − 1.5,\n // so from there f(b) is past the price and the walk down meets the answer.\n let base = (price * RATE_SCALE) / (RATE_SCALE + total) + 3n;\n let taxes = taxesOn(base, rates);\n while (base > 0n && base + taxes.reduce((sum, tax) => sum + tax, 0n) > price) {\n base -= 1n;\n taxes = taxesOn(base, rates);\n }\n const taxCents = taxes.map(Number);\n return { baseCents: Number(base), taxCents, netCents: priceCents - taxCents.reduce((sum, tax) => sum + tax, 0) };\n}\n\n/** Quantity with at most four decimals (`qCom`), as ten-thousandths. */\nfunction quantityInTenThousandths(quantity: number): bigint {\n return BigInt(Math.round(quantity * 10_000));\n}\n\n/**\n * `vUnComLiq`: the net value per unit, in reais with ten decimals, rounded\n * half-even — far inside the ±0,01 the layout allows between it × `qCom` and\n * `vProdLiq` (rule I11c-20).\n */\nexport function netUnitValue(netCents: number, quantity: number): string {\n const scaled = roundHalfEven(BigInt(netCents) * 10n ** 12n, quantityInTenThousandths(quantity));\n const digits = scaled.toString().padStart(11, \"0\");\n return `${digits.slice(0, -10)}.${digits.slice(-10)}`;\n}\n","/**\n * Input and table validation. Every check names the field it refused, and\n * every shape is checked before it is read, so a malformed input — a missing\n * object, an `undefined` where `null` is required, a `null` line — is a\n * `FiscalEngineError`, never a TypeError and never a NaN on a document.\n */\n\nimport { FiscalEngineError } from \"./errors\";\nimport type { FiscalEngineErrorCode } from \"./errors\";\nimport type { IsoDate, RatePeriod, RateTables, TaxClass, TaxClassCode, TaxInput, TaxLineInput, TaxRegime } from \"./types\";\n\nconst ISO_DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst IBGE_MUNICIPALITY = /^\\d{7}$/;\nconst IBGE_UF = /^\\d{2}$/;\nconst REGIMES: readonly TaxRegime[] = [\"REGIME_REGULAR\", \"SIMPLES_IBS_CBS_REGULAR\", \"SIMPLES\", \"MEI\", \"NAO_CONTRIBUINTE\"];\n\nfunction refuse(code: FiscalEngineErrorCode, message: string): never {\n throw new FiscalEngineError(code, message);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** A real calendar day in `YYYY-MM-DD` — `2026-02-30` is not one. */\nfunction isIsoDate(value: unknown): value is IsoDate {\n if (typeof value !== \"string\") return false;\n const match = ISO_DATE.exec(value);\n if (!match) return false;\n const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];\n const date = new Date(Date.UTC(year, month - 1, day));\n return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;\n}\n\nfunction isCents(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction isBp(value: unknown): value is number {\n return isCents(value) && value <= 10_000;\n}\n\nfunction isCode(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\";\n}\n\n/** Positive, finite, and at most four decimals — what `qCom` can carry. */\nfunction isQuantity(value: unknown): value is number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) return false;\n const tenThousandths = Math.round(value * 10_000);\n return tenThousandths > 0 && Number.isSafeInteger(tenThousandths) && Math.abs(tenThousandths / 10_000 - value) < 1e-9;\n}\n\nfunction assertInput(ok: boolean, what: string): void {\n if (!ok) refuse(\"INVALID_INPUT\", what);\n}\n\nfunction assertTable(ok: boolean, what: string): void {\n if (!ok) refuse(\"INVALID_TABLES\", what);\n}\n\nfunction assertTaxClass(taxClass: unknown, where: string): asserts taxClass is TaxClass {\n assertInput(isRecord(taxClass), `${where} must be an object`);\n const value = taxClass as Record<string, unknown>;\n assertInput(isCode(value.cClassTrib), `${where}.cClassTrib must be a code`);\n assertInput(isCode(value.cstIbsCbs), `${where}.cstIbsCbs must be a code`);\n assertInput(\n value.regimeEspecifico === null || value.regimeEspecifico === \"BARES_RESTAURANTES\",\n `${where}.regimeEspecifico must be \"BARES_RESTAURANTES\" or null`,\n );\n assertInput(isBp(value.reductionBp), `${where}.reductionBp must be integer basis points in 0..10000`);\n}\n\nfunction assertLine(line: unknown, index: number): asserts line is TaxLineInput {\n const where = `lines[${index}]`;\n assertInput(isRecord(line), `${where} must be an object`);\n const value = line as Record<string, unknown>;\n assertInput(isCode(value.id), `${where}.id must be a non-empty string`);\n assertInput(isCents(value.valueCents), `${where}.valueCents must be non-negative integer cents`);\n assertInput(isQuantity(value.quantity), `${where}.quantity must be positive, with at most four decimals`);\n assertInput(typeof value.foodAndDrink === \"boolean\", `${where}.foodAndDrink must be a boolean`);\n assertTaxClass(value.taxClass, `${where}.taxClass`);\n}\n\nfunction assertServiceCharge(charge: unknown): void {\n if (charge === null) return;\n assertInput(isRecord(charge), \"exclusions.serviceCharge must be an object or null\");\n const value = charge as Record<string, unknown>;\n assertInput(isCode(value.id), \"exclusions.serviceCharge.id must be a non-empty string\");\n assertInput(isCents(value.amountCents), \"exclusions.serviceCharge.amountCents must be non-negative integer cents\");\n assertInput(typeof value.passedToStaff === \"boolean\", \"exclusions.serviceCharge.passedToStaff must be a boolean\");\n assertTaxClass(value.taxClass, \"exclusions.serviceCharge.taxClass\");\n}\n\nfunction assertIntermediation(retained: unknown): void {\n if (retained === null) return;\n assertInput(isRecord(retained), \"exclusions.retainedIntermediation must be an object or null\");\n const value = retained as Record<string, unknown>;\n assertInput(isCode(value.id), \"exclusions.retainedIntermediation.id must be a non-empty string\");\n assertInput(isCents(value.amountCents), \"exclusions.retainedIntermediation.amountCents must be non-negative integer cents\");\n}\n\nfunction assertExclusions(exclusions: unknown): void {\n assertInput(isRecord(exclusions), \"exclusions must be an object\");\n const value = exclusions as Record<string, unknown>;\n assertInput(\"serviceCharge\" in value, \"exclusions.serviceCharge must be given (null when there is none)\");\n assertInput(\"retainedIntermediation\" in value, \"exclusions.retainedIntermediation must be given (null when there is none)\");\n assertServiceCharge(value.serviceCharge);\n assertIntermediation(value.retainedIntermediation);\n}\n\nfunction assertUniqueIds(input: TaxInput): void {\n const ids = input.lines.map((line) => line.id);\n if (input.exclusions.serviceCharge) ids.push(input.exclusions.serviceCharge.id);\n if (input.exclusions.retainedIntermediation) ids.push(input.exclusions.retainedIntermediation.id);\n const seen = new Set<string>();\n for (const id of ids) {\n assertInput(!seen.has(id), `line id \"${id}\" is used twice`);\n seen.add(id);\n }\n}\n\nfunction assertSeller(seller: unknown): void {\n assertInput(isRecord(seller), \"seller must be an object\");\n const value = seller as Record<string, unknown>;\n assertInput(REGIMES.includes(value.regime as TaxRegime), `seller.regime must be one of ${REGIMES.join(\", \")}`);\n assertInput(isIsoDate(value.regimeEffectiveFrom), \"seller.regimeEffectiveFrom must be a YYYY-MM-DD day\");\n assertInput(typeof value.restaurantRegime === \"boolean\", \"seller.restaurantRegime must be a boolean\");\n}\n\n/** Refuse anything the engine cannot compute from. */\nexport function assertTaxInput(input: unknown): asserts input is TaxInput {\n assertInput(isRecord(input), \"the input must be an object\");\n const value = input as Record<string, unknown>;\n assertInput(Array.isArray(value.lines) && value.lines.length > 0, \"lines must hold at least one line\");\n (value.lines as unknown[]).forEach(assertLine);\n assertSeller(value.seller);\n assertInput(\n typeof value.destinationIbge === \"string\" && IBGE_MUNICIPALITY.test(value.destinationIbge),\n \"destinationIbge must be a 7-digit IBGE municipality code\",\n );\n assertExclusions(value.exclusions);\n assertUniqueIds(input as TaxInput);\n assertInput(isIsoDate(value.supplyDate), \"supplyDate must be a YYYY-MM-DD day\");\n assertRateTables(value.tables);\n}\n\nfunction assertRateMap(map: unknown, keyShape: RegExp, where: string): void {\n assertTable(isRecord(map), `${where} must be an object`);\n for (const [key, bp] of Object.entries(map as Record<string, unknown>)) {\n assertTable(keyShape.test(key), `${where} key \"${key}\" is not an IBGE code of the right length`);\n assertTable(isBp(bp), `${where}[\"${key}\"] must be integer basis points in 0..10000`);\n }\n}\n\nfunction assertSphere(sphere: unknown, mapKey: \"byUf\" | \"byMunicipality\", keyShape: RegExp, where: string): void {\n assertTable(isRecord(sphere), `${where} must be an object`);\n const value = sphere as Record<string, unknown>;\n assertTable(isBp(value.referenceBp), `${where}.referenceBp must be integer basis points in 0..10000`);\n assertRateMap(value[mapKey], keyShape, `${where}.${mapKey}`);\n}\n\nfunction assertPeriodFlags(value: Record<string, unknown>, where: string): void {\n assertTable(value.status === \"LAW\" || value.status === \"ESTIMATE\", `${where}.status must be LAW or ESTIMATE`);\n for (const flag of [\"informative\", \"appliesToSimplesNacional\", \"taxInsidePrice\"] as const) {\n assertTable(typeof value[flag] === \"boolean\", `${where}.${flag} must be a boolean`);\n }\n}\n\nfunction assertPeriod(period: unknown, index: number): asserts period is RatePeriod {\n const where = `periods[${index}]`;\n assertTable(isRecord(period), `${where} must be an object`);\n const value = period as Record<string, unknown>;\n assertTable(isIsoDate(value.from), `${where}.from must be a YYYY-MM-DD day`);\n assertTable(\n value.to === null || (isIsoDate(value.to) && value.to >= (value.from as string)),\n `${where}.to must be null or a day on or after from`,\n );\n assertPeriodFlags(value, where);\n assertTable(isBp(value.cbsBp), `${where}.cbsBp must be integer basis points in 0..10000`);\n assertSphere(value.ibsUf, \"byUf\", IBGE_UF, `${where}.ibsUf`);\n assertSphere(value.ibsMun, \"byMunicipality\", IBGE_MUNICIPALITY, `${where}.ibsMun`);\n}\n\nfunction assertClassCode(code: unknown, where: string): asserts code is TaxClassCode {\n assertTable(isRecord(code), `${where} must be an object`);\n const value = code as Record<string, unknown>;\n assertTable(isCode(value.cClassTrib) && isCode(value.cstIbsCbs), `${where} must carry cClassTrib and cstIbsCbs`);\n}\n\nfunction assertTableHeader(value: Record<string, unknown>): void {\n assertTable(isCode(value.version), \"version must be a non-empty string\");\n assertTable(isBp(value.gorjetaCapBp), \"gorjetaCapBp must be integer basis points in 0..10000\");\n const special = value.specialRegimes as Record<string, Record<string, unknown> | undefined> | undefined;\n assertTable(isRecord(special) && isRecord(special.BARES_RESTAURANTES), \"specialRegimes.BARES_RESTAURANTES must be an object\");\n assertTable(isBp(special!.BARES_RESTAURANTES!.reductionBp), \"specialRegimes.BARES_RESTAURANTES.reductionBp must be basis points\");\n assertTable(isRecord(value.exclusionClasses), \"exclusionClasses must be an object\");\n const classes = value.exclusionClasses as Record<string, unknown>;\n assertClassCode(classes.GORJETA, \"exclusionClasses.GORJETA\");\n assertClassCode(classes.INTERMEDIATION, \"exclusionClasses.INTERMEDIATION\");\n}\n\n/** Refuse a table the engine cannot trust: bad rates, bad dates, overlapping periods. */\nexport function assertRateTables(tables: unknown): asserts tables is RateTables {\n assertTable(isRecord(tables), \"the rate table must be an object\");\n const value = tables as Record<string, unknown>;\n assertTableHeader(value);\n assertTable(Array.isArray(value.periods) && value.periods.length > 0, \"periods must hold at least one period\");\n const periods = value.periods as unknown[];\n periods.forEach(assertPeriod);\n const sorted = [...(periods as RatePeriod[])].sort((a, b) => a.from.localeCompare(b.from));\n for (let i = 1; i < sorted.length; i += 1) {\n const previous = sorted[i - 1]!;\n assertTable(previous.to !== null && previous.to < sorted[i]!.from, `periods starting ${previous.from} and ${sorted[i]!.from} overlap`);\n }\n}\n\n/** The period covering `date`, or a refusal. */\nexport function periodAt(tables: RateTables, date: IsoDate): RatePeriod {\n const period = tables.periods.find((p) => p.from <= date && (p.to === null || date <= p.to));\n return period ?? refuse(\"NO_RATE_PERIOD\", `table ${tables.version} has no period covering ${date}`);\n}\n","/**\n * Everything the computation decides BEFORE a per-item figure is produced:\n * the regime's treatment on the date, which items are segregated exclusions,\n * each taxed item's reduction and base (`vBC`). Shared by the table mode and\n * the oracle mode, so the two can only ever disagree on the per-item figures —\n * the thing the oracle is there to check.\n */\n\nimport { FiscalEngineError } from \"./errors\";\nimport { effectiveRate, netUnitValue, splitTaxInclusivePrice } from \"./rounding\";\nimport { assertTaxInput, periodAt } from \"./validate\";\nimport type {\n LineFigures,\n LineSource,\n LineTax,\n RatePeriod,\n TaxBreakdown,\n TaxClass,\n TaxClassCode,\n TaxInput,\n TaxRegime,\n TaxTreatment,\n} from \"./types\";\n\n/** The three nominal rates at the destination. */\nexport interface DestinationRates {\n readonly cbsBp: number;\n readonly ibsUfBp: number;\n readonly ibsMunBp: number;\n}\n\nexport interface PlannedLine {\n readonly lineId: string;\n readonly source: LineSource;\n readonly quantity: number;\n readonly valueCents: number;\n readonly taxClass: TaxClass;\n readonly reductionBp: number;\n /** False for a segregated exclusion and for a line whose rates do not apply. */\n readonly taxed: boolean;\n /** `vBC`: the value, the value less its inside tax, or 0 on an exclusion. */\n readonly taxBaseCents: number;\n}\n\nexport interface TaxPlan {\n readonly input: TaxInput;\n readonly period: RatePeriod;\n readonly rates: DestinationRates;\n readonly treatment: TaxTreatment;\n readonly informative: boolean;\n readonly lines: readonly PlannedLine[];\n readonly gorjetaExcludedCents: number;\n readonly intermediationExcludedCents: number;\n}\n\nconst TREATMENT: Readonly<Record<TaxRegime, TaxTreatment>> = {\n REGIME_REGULAR: \"FULL\",\n SIMPLES_IBS_CBS_REGULAR: \"FULL\",\n SIMPLES: \"INFORMATIVE\",\n MEI: \"NONE\",\n NAO_CONTRIBUINTE: \"NONE\",\n};\n\nfunction isSimplesOptant(regime: TaxRegime): boolean {\n return regime === \"SIMPLES\" || regime === \"SIMPLES_IBS_CBS_REGULAR\";\n}\n\n/** The destination's own rate where the table lists one, the reference rate everywhere else. */\nfunction ownOrReference(rates: Readonly<Record<string, number>>, key: string, referenceBp: number): number {\n return Object.hasOwn(rates, key) ? rates[key]! : referenceBp;\n}\n\n/** The three nominal rates of the period at the destination (art. 11 I). */\nexport function ratesAt(period: RatePeriod, destinationIbge: string): DestinationRates {\n return {\n cbsBp: period.cbsBp,\n ibsUfBp: ownOrReference(period.ibsUf.byUf, destinationIbge.slice(0, 2), period.ibsUf.referenceBp),\n ibsMunBp: ownOrReference(period.ibsMun.byMunicipality, destinationIbge, period.ibsMun.referenceBp),\n };\n}\n\n/** The effective rates of one item, in the order CBS, IBS-UF, IBS-Mun. */\nfunction effectiveRates(rates: DestinationRates, reductionBp: number): bigint[] {\n return [rates.cbsBp, rates.ibsUfBp, rates.ibsMunBp].map((rate) => effectiveRate(rate, reductionBp));\n}\n\n/**\n * The gorjeta is excluded only when it is passed in full to the staff and is\n * at most 15% of the food and drink (art. 274 par. único I, read as a\n * condition): above the ceiling nothing is excluded — the conservative\n * reading, which never under-states the tax. Restaurant regime only.\n */\nfunction gorjetaIsExcluded(input: TaxInput): boolean {\n const charge = input.exclusions.serviceCharge;\n if (!charge || !charge.passedToStaff || !input.seller.restaurantRegime) return false;\n const foodAndDrink = input.lines.filter((line) => line.foodAndDrink).reduce((sum, line) => sum + line.valueCents, 0);\n return BigInt(charge.amountCents) * 10_000n <= BigInt(foodAndDrink) * BigInt(input.tables.gorjetaCapBp);\n}\n\n/** The 40% of art. 275 applies to the special regime's lines in a restaurant store; otherwise the class's own. */\nfunction reductionFor(input: TaxInput, taxClass: TaxClass): number {\n if (input.seller.restaurantRegime && taxClass.regimeEspecifico === \"BARES_RESTAURANTES\") {\n return input.tables.specialRegimes.BARES_RESTAURANTES.reductionBp;\n }\n return taxClass.reductionBp;\n}\n\nfunction exclusionClass(code: TaxClassCode): TaxClass {\n return { cClassTrib: code.cClassTrib, cstIbsCbs: code.cstIbsCbs, regimeEspecifico: null, reductionBp: 0 };\n}\n\ninterface LineDraft {\n readonly lineId: string;\n readonly source: LineSource;\n readonly quantity: number;\n readonly valueCents: number;\n readonly taxClass: TaxClass;\n readonly excluded: boolean;\n}\n\nfunction exclusionDrafts(input: TaxInput, gorjetaExcluded: boolean): LineDraft[] {\n const drafts: LineDraft[] = [];\n const charge = input.exclusions.serviceCharge;\n if (charge) {\n drafts.push({\n lineId: charge.id,\n source: gorjetaExcluded ? \"GORJETA_EXCLUDED\" : \"SERVICE_CHARGE\",\n quantity: 1,\n valueCents: charge.amountCents,\n taxClass: gorjetaExcluded ? exclusionClass(input.tables.exclusionClasses.GORJETA) : charge.taxClass,\n excluded: gorjetaExcluded,\n });\n }\n const retained = input.exclusions.retainedIntermediation;\n if (retained) {\n if (!input.seller.restaurantRegime) {\n throw new FiscalEngineError(\n \"INVALID_INPUT\",\n \"a retained intermediation is excluded only when seller.restaurantRegime is set (art. 274 sole paragraph, II); otherwise the amount belongs in the lines\",\n );\n }\n drafts.push({\n lineId: retained.id,\n source: \"INTERMEDIATION_EXCLUDED\",\n quantity: 1,\n valueCents: retained.amountCents,\n taxClass: exclusionClass(input.tables.exclusionClasses.INTERMEDIATION),\n excluded: true,\n });\n }\n return drafts;\n}\n\nfunction planLine(draft: LineDraft, input: TaxInput, context: { ratesApply: boolean; period: RatePeriod; rates: DestinationRates }): PlannedLine {\n const reductionBp = draft.excluded ? 0 : reductionFor(input, draft.taxClass);\n const taxed = !draft.excluded && context.ratesApply;\n let taxBaseCents = draft.excluded ? 0 : draft.valueCents;\n if (taxed && context.period.taxInsidePrice) {\n taxBaseCents = splitTaxInclusivePrice(draft.valueCents, effectiveRates(context.rates, reductionBp)).baseCents;\n }\n return {\n lineId: draft.lineId,\n source: draft.source,\n quantity: draft.quantity,\n valueCents: draft.valueCents,\n taxClass: draft.taxClass,\n reductionBp,\n taxed,\n taxBaseCents,\n };\n}\n\nexport function planTax(input: TaxInput): TaxPlan {\n assertTaxInput(input);\n const { regime, regimeEffectiveFrom } = input.seller;\n if (input.supplyDate < regimeEffectiveFrom) {\n throw new FiscalEngineError(\n \"REGIME_NOT_IN_EFFECT\",\n `the supply on ${input.supplyDate} precedes the seller's ${regime} regime, effective ${regimeEffectiveFrom}`,\n );\n }\n const period = periodAt(input.tables, input.supplyDate);\n const rates = ratesAt(period, input.destinationIbge);\n const treatment = TREATMENT[regime];\n const ratesApply = treatment !== \"NONE\" && (!isSimplesOptant(regime) || period.appliesToSimplesNacional);\n const gorjetaExcluded = gorjetaIsExcluded(input);\n const drafts: LineDraft[] = [\n ...input.lines.map((line) => ({\n lineId: line.id,\n source: \"LINE\" as const,\n quantity: line.quantity,\n valueCents: line.valueCents,\n taxClass: line.taxClass,\n excluded: false,\n })),\n ...exclusionDrafts(input, gorjetaExcluded),\n ];\n return {\n input,\n period,\n rates,\n treatment,\n informative: treatment === \"INFORMATIVE\" || (treatment === \"FULL\" && period.informative),\n lines: drafts.map((draft) => planLine(draft, input, { ratesApply, period, rates })),\n gorjetaExcludedCents: gorjetaExcluded ? input.exclusions.serviceCharge!.amountCents : 0,\n intermediationExcludedCents: input.exclusions.retainedIntermediation?.amountCents ?? 0,\n };\n}\n\n/** Zero figures, for an excluded line or one whose rates do not apply. */\nexport function zeroFigures(line: PlannedLine): LineFigures {\n return {\n reductionBp: line.reductionBp,\n cbsRateBp: 0,\n cbsCents: 0,\n ibsUfRateBp: 0,\n ibsUfCents: 0,\n ibsMunRateBp: 0,\n ibsMunCents: 0,\n };\n}\n\nfunction lineTax(plan: TaxPlan, line: PlannedLine, figures: LineFigures): LineTax {\n const taxCents = figures.cbsCents + figures.ibsUfCents + figures.ibsMunCents;\n const netValueCents = plan.period.taxInsidePrice ? line.valueCents - taxCents : null;\n return {\n lineId: line.lineId,\n source: line.source,\n quantity: line.quantity,\n valueCents: line.valueCents,\n taxBaseCents: line.taxBaseCents,\n taxClass: line.taxClass,\n ...figures,\n taxCents,\n netValueCents,\n netUnitValue: netValueCents === null ? null : netUnitValue(netValueCents, line.quantity),\n };\n}\n\n/** The breakdown: each line with its figures, the order as the sum of its rounded lines. */\nexport function assembleBreakdown(plan: TaxPlan, figures: readonly LineFigures[], tablesVersion: string): TaxBreakdown {\n const lines = plan.lines.map((line, index) => lineTax(plan, line, figures[index]!));\n const sum = (pick: (line: LineTax) => number) => lines.reduce((total, line) => total + pick(line), 0);\n const cbsCents = sum((line) => line.cbsCents);\n const ibsUfCents = sum((line) => line.ibsUfCents);\n const ibsMunCents = sum((line) => line.ibsMunCents);\n return {\n lines,\n valueCents: sum((line) => line.valueCents),\n taxBaseCents: sum((line) => line.taxBaseCents),\n cbsCents,\n ibsUfCents,\n ibsMunCents,\n ibsCents: ibsUfCents + ibsMunCents,\n totalTaxCents: cbsCents + ibsUfCents + ibsMunCents,\n netValueCents: plan.period.taxInsidePrice ? sum((line) => line.netValueCents ?? 0) : null,\n gorjetaExcludedCents: plan.gorjetaExcludedCents,\n intermediationExcludedCents: plan.intermediationExcludedCents,\n regime: plan.input.seller.regime,\n treatment: plan.treatment,\n informative: plan.informative,\n provisional: plan.period.status === \"ESTIMATE\",\n taxInsidePrice: plan.period.taxInsidePrice,\n supplyDate: plan.input.supplyDate,\n destinationIbge: plan.input.destinationIbge,\n tablesVersion,\n };\n}\n","/**\n * `computeTax` — the table mode. Pure: no I/O, no clock, no defaults. The\n * same input gives the same breakdown, stamped with the table's version, so a\n * supply settled in March reproduces its own tax in December after the tables\n * moved.\n */\n\nimport { assembleBreakdown, planTax, zeroFigures } from \"./plan\";\nimport type { PlannedLine, TaxPlan } from \"./plan\";\nimport { roundTaxCents } from \"./rounding\";\nimport type { LineFigures, TaxBreakdown, TaxInput } from \"./types\";\n\n/**\n * Each tax rounded on the item's base. In a tax-inside-price period the base\n * is the one the plan took out of the price, and these are the very taxes it\n * was taken out with.\n */\nfunction tableFigures(plan: TaxPlan, line: PlannedLine): LineFigures {\n if (!line.taxed) return zeroFigures(line);\n const { cbsBp, ibsUfBp, ibsMunBp } = plan.rates;\n return {\n reductionBp: line.reductionBp,\n cbsRateBp: cbsBp,\n cbsCents: roundTaxCents(line.taxBaseCents, cbsBp, line.reductionBp),\n ibsUfRateBp: ibsUfBp,\n ibsUfCents: roundTaxCents(line.taxBaseCents, ibsUfBp, line.reductionBp),\n ibsMunRateBp: ibsMunBp,\n ibsMunCents: roundTaxCents(line.taxBaseCents, ibsMunBp, line.reductionBp),\n };\n}\n\n/** The IBS/CBS breakdown of one supply, from the rate tables it is given. */\nexport function computeTax(input: TaxInput): TaxBreakdown {\n const plan = planTax(input);\n return assembleBreakdown(\n plan,\n plan.lines.map((line) => tableFigures(plan, line)),\n input.tables.version,\n );\n}\n","/**\n * The ORACLE mode: the same interface as `computeTax`, with the per-item\n * figures asked of an injected `OfficialCalculator` — the port a host points\n * at the official IBS/CBS calculator (the Receita Federal's Calculadora de\n * Tributos, open source, with an HTTP API and an embeddable component).\n * Everything else — the regime's treatment, the segregated exclusions, each\n * item's base — is the engine's own plan, so running both modes over one\n * fixture set checks exactly the rates, the reductions and the rounding\n * against the official figures.\n *\n * In a tax-inside-price period the base is taken out of the price with the\n * TABLE's rates (the calculator takes a base, not a price), and the\n * calculator's taxes on that base give the net value.\n */\n\nimport { FiscalEngineError } from \"./errors\";\nimport { assembleBreakdown, planTax, zeroFigures } from \"./plan\";\nimport type { LineFigures, TaxBreakdown, TaxClass, TaxInput } from \"./types\";\n\n\n/** One item, as the calculator is asked about it. */\nexport interface OfficialCalculatorItemRequest {\n readonly supplyDate: string;\n readonly destinationIbge: string;\n readonly cClassTrib: string;\n readonly cstIbsCbs: string;\n /** The base after the engine's exclusions (`vBC`). */\n readonly taxBaseCents: number;\n readonly quantity: number;\n}\n\n/** The calculator's answer for one item: nominal rates, the reduction, and the rounded taxes. */\nexport type OfficialCalculatorItemAnswer = LineFigures;\n\n/** The port. The host's adapter owns the transport, the retries and the unit conversion. */\nexport interface OfficialCalculator {\n /** Stamped on the result next to the tables' version. */\n readonly version: string;\n calculateItem(request: OfficialCalculatorItemRequest): Promise<OfficialCalculatorItemAnswer>;\n}\n\nconst ANSWER_FIELDS = [\"reductionBp\", \"cbsRateBp\", \"cbsCents\", \"ibsUfRateBp\", \"ibsUfCents\", \"ibsMunRateBp\", \"ibsMunCents\"] as const;\n\nfunction assertAnswer(answer: OfficialCalculatorItemAnswer, lineId: string): OfficialCalculatorItemAnswer {\n for (const field of ANSWER_FIELDS) {\n const value = answer?.[field];\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n throw new FiscalEngineError(\n \"INVALID_ORACLE_ANSWER\",\n `the calculator answered ${String(value)} for ${field} of line \"${lineId}\" — expected integer cents or basis points`,\n );\n }\n }\n return answer;\n}\n\nfunction requestFor(input: TaxInput, taxClass: TaxClass, taxBaseCents: number, quantity: number): OfficialCalculatorItemRequest {\n return {\n supplyDate: input.supplyDate,\n destinationIbge: input.destinationIbge,\n cClassTrib: taxClass.cClassTrib,\n cstIbsCbs: taxClass.cstIbsCbs,\n taxBaseCents,\n quantity,\n };\n}\n\n/** `computeTax`, with the per-item figures from the official calculator. */\nexport async function computeTaxWithOracle(input: TaxInput, calculator: OfficialCalculator): Promise<TaxBreakdown> {\n const plan = planTax(input);\n const figures: LineFigures[] = [];\n for (const line of plan.lines) {\n if (!line.taxed) {\n figures.push(zeroFigures(line));\n continue;\n }\n const answer = await calculator.calculateItem(requestFor(input, line.taxClass, line.taxBaseCents, line.quantity));\n figures.push(assertAnswer(answer, line.lineId));\n }\n return assembleBreakdown(plan, figures, `${input.tables.version}+oracle:${calculator.version}`);\n}\n","/**\n * Where two breakdowns of the same supply disagree — the table mode against\n * the oracle mode, or a stored snapshot against a recomputation. Versions are\n * not compared: they differ by construction.\n */\n\nimport type { LineTax, TaxBreakdown } from \"./types\";\n\nexport interface BreakdownDisagreement {\n /** `null` for an order-level field. */\n readonly lineId: string | null;\n readonly field: string;\n readonly left: unknown;\n readonly right: unknown;\n}\n\nconst LINE_FIELDS = [\n \"valueCents\",\n \"taxBaseCents\",\n \"reductionBp\",\n \"cbsRateBp\",\n \"cbsCents\",\n \"ibsUfRateBp\",\n \"ibsUfCents\",\n \"ibsMunRateBp\",\n \"ibsMunCents\",\n \"netValueCents\",\n] as const satisfies readonly (keyof LineTax)[];\n\nconst ORDER_FIELDS = [\n \"taxBaseCents\",\n \"cbsCents\",\n \"ibsUfCents\",\n \"ibsMunCents\",\n \"totalTaxCents\",\n \"netValueCents\",\n \"gorjetaExcludedCents\",\n \"intermediationExcludedCents\",\n \"treatment\",\n \"informative\",\n] as const satisfies readonly (keyof TaxBreakdown)[];\n\nfunction lineDisagreements(left: LineTax, right: LineTax | undefined): BreakdownDisagreement[] {\n if (!right) return [{ lineId: left.lineId, field: \"line\", left: left.lineId, right: undefined }];\n return LINE_FIELDS.filter((field) => left[field] !== right[field]).map((field) => ({\n lineId: left.lineId,\n field,\n left: left[field],\n right: right[field],\n }));\n}\n\n/** Every per-line field that differs, by line id; then the order fields that the lines do not already explain. */\nexport function compareBreakdowns(left: TaxBreakdown, right: TaxBreakdown): BreakdownDisagreement[] {\n const rightById = new Map(right.lines.map((line) => [line.lineId, line]));\n const lines = left.lines.flatMap((line) => lineDisagreements(line, rightById.get(line.lineId)));\n const leftIds = new Set(left.lines.map((line) => line.lineId));\n const extra = right.lines\n .filter((line) => !leftIds.has(line.lineId))\n .map((line) => ({ lineId: line.lineId, field: \"line\", left: undefined, right: line.lineId }));\n const order = ORDER_FIELDS.filter((field) => left[field] !== right[field]).map((field) => ({\n lineId: null,\n field,\n left: left[field],\n right: right[field],\n }));\n return [...lines, ...extra, ...order];\n}\n"],"mappings":";;;;;AAmBO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAnB7C,OAmB6C;AAAA;AAAA;AAAA,EAClC;AAAA,EAET,YAAY,MAA6B,SAAiB;AACxD,UAAM,mBAAmB,IAAI,KAAK,OAAO,E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AACxE,QAAM,QAAQ,KAAK,MAAM,QAAQ,CAAC,SAAS,kBAAkB,MAAM,UAAU,IAAI,KAAK,MAAM,CAAC,CAAC;AAC9F,QAAM,UAAU,IAAI,IAAI,KAAK,MAAM,IAAI,CAAC,SAAS,KAAK,MAAM,CAAC;AAC7D,QAAM,QAAQ,MAAM,MACjB,OAAO,CAAC,SAAS,CAAC,QAAQ,IAAI,KAAK,MAAM,CAAC,EAC1C,IAAI,CAAC,UAAU,EAAE,QAAQ,KAAK,QAAQ,OAAO,QAAQ,MAAM,QAAW,OAAO,KAAK,OAAO,EAAE;AAC9F,QAAM,QAAQ,aAAa,OAAO,CAAC,UAAU,KAAK,KAAK,MAAM,MAAM,KAAK,CAAC,EAAE,IAAI,CAAC,WAAW;AAAA,IACzF,QAAQ;AAAA,IACR;AAAA,IACA,MAAM,KAAK,KAAK;AAAA,IAChB,OAAO,MAAM,KAAK;AAAA,EACpB,EAAE;AACF,SAAO,CAAC,GAAG,OAAO,GAAG,OAAO,GAAG,KAAK;AACtC;AAdgB;","names":[]}
package/dist/http.d.ts ADDED
@@ -0,0 +1,73 @@
1
+ import { D as DanfeNfceLabels } from './labels-BNvflT0h.js';
2
+ import { D as DocumentStorage } from './context-ChnWR4Kb.js';
3
+ import { F as FiscalDocuments } from './service-KTjH7AxW.js';
4
+ import './port-DpRFK56U.js';
5
+ import './sale/index.js';
6
+ import './sidecar/index.js';
7
+ import './types-B1b8LIWX.js';
8
+
9
+ /**
10
+ * `createApiFiscal` — the fiscal HTTP surface as framework-neutral route
11
+ * descriptors (the wiring contract's `http` capability, restated here
12
+ * structurally: this package imports nothing from the contract at runtime,
13
+ * and its manifest suite pins the twins).
14
+ *
15
+ * The package owns the paths, the bodies it reads (`./documents/profile-input`,
16
+ * unknown keys refused), the `{ data }` envelope, the permission each route
17
+ * needs and the status a refusal earns ({@link FISCAL_ERROR_STATUS}). The host
18
+ * owns resolving WHO is calling into the opaque `ownerId` of its tenant, the
19
+ * guards that check the declared permission, and every word a person reads:
20
+ * an error answers a `code` for the host to word, never a sentence for a user.
21
+ *
22
+ * Nothing secret leaves: the profile answers `hasCertificate` / `hasCsc`, never
23
+ * a ciphertext, and the certificate upload answers the profile view.
24
+ */
25
+
26
+ /** The caller, as the host's adapter resolved it. */
27
+ interface FiscalHttpActor {
28
+ /** The emitter profile's owner: the host's tenant, mapped to an opaque id. */
29
+ readonly ownerId: string;
30
+ }
31
+ /** Structural twin of the wiring contract's `WireRequest<FiscalHttpActor>`. */
32
+ interface FiscalHttpRequest {
33
+ actor: FiscalHttpActor;
34
+ params: Record<string, string | undefined>;
35
+ query: Record<string, string | undefined>;
36
+ body?: unknown;
37
+ }
38
+ /** Structural twin of the wiring contract's `WireResponse`. */
39
+ interface FiscalHttpResponse {
40
+ status: number;
41
+ body: unknown;
42
+ }
43
+ /** Structural twin of the wiring contract's `WireRoute<FiscalHttpActor>`. */
44
+ interface FiscalRoute {
45
+ method: "GET" | "POST" | "PUT";
46
+ path: string;
47
+ permission: string;
48
+ handle(request: FiscalHttpRequest): Promise<FiscalHttpResponse>;
49
+ }
50
+ interface FiscalApiConfig {
51
+ readonly documents: FiscalDocuments;
52
+ /** Where the XMLs are, to render a DANFE from. */
53
+ readonly storage: DocumentStorage;
54
+ /** The DANFE's words: the host's, or `@12-apps/fiscal/danfe/pt-BR`. */
55
+ readonly danfeLabels: DanfeNfceLabels;
56
+ }
57
+ declare const FISCAL_ERROR_STATUS: {
58
+ readonly INVALID_INPUT: 400;
59
+ readonly NOT_FOUND: 404;
60
+ readonly NOT_ISSUABLE: 409;
61
+ readonly NOT_SUPPORTED: 501;
62
+ readonly TRANSITION_REFUSED: 409;
63
+ readonly SERIES_EXHAUSTED: 409;
64
+ readonly CONFLICT: 409;
65
+ readonly SUBJECT_HAS_DOCUMENT: 409;
66
+ readonly NOT_PRINTABLE: 409;
67
+ readonly RESEND_CHANGES_PRINTED_FIELDS: 422;
68
+ };
69
+ declare function createApiFiscal(config: FiscalApiConfig): {
70
+ routes: readonly FiscalRoute[];
71
+ };
72
+
73
+ export { FISCAL_ERROR_STATUS, type FiscalApiConfig, type FiscalHttpActor, type FiscalHttpRequest, type FiscalHttpResponse, type FiscalRoute, createApiFiscal };
package/dist/http.js ADDED
@@ -0,0 +1,16 @@
1
+ import {
2
+ FISCAL_ERROR_STATUS,
3
+ createApiFiscal
4
+ } from "./chunk-V5ZQAAJT.js";
5
+ import "./chunk-ALABGVPO.js";
6
+ import "./chunk-RRFKYVLZ.js";
7
+ import "./chunk-PNTKG3DZ.js";
8
+ import "./chunk-XQGW5HUG.js";
9
+ import "./chunk-3SDXLSG4.js";
10
+ import "./chunk-X6MRDUYH.js";
11
+ import "./chunk-7QVYU63E.js";
12
+ export {
13
+ FISCAL_ERROR_STATUS,
14
+ createApiFiscal
15
+ };
16
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,43 @@
1
+ import { I as Issuer } from '../port-DpRFK56U.js';
2
+ export { C as CancelBySubstitutionCall, a as CancelCall, b as InutilizeCall, c as IssueCall, d as IssuerFailure, e as IssuerOutcome, L as LookupCall, S as SignContingencyCall, f as SigningMaterial, T as TransmitCall, m as modelPath } from '../port-DpRFK56U.js';
3
+ import '../sale/index.js';
4
+ import '../sidecar/index.js';
5
+
6
+ /**
7
+ * The Issuer adapter over the fiscal service in this package's `sidecar/`
8
+ * folder, speaking exactly its wire contract (`../sidecar/types`). JSON in,
9
+ * JSON out; a non-2xx answer carries `{ error }` and is handed back
10
+ * classified, never thrown.
11
+ *
12
+ * What the service cannot classify because it never answered — the fetch
13
+ * failed, timed out or got something that is not the service's JSON — is
14
+ * `RETRYABLE` with `outcomeUnknown: true`: the call may have reached SEFAZ, so
15
+ * the next attempt is a retry of the SAME call, which the service settles by
16
+ * looking the key up first. The message names the path and the HTTP status,
17
+ * never the request: the request carries the certificate.
18
+ */
19
+
20
+ /** The `fetch` the adapter calls: the global one fits. */
21
+ type SidecarFetch = (url: string, init: {
22
+ method: string;
23
+ headers: Record<string, string>;
24
+ body?: string;
25
+ signal?: AbortSignal;
26
+ }) => Promise<{
27
+ readonly status: number;
28
+ text(): Promise<string>;
29
+ }>;
30
+ interface SidecarIssuerConfig {
31
+ /** Where the service listens, `http://fiscal-sidecar:8080`. No default. */
32
+ readonly baseUrl: string;
33
+ readonly fetch: SidecarFetch;
34
+ /**
35
+ * How long one call may take, in ms. The service gives SEFAZ its connect
36
+ * timeout plus 20 s and may then look the key up, so this is longer than
37
+ * both; a shorter one turns answered calls into unknown outcomes.
38
+ */
39
+ readonly timeoutMs: number;
40
+ }
41
+ declare function createSidecarIssuer(config: SidecarIssuerConfig): Issuer;
42
+
43
+ export { Issuer, type SidecarFetch, type SidecarIssuerConfig, createSidecarIssuer };
@@ -0,0 +1,131 @@
1
+ import {
2
+ SIDECAR_ERROR_CLASSES
3
+ } from "../chunk-FOFIN5M7.js";
4
+ import {
5
+ __name
6
+ } from "../chunk-7QVYU63E.js";
7
+
8
+ // src/issuer/port.ts
9
+ function modelPath(model) {
10
+ return model === "NFE" ? "nfe" : "nfce";
11
+ }
12
+ __name(modelPath, "modelPath");
13
+
14
+ // src/issuer/sidecar.ts
15
+ function unanswered(message) {
16
+ return {
17
+ class: "RETRYABLE",
18
+ code: null,
19
+ message,
20
+ details: [],
21
+ accessKey: null,
22
+ signedXml: null,
23
+ sefazReply: null,
24
+ outcomeUnknown: true
25
+ };
26
+ }
27
+ __name(unanswered, "unanswered");
28
+ function isErrorBody(value) {
29
+ if (value === null || typeof value !== "object" || !("error" in value)) return false;
30
+ const error = value.error;
31
+ return error !== null && typeof error === "object" && SIDECAR_ERROR_CLASSES.includes(error.class);
32
+ }
33
+ __name(isErrorBody, "isErrorBody");
34
+ function parse(text) {
35
+ try {
36
+ return JSON.parse(text);
37
+ } catch {
38
+ return void 0;
39
+ }
40
+ }
41
+ __name(parse, "parse");
42
+ async function post(config, base, path, body) {
43
+ let status;
44
+ let text;
45
+ try {
46
+ const response = await config.fetch(`${base}${path}`, {
47
+ method: "POST",
48
+ headers: { "content-type": "application/json", accept: "application/json" },
49
+ body: JSON.stringify(body),
50
+ signal: AbortSignal.timeout(config.timeoutMs)
51
+ });
52
+ status = response.status;
53
+ text = await response.text();
54
+ } catch (error) {
55
+ const why = error instanceof Error ? error.name : "unknown";
56
+ return { ok: false, error: unanswered(`POST ${path} got no answer from the fiscal service (${why}).`) };
57
+ }
58
+ const parsed = parse(text);
59
+ if (status >= 200 && status < 300 && parsed !== void 0 && !isErrorBody(parsed)) return { ok: true, answer: parsed };
60
+ if (isErrorBody(parsed)) return { ok: false, error: parsed.error };
61
+ return { ok: false, error: unanswered(`POST ${path} answered HTTP ${status} without the service's error body.`) };
62
+ }
63
+ __name(post, "post");
64
+ function createSidecarIssuer(config) {
65
+ if (typeof config?.baseUrl !== "string" || config.baseUrl === "") throw new TypeError("createSidecarIssuer needs baseUrl.");
66
+ if (typeof config.fetch !== "function") throw new TypeError("createSidecarIssuer needs fetch.");
67
+ if (!Number.isInteger(config.timeoutMs) || config.timeoutMs <= 0) throw new TypeError("createSidecarIssuer needs a positive timeoutMs.");
68
+ let baseEnd = config.baseUrl.length;
69
+ while (baseEnd > 0 && config.baseUrl[baseEnd - 1] === "/") baseEnd -= 1;
70
+ const base = config.baseUrl.slice(0, baseEnd);
71
+ const call = /* @__PURE__ */ __name((path, body) => post(config, base, path, body), "call");
72
+ return {
73
+ issue: /* @__PURE__ */ __name(({ model, environment, signing, document }) => call(`/${modelPath(model)}/issue`, {
74
+ environment,
75
+ certificate: signing.certificate,
76
+ csc: model === "NFCE" ? signing.csc : null,
77
+ document
78
+ }), "issue"),
79
+ signContingency: /* @__PURE__ */ __name(({ environment, signing, document, contingency }) => call("/nfce/sign-contingency", {
80
+ environment,
81
+ certificate: signing.certificate,
82
+ csc: signing.csc,
83
+ document,
84
+ contingency
85
+ }), "signContingency"),
86
+ transmit: /* @__PURE__ */ __name(({ model, environment, signing, signedXml }) => call(`/${modelPath(model)}/transmit`, { environment, certificate: signing.certificate, signedXml }), "transmit"),
87
+ cancel: /* @__PURE__ */ __name(({ model, environment, signing, accessKey, protocol, reason }) => call(`/${modelPath(model)}/cancel`, {
88
+ environment,
89
+ certificate: signing.certificate,
90
+ accessKey,
91
+ protocol,
92
+ reason
93
+ }), "cancel"),
94
+ cancelBySubstitution: /* @__PURE__ */ __name(({ environment, signing, accessKey, protocol, reason, substituteAccessKey }) => call("/nfce/cancel-substitution", {
95
+ environment,
96
+ certificate: signing.certificate,
97
+ accessKey,
98
+ protocol,
99
+ reason,
100
+ substituteAccessKey
101
+ }), "cancelBySubstitution"),
102
+ lookup: /* @__PURE__ */ __name(({ model, environment, signing, accessKey }) => call(`/${modelPath(model)}/lookup`, { environment, certificate: signing.certificate, accessKey }), "lookup"),
103
+ inutilize: /* @__PURE__ */ __name(({ model, environment, signing, uf, cnpj, year, series, from, to, reason }) => call("/inutilize", {
104
+ environment,
105
+ certificate: signing.certificate,
106
+ model: modelPath(model),
107
+ uf,
108
+ cnpj,
109
+ year,
110
+ series,
111
+ from,
112
+ to,
113
+ reason
114
+ }), "inutilize"),
115
+ async health() {
116
+ const response = await config.fetch(`${base}/health`, {
117
+ method: "GET",
118
+ headers: { accept: "application/json" },
119
+ signal: AbortSignal.timeout(config.timeoutMs)
120
+ });
121
+ if (response.status !== 200) throw new Error(`The fiscal service's /health answered HTTP ${response.status}.`);
122
+ return JSON.parse(await response.text());
123
+ }
124
+ };
125
+ }
126
+ __name(createSidecarIssuer, "createSidecarIssuer");
127
+ export {
128
+ createSidecarIssuer,
129
+ modelPath
130
+ };
131
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/issuer/port.ts","../../src/issuer/sidecar.ts"],"sourcesContent":["/**\n * The Issuer port: what the document service asks of whoever talks to SEFAZ.\n * The first (and today only) adapter is the fiscal service in this package's\n * `sidecar/` folder (`./sidecar`). A call never throws for a failure the\n * service classified: it answers `{ ok: false, error }` with the service's\n * class (`REJECTED`, `RETRYABLE`, `CONTINGENCY`, `AUTH`, `INVALID`,\n * `INTERNAL`), and the document service maps that onto the state machine.\n *\n * The certificate and the CSC travel with each call (the service is\n * stateless) inside {@link SigningMaterial}, built by the signing identity\n * for this one call and dropped with it.\n */\n\nimport type { FiscalDocumentModel } from \"../documents/types\";\nimport type { SaleForDocument } from \"../sale/types\";\nimport type {\n CancelledDocument,\n ContingencyEntry,\n ContingencySignedDocument,\n Csc,\n InutilizedRange,\n IssuedDocument,\n LookedUpDocument,\n SefazEnvironment,\n SidecarErrorBody,\n SidecarHealth,\n SigningCertificate,\n} from \"../sidecar/types\";\n\n/** What signs one call: the A1 and, for an NFC-e, the CSC. Never stored, never logged. */\nexport interface SigningMaterial {\n readonly certificate: SigningCertificate;\n readonly csc: Csc | null;\n}\n\n/** A failed call, classified. The service's error body, verbatim. */\nexport type IssuerFailure = SidecarErrorBody[\"error\"];\n\nexport type IssuerOutcome<T> = { readonly ok: true; readonly answer: T } | { readonly ok: false; readonly error: IssuerFailure };\n\ninterface Call {\n readonly environment: SefazEnvironment;\n readonly signing: SigningMaterial;\n}\n\nexport interface IssueCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly document: SaleForDocument;\n}\n\nexport interface SignContingencyCall extends Call {\n readonly document: SaleForDocument;\n readonly contingency: ContingencyEntry;\n}\n\nexport interface TransmitCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly signedXml: string;\n}\n\nexport interface CancelCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly accessKey: string;\n readonly protocol: string;\n readonly reason: string;\n}\n\n/** NFC-e only: cancel an online document whose sale was issued again in contingency (event 110112). */\nexport interface CancelBySubstitutionCall extends Call {\n readonly accessKey: string;\n readonly protocol: string;\n readonly reason: string;\n readonly substituteAccessKey: string;\n}\n\nexport interface LookupCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly accessKey: string;\n}\n\nexport interface InutilizeCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly uf: string;\n readonly cnpj: string;\n readonly year: number;\n readonly series: number;\n readonly from: number;\n readonly to: number;\n readonly reason: string;\n}\n\nexport interface Issuer {\n /** Build, sign and transmit. `AUTHORIZED` or `DENIED`. */\n issue(call: IssueCall): Promise<IssuerOutcome<IssuedDocument>>;\n /** NFC-e only: build and sign offline (`tpEmis = 9`); nothing is sent. */\n signContingency(call: SignContingencyCall): Promise<IssuerOutcome<ContingencySignedDocument>>;\n /** Send an already signed XML (a contingency document). */\n transmit(call: TransmitCall): Promise<IssuerOutcome<IssuedDocument>>;\n cancel(call: CancelCall): Promise<IssuerOutcome<CancelledDocument>>;\n cancelBySubstitution(call: CancelBySubstitutionCall): Promise<IssuerOutcome<CancelledDocument>>;\n lookup(call: LookupCall): Promise<IssuerOutcome<LookedUpDocument>>;\n inutilize(call: InutilizeCall): Promise<IssuerOutcome<InutilizedRange>>;\n health(): Promise<SidecarHealth>;\n}\n\n/** The path segment of a model on the service's routes. */\nexport function modelPath(model: FiscalDocumentModel): \"nfe\" | \"nfce\" {\n return model === \"NFE\" ? \"nfe\" : \"nfce\";\n}\n","/**\n * The Issuer adapter over the fiscal service in this package's `sidecar/`\n * folder, speaking exactly its wire contract (`../sidecar/types`). JSON in,\n * JSON out; a non-2xx answer carries `{ error }` and is handed back\n * classified, never thrown.\n *\n * What the service cannot classify because it never answered — the fetch\n * failed, timed out or got something that is not the service's JSON — is\n * `RETRYABLE` with `outcomeUnknown: true`: the call may have reached SEFAZ, so\n * the next attempt is a retry of the SAME call, which the service settles by\n * looking the key up first. The message names the path and the HTTP status,\n * never the request: the request carries the certificate.\n */\n\nimport type {\n CancelBySubstitutionRequest,\n CancelRequest,\n InutilizeRequest,\n IssueRequest,\n LookupRequest,\n SidecarErrorBody,\n SidecarHealth,\n SignContingencyRequest,\n TransmitRequest,\n} from \"../sidecar/types\";\nimport { SIDECAR_ERROR_CLASSES } from \"../sidecar/types\";\nimport { type Issuer, type IssuerFailure, type IssuerOutcome, modelPath } from \"./port\";\n\n/** The `fetch` the adapter calls: the global one fits. */\nexport type SidecarFetch = (url: string, init: { method: string; headers: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<{\n readonly status: number;\n text(): Promise<string>;\n}>;\n\nexport interface SidecarIssuerConfig {\n /** Where the service listens, `http://fiscal-sidecar:8080`. No default. */\n readonly baseUrl: string;\n readonly fetch: SidecarFetch;\n /**\n * How long one call may take, in ms. The service gives SEFAZ its connect\n * timeout plus 20 s and may then look the key up, so this is longer than\n * both; a shorter one turns answered calls into unknown outcomes.\n */\n readonly timeoutMs: number;\n}\n\nfunction unanswered(message: string): IssuerFailure {\n return {\n class: \"RETRYABLE\",\n code: null,\n message,\n details: [],\n accessKey: null,\n signedXml: null,\n sefazReply: null,\n outcomeUnknown: true,\n };\n}\n\nfunction isErrorBody(value: unknown): value is SidecarErrorBody {\n if (value === null || typeof value !== \"object\" || !(\"error\" in value)) return false;\n const error = (value as { error: unknown }).error;\n return (\n error !== null &&\n typeof error === \"object\" &&\n SIDECAR_ERROR_CLASSES.includes((error as { class: IssuerFailure[\"class\"] }).class)\n );\n}\n\nfunction parse(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/** One POST to the service, its answer classified; never throws. */\nasync function post<T>(config: SidecarIssuerConfig, base: string, path: string, body: unknown): Promise<IssuerOutcome<T>> {\n let status: number;\n let text: string;\n try {\n const response = await config.fetch(`${base}${path}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", accept: \"application/json\" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(config.timeoutMs),\n });\n status = response.status;\n text = await response.text();\n } catch (error) {\n const why = error instanceof Error ? error.name : \"unknown\";\n return { ok: false, error: unanswered(`POST ${path} got no answer from the fiscal service (${why}).`) };\n }\n const parsed = parse(text);\n if (status >= 200 && status < 300 && parsed !== undefined && !isErrorBody(parsed)) return { ok: true, answer: parsed as T };\n if (isErrorBody(parsed)) return { ok: false, error: parsed.error };\n return { ok: false, error: unanswered(`POST ${path} answered HTTP ${status} without the service's error body.`) };\n}\n\nexport function createSidecarIssuer(config: SidecarIssuerConfig): Issuer {\n if (typeof config?.baseUrl !== \"string\" || config.baseUrl === \"\") throw new TypeError(\"createSidecarIssuer needs baseUrl.\");\n if (typeof config.fetch !== \"function\") throw new TypeError(\"createSidecarIssuer needs fetch.\");\n if (!Number.isInteger(config.timeoutMs) || config.timeoutMs <= 0) throw new TypeError(\"createSidecarIssuer needs a positive timeoutMs.\");\n let baseEnd = config.baseUrl.length;\n while (baseEnd > 0 && config.baseUrl[baseEnd - 1] === \"/\") baseEnd -= 1;\n const base = config.baseUrl.slice(0, baseEnd);\n\n const call = <T>(path: string, body: unknown) => post<T>(config, base, path, body);\n\n return {\n issue: ({ model, environment, signing, document }) =>\n call(`/${modelPath(model)}/issue`, {\n environment,\n certificate: signing.certificate,\n csc: model === \"NFCE\" ? signing.csc : null,\n document,\n } satisfies IssueRequest),\n signContingency: ({ environment, signing, document, contingency }) =>\n call(\"/nfce/sign-contingency\", {\n environment,\n certificate: signing.certificate,\n csc: signing.csc,\n document,\n contingency,\n } satisfies SignContingencyRequest),\n transmit: ({ model, environment, signing, signedXml }) =>\n call(`/${modelPath(model)}/transmit`, { environment, certificate: signing.certificate, signedXml } satisfies TransmitRequest),\n cancel: ({ model, environment, signing, accessKey, protocol, reason }) =>\n call(`/${modelPath(model)}/cancel`, {\n environment,\n certificate: signing.certificate,\n accessKey,\n protocol,\n reason,\n } satisfies CancelRequest),\n cancelBySubstitution: ({ environment, signing, accessKey, protocol, reason, substituteAccessKey }) =>\n call(\"/nfce/cancel-substitution\", {\n environment,\n certificate: signing.certificate,\n accessKey,\n protocol,\n reason,\n substituteAccessKey,\n } satisfies CancelBySubstitutionRequest),\n lookup: ({ model, environment, signing, accessKey }) =>\n call(`/${modelPath(model)}/lookup`, { environment, certificate: signing.certificate, accessKey } satisfies LookupRequest),\n inutilize: ({ model, environment, signing, uf, cnpj, year, series, from, to, reason }) =>\n call(\"/inutilize\", {\n environment,\n certificate: signing.certificate,\n model: modelPath(model),\n uf,\n cnpj,\n year,\n series,\n from,\n to,\n reason,\n } satisfies InutilizeRequest),\n async health() {\n const response = await config.fetch(`${base}/health`, {\n method: \"GET\",\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(config.timeoutMs),\n });\n if (response.status !== 200) throw new Error(`The fiscal service's /health answered HTTP ${response.status}.`);\n return JSON.parse(await response.text()) as SidecarHealth;\n },\n };\n}\n"],"mappings":";;;;;;;;AA0GO,SAAS,UAAU,OAA4C;AACpE,SAAO,UAAU,QAAQ,QAAQ;AACnC;AAFgB;;;AC5DhB,SAAS,WAAW,SAAgC;AAClD,SAAO;AAAA,IACL,OAAO;AAAA,IACP,MAAM;AAAA,IACN;AAAA,IACA,SAAS,CAAC;AAAA,IACV,WAAW;AAAA,IACX,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,gBAAgB;AAAA,EAClB;AACF;AAXS;AAaT,SAAS,YAAY,OAA2C;AAC9D,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,EAAE,WAAW,OAAQ,QAAO;AAC/E,QAAM,QAAS,MAA6B;AAC5C,SACE,UAAU,QACV,OAAO,UAAU,YACjB,sBAAsB,SAAU,MAA4C,KAAK;AAErF;AARS;AAUT,SAAS,MAAM,MAAuB;AACpC,MAAI;AACF,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AANS;AAST,eAAe,KAAQ,QAA6B,MAAc,MAAc,MAA0C;AACxH,MAAI;AACJ,MAAI;AACJ,MAAI;AACF,UAAM,WAAW,MAAM,OAAO,MAAM,GAAG,IAAI,GAAG,IAAI,IAAI;AAAA,MACpD,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,oBAAoB,QAAQ,mBAAmB;AAAA,MAC1E,MAAM,KAAK,UAAU,IAAI;AAAA,MACzB,QAAQ,YAAY,QAAQ,OAAO,SAA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M,WAAW,MAAM,OAAO,MAAM,GAAG,IAAI,WAAW;AAAA,QACpD,QAAQ;AAAA,QACR,SAAS,EAAE,QAAQ,mBAAmB;AAAA,QACtC,QAAQ,YAAY,QAAQ,OAAO,SAAS;AAAA,MAC9C,CAAC;AACD,UAAI,SAAS,WAAW,IAAK,OAAM,IAAI,MAAM,8CAA8C,SAAS,MAAM,GAAG;AAC7G,aAAO,KAAK,MAAM,MAAM,SAAS,KAAK,CAAC;AAAA,IACzC;AAAA,EACF;AACF;AAtEgB;","names":[]}
package/dist/jobs.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ import * as _12_apps_wiring from '@12-apps/wiring';
2
+ import { F as FiscalStore, a as FiscalNotifyPort } from './context-ChnWR4Kb.js';
3
+ import { F as FiscalDocuments } from './service-KTjH7AxW.js';
4
+ import './port-DpRFK56U.js';
5
+ import './sale/index.js';
6
+ import './sidecar/index.js';
7
+ import './types-B1b8LIWX.js';
8
+
9
+ interface FiscalJobDeps {
10
+ readonly documents: Pick<FiscalDocuments, "sweep" | "transmitContingency">;
11
+ readonly store: Pick<FiscalStore, "listExpiringCertificates">;
12
+ readonly notify: FiscalNotifyPort;
13
+ readonly now: () => Date;
14
+ }
15
+ /** The single-flight lease a sweep or a transmission run holds. */
16
+ declare const FISCAL_JOB_LEASE_MS: number;
17
+ /**
18
+ * The worst one document can cost a run: an issue call and the offline
19
+ * signing after it, each bounded by the issuer's timeout (90 s recommended
20
+ * for the sidecar adapter, whose own SEFAZ call gets 50 s and a lookup).
21
+ */
22
+ declare const FISCAL_WORST_STEP_MS: number;
23
+ /**
24
+ * At most this many documents per run, derived so that a run of the worst
25
+ * steps still ends inside its lease: a second run can never overlap the
26
+ * first. A backlog drains over several five-minute runs.
27
+ */
28
+ declare const FISCAL_SWEEP_BATCH: number;
29
+ /** The days before expiry the owner is told; after expiry, every day. */
30
+ declare const CERTIFICATE_WARNING_DAYS: readonly number[];
31
+ /** Whole days from `now` to `expiresAt`, rounded up: 0 is "today", negative is "expired". */
32
+ declare function daysLeft(expiresAt: string, now: Date): number;
33
+ declare const FISCAL_JOBS: {
34
+ namespace: string;
35
+ blueprints: {
36
+ sweep: {
37
+ name: string;
38
+ schedule: {
39
+ pattern: string;
40
+ };
41
+ /** The batch is sized so a run of worst-case steps ends inside this lease. */
42
+ lease: {
43
+ ttlMs: number;
44
+ };
45
+ /** A missed run is caught up by the next tick. */
46
+ attempts: number;
47
+ handle(_payload: never, deps: FiscalJobDeps, context: _12_apps_wiring.WireJobContext): Promise<void>;
48
+ };
49
+ transmitContingency: {
50
+ name: string;
51
+ schedule: {
52
+ pattern: string;
53
+ };
54
+ lease: {
55
+ ttlMs: number;
56
+ };
57
+ attempts: number;
58
+ handle(_payload: never, deps: FiscalJobDeps, context: _12_apps_wiring.WireJobContext): Promise<void>;
59
+ };
60
+ certificateExpiry: {
61
+ name: string;
62
+ schedule: {
63
+ pattern: string;
64
+ };
65
+ lease: {
66
+ ttlMs: number;
67
+ };
68
+ attempts: number;
69
+ handle(_payload: never, deps: FiscalJobDeps, context: _12_apps_wiring.WireJobContext): Promise<void>;
70
+ };
71
+ };
72
+ };
73
+
74
+ export { CERTIFICATE_WARNING_DAYS, FISCAL_JOBS, FISCAL_JOB_LEASE_MS, FISCAL_SWEEP_BATCH, FISCAL_WORST_STEP_MS, type FiscalJobDeps, daysLeft };
package/dist/jobs.js ADDED
@@ -0,0 +1,22 @@
1
+ import {
2
+ CERTIFICATE_WARNING_DAYS,
3
+ FISCAL_JOBS,
4
+ FISCAL_JOB_LEASE_MS,
5
+ FISCAL_SWEEP_BATCH,
6
+ FISCAL_WORST_STEP_MS,
7
+ daysLeft
8
+ } from "./chunk-HQ2NXSTX.js";
9
+ import "./chunk-27B4HNO6.js";
10
+ import "./chunk-XQGW5HUG.js";
11
+ import "./chunk-3SDXLSG4.js";
12
+ import "./chunk-X6MRDUYH.js";
13
+ import "./chunk-7QVYU63E.js";
14
+ export {
15
+ CERTIFICATE_WARNING_DAYS,
16
+ FISCAL_JOBS,
17
+ FISCAL_JOB_LEASE_MS,
18
+ FISCAL_SWEEP_BATCH,
19
+ FISCAL_WORST_STEP_MS,
20
+ daysLeft
21
+ };
22
+ //# sourceMappingURL=jobs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The words a DANFE NFC-e prints. The layout is the Manual do DANFE NFC-e's
3
+ * and the words are the host's language: a host passes them all, or the
4
+ * `./pt-BR` pack, which carries the Manual's own texts. Nothing here defaults.
5
+ */
6
+ interface DanfeNfceLabels {
7
+ /** Division I. */
8
+ readonly cnpj: string;
9
+ readonly stateRegistration: string;
10
+ /** Division II: the document's own title. */
11
+ readonly title: string;
12
+ /** Division III: the item table's header. */
13
+ readonly itemsHeader: string;
14
+ /** Division IV. */
15
+ readonly itemCount: string;
16
+ readonly totalValue: string;
17
+ readonly discounts: string;
18
+ readonly amountDue: string;
19
+ readonly paymentHeader: string;
20
+ readonly change: string;
21
+ /** `tPag` code (`01`, `17`…) → the method's name; an unknown code prints itself. */
22
+ readonly paymentMethods: Readonly<Record<string, string>>;
23
+ /** Division V. */
24
+ readonly lookupByKey: string;
25
+ readonly homologation: string;
26
+ readonly contingency: string;
27
+ readonly pendingAuthorization: string;
28
+ /** Printed on a paper signed offline and not yet authorised: the one copy, the consumer's. */
29
+ readonly consumerCopy: string;
30
+ /** Division VI. */
31
+ readonly consumer: string;
32
+ readonly unidentifiedConsumer: string;
33
+ /** Division VII. */
34
+ readonly number: string;
35
+ readonly series: string;
36
+ readonly protocol: string;
37
+ readonly authorizedAt: string;
38
+ /** Division VIII and after: the QR code's caption and the approximate tax line (Lei 12.741/2012). */
39
+ readonly qrCaption: string;
40
+ readonly approximateTaxes: string;
41
+ }
42
+ declare const DANFE_LABEL_KEYS: readonly (keyof DanfeNfceLabels)[];
43
+
44
+ export { type DanfeNfceLabels as D, DANFE_LABEL_KEYS as a };