@dojocoding/hacienda-sdk

中文文档
0.13.0发布于 2026/11/01MITTypeScriptES Module构建来源已验证近 30 天下载 6022

Core SDK for Costa Rica electronic invoicing (Hacienda API v4.4)

原始使用文档
文档目录24 节
  1. Installation
  2. Quick Start
  3. Supported Inputs
  4. API Reference
  5. Client
  6. Authentication
  7. Clave Numerica
  8. XML
  9. Tax Calculation
  10. Signing
  11. API Client
  12. Configuration
  13. Logging
  14. Errors
  15. Error Codes (API)
  16. Full Documentation
  17. Migrating to 0.4.0
  18. Exact decimal ordinary FE (additive)
  19. Exact ordinary TE source candidate
  20. Exact ordinary ND source candidate
  21. Unreleased exact ordinary domestic FEC source
  22. Unreleased exact credit extensions
  23. Unreleased current FE validation correction
  24. Unreleased explicit foreign-service IVA13 purchase source

@dojocoding/hacienda-sdk

Core SDK for Costa Rica electronic invoicing (Hacienda API v4.4).

Provides authentication, XML generation, XAdES-EPES digital signing, tax calculation, and a typed HTTP client for the Ministerio de Hacienda API.

Installation

npm install @dojocoding/hacienda-sdk

Requires Node.js 22+ (uses native fetch and crypto.subtle).

Quick Start

import { HaciendaClient, Environment, IdType } from "@dojocoding/hacienda-sdk";

const client = new HaciendaClient({
  environment: Environment.Sandbox,
  credentials: {
    idType: IdType.PersonaJuridica,
    idNumber: "3101234567",
    username: process.env.HACIENDA_USERNAME!, // Full issued IDP username.
    password: process.env.HACIENDA_PASSWORD!,
  },
});

await client.authenticate();
const token = await client.getAccessToken();

Set HACIENDA_USERNAME to the complete username copied from Tico Factura, including every hyphen and the domain (for example, [email protected]). credentials.username is sent unchanged and can be used with just password; identification fields are optional in this mode. If supplied, they remain validated taxpayer IDs. Without username, the SDK retains the legacy buildUsername(idType, idNumber) fallback. It cannot infer an issued username from a taxpayer ID.

For a runnable invoice → validation → signing → submission → status workflow, follow the sandbox walkthrough using examples/sandbox.mjs and examples/order.json. For application architecture, see the production integration guide. Review the v4.4 migration notes before adapting existing inputs.

Supported Inputs

Legal entity IDs accept ten alphanumeric characters throughout identification and clave generation/parsing. Three-digit special phones such as 911 are supported. Taxes support amount-only ISC and datosImpuestoEspecifico, including five-decimal alcohol proportions. Mixed-tax calculations include applicable specific taxes in the IVA base and all net taxes in totals. See the migration notes for input examples and compatibility details.

API Reference

Client

ExportTypeDescription
HaciendaClientClassPrimary entry point -- orchestrates auth, clave generation
HaciendaClientOptionsSchemaZod schemaValidates client constructor options

Authentication

ExportTypeDescription
TokenManagerClassOAuth2 ROPC token lifecycle management
loadCredentials()FunctionBuilds and validates auth credentials
buildUsername()FunctionBuilds the IDP username from cedula type and number
getEnvironmentConfig()FunctionReturns API/IDP URLs for an environment
EnvironmentEnumSandbox, Production
IdTypeEnumPersonaFisica, PersonaJuridica, DIMEX, NITE

Clave Numerica

ExportTypeDescription
buildClave()FunctionBuilds a 50-character clave from components
parseClave()FunctionParses a 50-character clave into components
DocumentTypeEnumDocument type codes (01-09)
SituationEnumSituation codes (1-3)

XML

ExportTypeDescription
buildXml()FunctionLow-level XML builder with namespace support
buildFacturaXml()FunctionBuilds a Factura Electronica XML document
buildTiqueteXml()FunctionBuilds a Tiquete Electronico XML document
buildNotaCreditoXml()FunctionBuilds a Nota de Credito Electronica XML document
buildNotaDebitoXml()FunctionBuilds a Nota de Debito Electronica XML document
buildFacturaCompraXml()FunctionBuilds a Factura Electronica de Compra XML document
buildFacturaExportacionXml()FunctionBuilds a Factura Electronica de Exportacion XML document
buildReciboPagoXml()FunctionBuilds a Recibo Electronico de Pago XML document
buildMensajeReceptorXml()FunctionBuilds a Mensaje Receptor XML document
validateFacturaInput()FunctionValidates factura data against business rules
validateDocumentXml()FunctionValidates against bundled v4.4 XSD; optionally requires signature structure

