npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@grod30/hacienda-js

v0.1.0

Published

Biblioteca TypeScript para facturación electrónica de Costa Rica (Hacienda)

Downloads

6

Readme

@hacienda-js

Biblioteca TypeScript para facturación electrónica de Costa Rica (Ministerio de Hacienda).

Características

  • ✅ Firma digital de documentos XML
  • ✅ Soporte para certificados .p12 y .pem
  • ✅ Envío de documentos al API de Hacienda
  • ✅ Consulta de estado de documentos
  • ✅ Soporte para ambientes de desarrollo y producción
  • ✅ TypeScript con tipos estrictos
  • ✅ Compatible con Node.js, Vite y frameworks modernos

Arquitectura

graph TD
    A[Cliente] --> B[HaciendaAPI]
    B --> C[Firma Digital]
    B --> D[API Hacienda]
    C --> E[Certificado Digital]
    D --> F[Token]
    D --> G[Envío Documentos]
    D --> H[Consulta Estado]

Componentes Principales

  1. HaciendaAPI: Clase principal que maneja la comunicación con el API de Hacienda

    • Gestión de tokens
    • Envío de documentos
    • Consulta de estado
  2. Firma Digital: Módulo para firmar documentos XML

    • Soporte para certificados P12 y PEM
    • Validación de certificados
    • Manejo de errores
  3. XML: Utilidades para manejo de documentos XML

    • Validación de estructura
    • Transformación de datos

Requisitos

  • Node.js 14.x o superior
  • npm 6.x o superior

Instalación

# Usando npm
npm install @hacienda-js

# Usando yarn
yarn add @hacienda-js

# Usando pnpm
pnpm add @hacienda-js

Configuración del Proyecto

  1. Instalar dependencias:
npm install
  1. Compilar el proyecto:
npm run build
  1. Ejecutar pruebas:
npm test

Guía de Uso

1. Configuración Inicial

import { HaciendaAPI, signXml } from '@hacienda-js';

// Crear instancia del API
const api = new HaciendaAPI({
  apiUrl: 'https://api.hacienda.go.cr/fe/ae',
  clientId: 'api-stag',
  environment: 'desarrollo' // o 'produccion'
});

2. Autenticación

// Obtener token de acceso
const token = await api.getToken('[email protected]', 'contraseña');

3. Firma Digital

// Firmar documento XML
const signedXml = await signXml(facturaXml, {
  certPath: './certificado.p12', // o './certificado.pem'
  password: 'contraseña-del-certificado',
  certType: 'p12' // o 'pem'
});

4. Envío de Documentos

// Enviar documento a Hacienda
const response = await api.sendDocument(signedXml, token);

// Consultar estado
const status = await api.checkStatus(response.clave, token);

Manejo de Errores

try {
  const signedXml = await signXml(facturaXml, options);
} catch (error) {
  if (error.message === 'Invalid certificate type') {
    // Manejar error de tipo de certificado inválido
  } else if (error.message === 'File not found') {
    // Manejar error de archivo no encontrado
  }
}

Estructura del Proyecto

hacienda-js/
├── src/
│   ├── api/        # Comunicación con API de Hacienda
│   ├── signature/  # Firma digital de documentos
│   ├── types/     # Definiciones de tipos TypeScript
│   ├── xml/       # Utilidades para manejo de XML
│   └── __tests__/ # Pruebas unitarias
├── dist/          # Código compilado
├── examples/      # Ejemplos de uso
└── docs/          # Documentación adicional

Dependencias Principales

  • xml-crypto: Firma digital de documentos XML
  • axios: Cliente HTTP para comunicación con API
  • typescript: Soporte para tipos estáticos
  • jest: Framework de pruebas

Documentación Adicional

Pruebas

# Ejecutar todas las pruebas
npm test

# Ver cobertura de pruebas
npm run test:coverage

# Ejecutar pruebas en modo watch
npm run test:watch

Flujo de Trabajo

sequenceDiagram
    participant C as Cliente
    participant A as HaciendaAPI
    participant H as Hacienda

    C->>A: Crear instancia
    C->>A: Obtener token
    A->>H: Solicitar token
    H-->>A: Token
    A-->>C: Token

    C->>A: Firmar documento
    A-->>C: Documento firmado

    C->>A: Enviar documento
    A->>H: POST /recepcion
    H-->>A: Respuesta
    A-->>C: Estado envío

    C->>A: Consultar estado
    A->>H: GET /recepcion/{clave}
    H-->>A: Estado documento
    A-->>C: Estado documento

Licencia

Este proyecto está bajo la Licencia MIT - vea el archivo LICENSE para más detalles.

La Licencia MIT es una licencia de software permisiva que permite:

✅ Uso comercial ✅ Modificación ✅ Distribución ✅ Uso privado

Sin ninguna garantía y con la única obligación de incluir la nota de copyright y la licencia en cualquier copia del software/código.

Esto significa que puedes:

  • Usar este software en proyectos comerciales
  • Modificar el código fuente
  • Distribuir el software original o modificado
  • Incluirlo como dependencia en tu proyecto

Solo necesitas mantener el aviso de copyright y la licencia en cualquier copia o parte sustancial del software.

Contribuir

  1. Fork el repositorio
  2. Crea una rama para tu feature (git checkout -b feature/amazing-feature)
  3. Commit tus cambios (git commit -m 'Add amazing feature')
  4. Push a la rama (git push origin feature/amazing-feature)
  5. Abre un Pull Request

Soporte

Si encuentras un bug o tienes una sugerencia, por favor abre un issue en el repositorio.