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

@emitefy/sdk-node

v0.1.0

Published

SDK oficial Node.js/TypeScript para a API de integração do Emitefy (emissão de NFe/NFC-e).

Readme

Emitefy SDK Node.js/TypeScript

SDK oficial Node.js/TypeScript para a API de integração do Emitefy - emissão de NFe/NFC-e via API REST, para e-commerces, ERPs e outros SaaS que integram emissão fiscal em seus próprios sistemas.

Instalação

npm install @emitefy/sdk-node

Requer Node.js 18+ (usa fetch nativo, sem dependência de runtime extra).

Autenticação

Gere um token de integração no painel Emitefy (Configurações → Tokens)

  • um token de sessão do painel não funciona aqui. Veja Autenticação.
import { Client } from '@emitefy/sdk-node';

const client = new Client('SEU_TOKEN_DE_INTEGRACAO');

Emitindo uma nota fiscal

const nota = await client.emitir(
  {
    tipo: 'nfce', // opcional - "nfe" (padrão) | "nfce"
    empresa_id: 'b1e6c1b0-...',
    natureza_operacao: 'Venda no varejo',
    forma_pagamento: 'pix', // obrigatório só para tipo "nfce"
    itens: [
      {
        codigo: 'SKU001',
        descricao: 'Produto de exemplo',
        ncm: '84713012',
        cfop: '5102',
        unidade: 'UN',
        quantidade: 1,
        valor_unitario: 99.9,
        icms: { situacao_tributaria: '102' },
      },
    ],
  },
  'um-uuid-gerado-pelo-seu-sistema', // idempotencyKey, opcional
);

// nota.status === 'processando' - a transmissão à SEFAZ é assíncrona.
// Acompanhe via webhook ou consultando de novo mais tarde:
const notaAtualizada = await client.consultar(nota.id as string);

Payload completo (destinatário, endereço, múltiplos itens) documentado em Emissão de Notas Fiscais.

O parâmetro opcional idempotencyKey evita emitir a mesma nota duas vezes se uma chamada anterior tiver dado timeout do seu lado sem confirmação - reenviar a mesma chave com o mesmo payload devolve a nota já criada.

Consultando, cancelando e corrigindo

await client.consultar(id);
await client.consultarPorChaveAcesso(chaveDeAcesso); // 44 caracteres

await client.cancelar(id, 'Cliente desistiu da compra antes da entrega.');
await client.cartaCorrecao(id, 'Correção do CFOP do item 1, sem impacto no valor.');

Cancelamento e Carta de Correção só são aceitos para notas autorizada e são assíncronos - o resultado final chega por webhook ou numa nova chamada a consultar().

Baixando XML, DANFE e DANFCE

import { writeFile } from 'node:fs/promises';

await writeFile('nota.xml', await client.baixarXml(id));
await writeFile('danfe.pdf', await client.baixarDanfe(id)); // NFe
await writeFile('danfce.pdf', await client.baixarDanfce(id)); // NFC-e

Só disponíveis para uma nota já autorizada.

Tratamento de erros

Toda falha da API vira um erro tipado, todos estendendo EmitefyApiError (statusCode, type, errors, rawBody):

| Erro | Quando | |---|---| | EmitefyValidationError | 422 - payload inválido ou regra de negócio recusada | | EmitefyAuthError | 401/403 - token inválido ou bloqueado pelo Firewall de IP | | EmitefyNotFoundError | 404 - empresa_id/nota inexistente | | EmitefyRateLimitError | 429 - limite de requisições excedido (retryAfterSeconds) | | EmitefyServerError | 5xx - falha inesperada do Emitefy | | EmitefyConnectionError | Falha de rede antes de qualquer resposta chegar |

import { EmitefyValidationError } from '@emitefy/sdk-node';

try {
  await client.emitir(payload);
} catch (error) {
  if (error instanceof EmitefyValidationError) {
    // error.errors: { 'destinatario.documento': ['O campo documento é obrigatório.'] }
  }
}

Verificando webhooks

import { verifyAndDecodeWebhook, EmitefyWebhookSignatureError } from '@emitefy/sdk-node';

// Exemplo com um handler HTTP genérico - adapte ao seu framework
// (Express, Fastify, etc), sempre usando o corpo bruto (antes do parse).
const payload = verifyAndDecodeWebhook(rawBody, signatureHeader, webhookSecret);
// lança EmitefyWebhookSignatureError se a assinatura não conferir

switch (payload.evento) {
  case 'nota.autorizada':
    // ...
    break;
  case 'nota.rejeitada':
    // ...
    break;
}

O segredo do webhook é exibido uma única vez no painel, ao configurar a URL de callback de uma Empresa Emitente (Empresas → editar → aba Webhooks). Catálogo completo de eventos em WEBHOOK_EVENTS/tipo WebhookEvent e em Webhooks.

Testando contra outro ambiente

const client = new Client('...', { baseUrl: 'http://localhost:8000' });

Desenvolvimento

npm install
npm test
npm run build

Links