Tax Calculation

ExportTypeDescription
calculateLineItemTotals()FunctionComputes all totals for a single line item
calculateInvoiceSummary()FunctionAggregates all line items into a ResumenFactura
round5()FunctionRounds to 5 decimal places (Hacienda requirement)

Signing

ExportTypeDescription
loadP12()FunctionLoads a .p12 certificate and extracts keys
signXml()FunctionSigns XML with XAdES-EPES (returns signed XML string)
signAndEncode()FunctionSigns XML and Base64-encodes for API submission

API Client

ExportTypeDescription
HttpClientClassTyped HTTP client with auth header injection
bootstrapClient()FunctionCreates an authenticated HTTP client from a saved profile
RateLimiterClassRequest rate limiter
submitDocument()FunctionSubmits a document (POST /recepcion)
getStatus()FunctionGets document status (GET /recepcion/{clave})
submitAndWait()FunctionSubmits and polls until terminal status
withRetry()FunctionWraps an async operation with retry logic
listComprobantes()FunctionLists one observed metadata page with combined party filters
getComprobante()FunctionGets observed metadata/references by clave (not XML/status)
lookupTaxpayer()FunctionLooks up taxpayer by cedula (public API)
isTerminalStatus()FunctionChecks if a status is final
extractRejectionReason()FunctionExtracts rejection reason from response XML

Configuration

ExportTypeDescription
loadConfig()FunctionLoads a profile from ~/.hacienda-cr/config.toml
saveConfig()FunctionSaves a profile to config
listProfiles()FunctionLists all configured profiles
deleteProfile()FunctionDeletes a profile
getNextSequence()FunctionGets and increments the next document sequence
getCurrentSequence()FunctionGets the current sequence without incrementing
resetSequence()FunctionResets a document sequence to 0

Sequence helpers take (documentType, branch, pos, options); resetSequence takes (documentType, branch, pos, value, options). The local counter key does not include issuer, profile, or environment. Use options.configDir to isolate local counters, or allocate transactionally in your application's database for multiple hosts. See sequence allocation.

Logging

ExportTypeDescription
LoggerClassStructured logger with levels and formats
LogLevelEnumDEBUG, INFO, WARN, ERROR, SILENT
noopLoggerInstanceLogger that suppresses all output

Errors

ExportTypeDescription
HaciendaErrorClassBase error class for all SDK errors
ValidationErrorClassInput validation failures
ApiErrorClassHTTP/network errors (includes statusCode, responseBody)
AuthenticationErrorClassAuth/token lifecycle failures
SigningErrorClassXAdES-EPES signing failures
HaciendaErrorCodeEnumError category codes

Error Codes (API)

ExportTypeDescription
HaciendaRejectionCodeEnumHacienda rejection reason codes
REJECTION_CODE_DESCRIPTIONSObjectHuman-readable rejection descriptions
getRejectionDescription()FunctionMaps rejection code to description
getHttpStatusDescription()FunctionMaps HTTP status to description
isRetryableStatus()FunctionChecks if an HTTP status is retryable

Full Documentation

See the SDK reference, sandbox walkthrough, and production integration guide.

Migrating to 0.4.0

See migration guidance for required provider IDs, strict XSD validation, request deadlines, cancellation, and submission retry behavior.

Exact decimal ordinary FE (additive)

calculateExactFe and buildExactFacturaXml accept strict ExactFeInput decimal-string facts for the explicitly named FE-domestic-ordinary-iva13-v1 case. They use scaled BigInt and exact decimal XML without Number conversion. Legacy numeric APIs remain unchanged. This is ordinary IVA13 with completely allocated payments, not every fiscal regime. See contract, precision, limits and independent checks.

History wrappers now follow the documented metadata contract and expose raw observed range headers. See the explicit migration and limits before changing a backfill consumer.

