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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@alijunior/nuvemfiscal-sdk-node

v2.3.3

Published

SDK em Typescript para comunicação com a api Nuvem Fiscal

Downloads

774

Readme

SDK em TypeScript/Node.js para integração com a API Nuvem Fiscal, com tipos gerados a partir do OpenAPI e client HTTP enxuto (fetch/axios).

✅ Destaques

  • Tipagem forte (params, body e response) direto do OpenAPI
  • Client simples: NuvemFiscalClient
  • Adapters: FetchHttpClient (nativo) e AxiosHttpClient (opcional)
  • Novos helpers de token:
    • getClientCredentialsToken (objeto completo do token)
    • getAccessTokenString (só a string do token; wrapper)
    • getNuvemFiscalTokenForBrowser (para testes no browser — não usar em produção)

Instalação

pnpm add @alijunior/nuvemfiscal-sdk-node

ou

npm i @alijunior/nuvemfiscal-sdk-node

ou

yarn add @alijunior/nuvemfiscal-sdk-node

Requisitos

  • Node >= 18 (fetch nativo)
  • TypeScript >= 5 (recomendado)

Variáveis de ambiente (para exemplos)

Crie um .env na raiz do seu projeto:

TOKEN_URL=https://auth.nuvemfiscal.com.br/oauth/token
CLIENT_ID=SEU_CLIENT_ID
CLIENT_SECRET=SEU_CLIENT_SECRET
API_BASE=https://api.nuvemfiscal.com.br
SCOPE=empresa conta cnpj cep nfce nfe

Helpers de Token

1) getClientCredentialsToken (Node – objeto completo)

Fluxo OAuth2 Client Credentials. Retorna { access_token, expires_in, ... }.
Suporta authStyle: "basic" | "body" | "both" | "auto" (padrão: "auto").

import {
  getClientCredentialsToken,
  type ClientCredentialsInput,
} from "@alijunior/nuvemfiscal-sdk-node";

const input: ClientCredentialsInput = {
  tokenUrl: process.env.TOKEN_URL!,
  clientId: process.env.CLIENT_ID!,
  clientSecret: process.env.CLIENT_SECRET!,
  scope: process.env.SCOPE,
  authStyle: "auto", // tenta basic e cai para Body em 400/401
};

const token = await getClientCredentialsToken(input);
console.log("access_token:", token.access_token, "exp:", token.expires_in);

2) getAccessTokenString (Node – apenas a string)

Wrap prático quando você só precisa do access_token.

import { getAccessTokenString } from "@alijunior/nuvemfiscal-sdk-node";

const accessToken = await getAccessTokenString({
  tokenUrl: process.env.TOKEN_URL!,
  clientId: process.env.CLIENT_ID!,
  clientSecret: process.env.CLIENT_SECRET!,
  scope: process.env.SCOPE!,
});

3) getNuvemFiscalTokenForBrowser (Browser – somente testes)

Útil para provar fluxo no front localmente. Não use em produção (expõe o client_secret).

import { getNuvemFiscalTokenForBrowser } from "@alijunior/nuvemfiscal-sdk-node";

const accessToken = await getNuvemFiscalTokenForBrowser(
  "CLIENT_ID",
  "CLIENT_SECRET",
  "https://auth.nuvemfiscal.com.br/oauth/token", // default
  "empresa conta cnpj cep nfce nfe" // default
);

Usando o Client com o Token

Com fetch (nativo Node 18+)

import {
  NuvemFiscalClient,
  FetchHttpClient,
  getAccessTokenString,
} from "@alijunior/nuvemfiscal-sdk-node";

const accessToken = await getAccessTokenString({
  tokenUrl: process.env.TOKEN_URL!,
  clientId: process.env.CLIENT_ID!,
  clientSecret: process.env.CLIENT_SECRET!,
  scope: process.env.SCOPE!,
});

const http = new FetchHttpClient({
  headers: { Authorization: `Bearer ${accessToken}` },
});

const api = new NuvemFiscalClient(http, process.env.API_BASE!);

// CEP
const cep = await api.consultarCep({ Cep: "04513010" });
console.log("CEP:", cep);

// CNPJ (exemplo)
const cnpjList = await api.listarCnpj({
  cnae_principal: "6201501",
  municipio: "3550308",
  natureza_juridica: "2062",
  $top: 5,
  $skip: 0,
  $inlinecount: false,
});
console.log("CNPJ:", cnpjList);

Com axios (opcional)

import axios from "axios";
import {
  NuvemFiscalClient,
  AxiosHttpClient,
  getAccessTokenString,
} from "@alijunior/nuvemfiscal-sdk-node";

const accessToken = await getAccessTokenString({
  tokenUrl: process.env.TOKEN_URL!,
  clientId: process.env.CLIENT_ID!,
  clientSecret: process.env.CLIENT_SECRET!,
});

const axiosInstance = axios.create({
  headers: { Authorization: `Bearer ${accessToken}` },
});

const http = new AxiosHttpClient(axiosInstance);
const api = new NuvemFiscalClient(http, process.env.API_BASE!);

// exemplo
const cep = await api.consultarCep({ Cep: "01001000" });

Tratamento de erros (exemplo)

Os adapters levantam Error com status e, se presente, body.

function printHttpError(e: unknown, ctx?: string) {
  const status = (e as any)?.status;
  const msg =
    (e as any)?.body?.error?.message ??
    (e as any)?.body?.message ??
    (e as Error)?.message ??
    String(e);

  console.error(
    `${ctx ? ctx + ": " : ""}${status ? status + " - " : ""}${msg}`
  );
}

try {
  const res = await api.listarCnpj({
    /* ... */
  });
} catch (e) {
  printHttpError(e, "Falha ao listar CNPJ");
}

Tipos úteis (reexportados)

import type {
  CepEndereco,
  CnpjListagem,
  CnpjEmpresa,
  ContaCotaListagem,
  ContaCota,
  EmpresaListagem,
  Empresa,
  EmpresaCertificado,
  NfePedidoEmissao,
  Dfe,
  NfePedidoCancelamento,
  DfeCancelamento,
  EmpresaPedidoCadastroCertificado,
} from "@alijunior/nuvemfiscal-sdk-node";

Os tipos de params/query/body/response dos métodos são inferidos das operations/paths do OpenAPI. Se o contrato mudar, o TypeScript aponta onde ajustar.


Download de binarios

import { writeFile } from "node:fs/promises";
import { arrayBufferToNodeBuffer } from "../types/nuvem-fiscal-api.httpclient";

// Node: para salvar o arquivo

const pdf = await api.baixarPdfNfe({ id: "..." });
await writeFile("nota.pdf", arrayBufferToNodeBuffer(pdf));
// Browser: para baixar

const ab = await api.baixarPdfNfe({ id: "..." });
const blob = new Blob([ab], { type: "application/pdf" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "nota.pdf";
a.click();
URL.revokeObjectURL(url);

Desenvolvimento

# exemplos locais (usando .env)
pnpm test

# build da lib
pnpm build

Segurança

  • Nunca exponha CLIENT_SECRET no front em produção.
  • Faça a emissão de token no backend e envie apenas o access_token ao cliente.
  • Rotacione/Revogue credenciais comprometidas.

Licença

MIT