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

@treeunfe/cte

v1.0.10

Published

Operações CTe para Treeunfe DFe

Downloads

524

Readme

Treeunfe DFe 🪄

Biblioteca Node.js open source para integração com webservices da SEFAZ, desenvolvida e mantida pela Treeunfe.

License: GPL-3.0 TypeScript Node.js

📖 Sobre

Treeunfe DFe é uma biblioteca open source desenvolvida e mantida pela empresa Treeunfe, projetada para simplificar a integração com os webservices da SEFAZ. A biblioteca oferece uma solução robusta e modular para automação de processos relacionados a documentos fiscais eletrônicos.

✨ Características

  • 🚀 Open Source: Código aberto e gratuito para uso
  • 🔄 Atualizações Frequentes: Mantida ativamente pela Treeunfe com atualizações regulares
  • 📦 Modular: Instale apenas os módulos que você precisa
  • 🛠️ TypeScript: Totalmente tipado para melhor experiência de desenvolvimento
  • 📚 Documentação Completa: Documentação detalhada e exemplos práticos

🏢 Sobre a Treeunfe

A Treeunfe é uma empresa especializada em soluções fiscais e tributárias. Esta biblioteca é mantida ativamente pela equipe Treeunfe, garantindo atualizações frequentes, correções de bugs e suporte às últimas normas técnicas da SEFAZ.

💬 Comunidade

🎯 Junte-se à nossa comunidade no Discord!

Discord

Estamos aqui para apoiá-lo!

✨ Tire suas dúvidas
🤝 Colabore com a comunidade
🚀 Contribua para o desenvolvimento open source

👉 Clique aqui para entrar no Discord

📦 Instalação

A biblioteca é modular, permitindo instalar apenas os módulos necessários:

# Instalar módulo NFe
npm install @treeunfe/nfe @treeunfe/types @treeunfe/shared

# Instalar módulo NFCe
npm install @treeunfe/nfce @treeunfe/types @treeunfe/shared

# Instalar módulo CTe
npm install @treeunfe/cte @treeunfe/types @treeunfe/shared

# Instalar módulo NFSe
npm install @treeunfe/nfse @treeunfe/types @treeunfe/shared

# Instalar módulo DANFE (geração de PDF)
npm install @treeunfe/danfe

🚀 Início Rápido

Exemplo: NFe

import { NFe, TreeunfeDFeService } from '@treeunfe/nfe';
import { TreeunfeDFeProps } from '@treeunfe/types';
import path from 'path';

const __dirname = path.dirname(new URL(import.meta.url).pathname);

// Inicializar serviço
const treeunfeDFeService = new TreeunfeDFeService();
const nfeHandler = new NFe(treeunfeDFeService);

// Configurar ambiente
await nfeHandler.LoadEnvironment({
  config: {
    dfe: {
      baixarXMLDistribuicao: true,
      pathXMLDistribuicao: "tmp/DistribuicaoDFe/NFe",
      armazenarXMLAutorizacao: true,
      pathXMLAutorizacao: "tmp/Autorizacao/NFe",
      armazenarXMLRetorno: true,
      pathXMLRetorno: "tmp/RequestLogs/NFe",
      armazenarXMLConsulta: true,
      pathXMLConsulta: "tmp/RequestLogs/NFe",
      
      pathCertificado: path.resolve(__dirname, "certificado.pfx"),
      senhaCertificado: "sua_senha_aqui",
      UF: "SP",
      CPFCNPJ: "00000000000000",
    },
    nfe: {
      ambiente: 2, // 1 = Produção, 2 = Homologação
      versaoDF: "4.00",
      tokenCSC: 'seu_token_csc',
      idCSRT: '01'
    },
    lib: {
      connection: {
        timeout: 30000,
      },
      log: {
        exibirLogNoConsole: true,
        armazenarLogs: true,
        pathLogs: 'tmp/Logs/NFe'
      },
      useOpenSSL: false,
      useForSchemaValidation: 'validateSchemaJsBased',
    }
  } as TreeunfeDFeProps
});

// Consultar status do serviço
await nfeHandler.ConsultaStatusServico();

// Consultar protocolo
await nfeHandler.ConsultaProtocolo('00000000000000000000000000000000000000000000');

Exemplo: NFSe

import { NFSe } from '@treeunfe/nfse';
import { TreeunfeDFeService } from '@treeunfe/nfe';
import { TreeunfeDFeProps } from '@treeunfe/types';
import path from 'path';