Current exact FE credit terms require positive 1–5 digit plazoCredito for 02/10, without changing valid original lexemes. Historical read-only compatibility uses the explicitly separate calculateRetainedExactFe/RetainedExactFeInputSchema contract, never a retained XML/signing builder. See credit-term rules and consumer migration.

Exact ordinary TE source candidate

The additive calculateExactTe / buildExactTiqueteXml and shared ExactTeInputSchema preserve decimal text and actual optional receiver data. They do not fabricate an FE receiver or enable live TE issuance. See the contract, scope and verification limits. This source slice is not a new published version or exact CLI/MCP activation.

Exact ordinary ND source candidate

calculateExactNd / buildExactNotaDebitoXml calculate independently supplied positive FE-reference increments with explicit original-line and reference binding. They preserve original facts and do not establish original acceptance, legal-age eligibility or account effects. See scope and primary rules. This additive SDK/shared source slice is not a version bump or live activation.

Unreleased exact ordinary domestic FEC source

Additive ExactFecInputSchema / calculateExactFec / buildExactFacturaCompraXml preserve actual supplier Emisor and buyer Receptor, require buyer-owned 08 identity/activity and explicit supporting evidence, and calculate ordinary IVA13 decimal strings without Number conversion. This first case is domestic 01–04 with conditions 01/02; foreign 05, used-goods 06/condition 13 and special tax cases remain separately required. Existing family/legacy APIs are unchanged. See exact FEC boundary for independent eligibility/age/response-oracle and release gates.

Unreleased exact credit extensions

calculateExactNcPartial / buildExactNotaCreditoPartialXml calculate explicit correlated credit lines with exact decimal strings. Cumulative remaining credit is external immutable concurrent ledger authority, not the original-total cap. calculateExactFeReplacement / buildExactFacturaReplacementXml build a new FE with a retained institutionally rejected reference, fresh identity and explicit reason 16. Existing APIs are unchanged. See source contracts and independent authority/release limits.

Unreleased current FE validation correction

Current exact FE uses native Unicode issuer/receiver/commercial-name bounds and positive supplied payment allocations; new exact TE shares the positive-payment contract. Historical 0.6–0.9 source/math and calculated-output decoding remain separately readable, without a retained builder or authority to issue. See current rules, genuine registry evidence and version-bound migration.

Unreleased explicit foreign-service IVA13 purchase source

calculateExactFecForeignServiceIva13 / buildExactFacturaCompraForeignServiceIva13Xml preserve actual supplier 05, foreign address/reference 16/reason 11 and buyer-owned 08 identity for an explicitly selected ordinary IVA13 service case. Supplier identity never decides liability or creditability. Used-goods06/condition 13 and other regimes remain unfinished. See source, primary rules and independent gates.

Exact recipient source contract and remaining transport/outcome gates: recipient confirmation.

  • Source-only explicit non-subject personal-used-goods FEC: actual supplier 06/buyer 08, ordinary discounts, exact non-subject amounts; qualification, resale and acceptance remain independent.

版本与发布记录

@dojocoding/hacienda-sdk 共发布 14 个版本,首次发布于 2026/02/23;过去 12 个月发布了 14 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.13.0latest2026/11/0112 天前
0.12.12026/10/2222 天前
0.11.02026/10/2222 天前
0.10.02026/10/1826 天前
0.9.02026/10/1826 天前
0.8.02026/10/1826 天前

关于 @dojocoding/hacienda-sdk 的常见问题

@dojocoding/hacienda-sdk 是什么?

Core SDK for Costa Rica electronic invoicing (Hacienda API v4.4)

如何安装 @dojocoding/hacienda-sdk?

在项目目录运行 npm install @dojocoding/hacienda-sdk,或使用 pnpm add / yarn add / bun add。

@dojocoding/hacienda-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dojocoding/hacienda-sdk 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@dojocoding/hacienda-sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@dojocoding/hacienda-sdk 可以商用吗?

@dojocoding/hacienda-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dojocoding/hacienda-sdk 的下载量有多少?

根据 npm 官方下载统计,@dojocoding/hacienda-sdk 在 2026/10/13 – 2026/11/11 这 30 天内被下载 6,022 次,日均约 201 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dojocoding/hacienda-sdk 还在维护吗?

最新版本 0.13.0 发布于 2026/11/01(12 天前);至今共发布 14 个版本,其中过去 12 个月发布了 14 个;首次发布于 2026/02/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。