const __dirname = path.dirname(new URL(import.meta.url).pathname);

// Inicializar serviço
const treeunfeDFeService = new TreeunfeDFeService();
const nfseHandler = new NFSe(treeunfeDFeService);

// Configurar ambiente
await nfseHandler.LoadEnvironment({
  config: {
    dfe: {
      baixarXMLDistribuicao: true,
      pathXMLDistribuicao: "tmp/DistribuicaoDFe/NFSe",
      armazenarXMLAutorizacao: true,
      pathXMLAutorizacao: "tmp/Autorizacao/NFSe",
      armazenarXMLRetorno: true,
      pathXMLRetorno: "tmp/RequestLogs/NFSe",
      
      pathCertificado: path.resolve(__dirname, "certificado.pfx"),
      senhaCertificado: "sua_senha_aqui",
      UF: "SP",
      CPFCNPJ: "00000000000000",
    },
    nfse: {
      ambiente: 2, // 1 = Produção, 2 = Homologação
      versao: "1.00"
    },
    lib: {
      connection: {
        timeout: 30000,
      },
      log: {
        exibirLogNoConsole: true,
        armazenarLogs: true,
        pathLogs: 'tmp/Logs/NFSe'
      },
      useOpenSSL: false,
      useForSchemaValidation: 'validateSchemaJsBased',
    }
  } as TreeunfeDFeProps
});

// Consultar NFSe por chave
await nfseHandler.Consulta({
  chaveAcesso: '00000000000000000000000000000000000000000000'
});

📚 Funcionalidades

NFe (Nota Fiscal Eletrônica)

  • ✅ Autorização de NFe
  • ✅ Consulta de Protocolo
  • ✅ Consulta de Status do Serviço
  • ✅ Distribuição DFe (por NSU, Último NSU ou Chave)
  • ✅ Inutilização de NFe
  • ✅ Recepção de Eventos (Cancelamento, Carta de Correção, EPEC, etc.)
  • ✅ Geração de DANFE

NFCe (Nota Fiscal de Consumidor Eletrônica)

  • ✅ Autorização de NFCe
  • ✅ Consulta de Protocolo
  • ✅ Geração de QR Code
  • ✅ Geração de DANFE

CTe (Conhecimento de Transporte Eletrônico)

  • ✅ Distribuição DFe (por NSU, Último NSU ou Chave)
  • ✅ Download automático de documentos CT-e

NFSe (Nota Fiscal de Serviços Eletrônica)

  • ✅ Autorização de NFSe
  • ✅ Consulta de NFSe
  • ✅ Consulta de Parâmetros Municipais
  • ✅ Registro de Eventos (Cancelamento, etc.)
  • ✅ Distribuição por NSU

📖 Documentação

Para documentação completa, exemplos detalhados e referência da API, acesse:

🔗 Documentação Completa

⚙️ Requisitos

  • Node.js: Versão 16 ou superior
  • Certificado: Certificado A1 (arquivo .pfx)
  • TypeScript: Recomendado (mas não obrigatório)

Validação de Schema

Por padrão, a biblioteca utiliza validação baseada em Java. Para ambientes sem suporte ao JDK (como Vercel, AWS Lambda sem layers), configure:

lib: {
  useForSchemaValidation: 'validateSchemaJsBased'
}

🤝 Contribuindo

Contribuições são bem-vindas! Este é um projeto open source mantido pela Treeunfe, e sua colaboração é muito apreciada.

Como Contribuir

  1. Reportar Bugs: Abra uma issue descrevendo o problema
  2. Sugerir Funcionalidades: Compartilhe suas ideias
  3. Enviar Pull Requests: Contribua com código, documentação ou melhorias
  4. Espalhar a Palavra: Compartilhe o projeto com outros desenvolvedores

Ao Abrir uma Issue

Por favor, inclua as seguintes informações:

## Parametrização
- UF: SP
- Certificado: A1
- Método: NFE_ConsultaStatusServico
- Status: ✅ Funcionando / ❌ Com erro

Inclua também os logs gerados no diretório configurado em pathLogs (arquivos app.jsonl, error.jsonl e http.jsonl).

📝 Licença

Este projeto é licenciado sob a GPL-3.0.

🏢 Mantido por Treeunfe

Desenvolvido e mantido com ❤️ pela equipe Treeunfe.

⭐ Agradecimentos

Agradecemos a todos os contribuidores e usuários que tornam este projeto possível!


Treeunfe DFe - Simplificando a integração com a SEFAZ 🚀