Skip to content

About

MIT · The Brazilian data toolkit for TypeScript — validate 18 document types and query 17 government datasets (IBGE, Bacen, CNAE, NCM, CFOP, Incoterms…) entirely offline. Zero runtime deps, tree-shakeable, never throws.

Resources

Code of conduct

Contributing

Security policy

Stars

9 stars

Watchers

0 watching

Forks

Latest commit

 

History

386 Commits

Folders and files

Repository files navigation

BR Validators

License: MIT OpenSSF Best Practices GitHub release Playground

100% open-source (MIT) monorepo — TypeScript library, terminal CLI, and web playground for formatting and validating Brazilian document identifiers. Algorithms trace to official primary sources (Receita Federal, Bacen, CONTRAN, Correios, SEFAZ).

🚀 Playground interativo: experimente no navegador em open-data-brazil.github.io/br-validators — validação 100% client-side sem envio de dados, com gerador de testes, temas claro/escuro e consultas offline.

Surface Package / URL
Library @br-validators/core — br-validators-core-<version>.tgz on GitHub Releases
CLI @br-validators/cli — br-validators-cli-<version>.tgz on GitHub Releases
Zod @br-validators/zod — br-validators-zod-<version>.tgz on GitHub Releases
React Hook Form @br-validators/react-hook-form — br-validators-react-hook-form-<version>.tgz on GitHub Releases
Express / Fastify @br-validators/express — br-validators-express-<version>.tgz on GitHub Releases
Vue 3 @br-validators/vue — br-validators-vue-<version>.tgz on GitHub Releases
Documentation docs.br-validators.dev — VitePress deep reference (README = quick start)
Playground open-data-brazil.github.io/br-validators — client-side only, no PII sent to server

Reference datasets (IBGE, Bacen banks, DDD lookup, national holidays, CNAE, CFOP, CST, LC 116, eSocial categorias, NCM, CBO, natureza jurídica, NBS, CEST, moedas, PTAX cotações, países Bacen, NF-e cUF, IRPF / INSS tables, SELIC meta, ISS municipal top 500 PIB, Incoterms, portos, aeroportos, ANP fuel prices) are embedded offline and refreshed daily (00:00 Brasília) — see docs/DATA-FRESHNESS.md. CST, LC 116, eSocial, and ISS municipal use manual maintainer refresh (pnpm fetch:data:cst, pnpm fetch:data:lc116, pnpm fetch:data:esocial, pnpm fetch:data:iss-municipal). Critical source failures: data/refresh-reports/CRITICAL-ALERTS.md.

Distribution: since v1.10.1-data.34 every package is published only as a GitHub Release asset (npm pack tarballs + reference data) — no npm registry, no token. Versions up to 1.10.1 remain on npm but are no longer updated. The unscoped npm name br-validators belongs to another project.


Install

Pick a tag from GitHub Releases — each release attaches every package as an npm pack tarball. npm, pnpm, yarn and bun install straight from the URL (the lockfile pins the tarball integrity).

Library (Node, Bun, bundlers)

VERSION=1.10.1-data.34   # any tag from the Releases page, without the leading "v"
npm install "https://github.com/open-data-brazil/br-validators/releases/download/v$VERSION/br-validators-core-$VERSION.tgz"
# or
pnpm add "https://github.com/open-data-brazil/br-validators/releases/download/v$VERSION/br-validators-core-$VERSION.tgz"

CLI

npm install -g "https://github.com/open-data-brazil/br-validators/releases/download/v$VERSION/br-validators-cli-$VERSION.tgz"
br-validators --help

Adapters

Attached to the same release (br-validators-zod-…, br-validators-react-hook-form-…, br-validators-express-…, br-validators-vue-…). Their @br-validators/core dependency points at the core tarball of that same release, so no registry lookup happens.

Reference data only

Every release also ships br-validators-data-<version>.tar.gz (all embedded datasets + metadata.json), catalog.json (capture date, record counts and SHA-256 per file) and SHA256SUMS. The newest catalog is always at releases/latest/download/catalog.json.


Use in your project

Validate and format (barrel import)

import { validateCnpj, formatCnpj, validateCpf } from '@br-validators/core';

const cnpj = validateCnpj('12ABC34501DE35'); // RFB FAQ Q14 golden vector
if (cnpj.ok) {
  console.log(cnpj.value); // canonical stripped value
}

const formatted = formatCnpj('12ABC34501DE35');
// { ok: true, formatted: '12.ABC.345/01DE-35' }

validateCpf('12345678909'); // never throws — check result.ok

Tree-shake with subpath imports

import { validateCep } from '@br-validators/core/cep';
import { validatePixKey } from '@br-validators/core/pix';
import { validateInscricaoEstadual } from '@br-validators/core/inscricao-estadual';

validateCep('01310100');
validatePixKey('[email protected]');
validateInscricaoEstadual('110042490114', { uf: 'SP' });

Bundle size (gzipped)

Measured @br-validators/[email protected] with pnpm measure:bundle-sizes (esbuild ESM bundle per subpath). Reference-data subpaths include embedded JSON; some validators (e.g. cep, sanitize) also bundle shared core dependencies when tree-shaken alone.

Subpath Raw (esbuild) Gzip Notes
@br-validators/core/cpf 4.0 KB 1.5 KB validator only
@br-validators/core/cnpj 6.8 KB 2.0 KB validator only
@br-validators/core/cep 2340.8 KB 161.8 KB validator only
@br-validators/core/ncm 914.6 KB 142.2 KB includes embed
@br-validators/core/cfop 100.3 KB 9.4 KB includes embed
@br-validators/core/cst 19.1 KB 3.4 KB includes embed
@br-validators/core/pix 17.6 KB 3.9 KB validator only
@br-validators/core/ptax 214.2 KB 22.4 KB includes embed
@br-validators/core/ibge 392.6 KB 60.5 KB includes embed
@br-validators/core/sanitize 2995.5 KB 219.4 KB platform utilities

Full table (all 62 subpaths): data/bundle-sizes/subpath-sizes.md. Regenerate after core changes: pnpm measure:bundle-sizes.

Form handler pattern (never trust client input)

import { validateCpf, stripCpf } from '@br-validators/core/cpf';

function parseCpfField(raw: string) {
  const result = validateCpf(raw);
  if (!result.ok) {
    return { error: result.message, code: result.code };
  }
  return { cpf: result.value, display: stripCpf(raw) };
}

Next.js / React (client or server)

'use client';

import { validateCnpj, formatCnpj } from '@br-validators/core/cnpj';
import { useState } from 'react';

export function CnpjField() {
  const [input, setInput] = useState('');
  const result = input ? validateCnpj(input) : null;
  const formatted = result?.ok ? formatCnpj(result.value) : null;

  return (
    <div>
      <input value={input} onChange={(e) => setInput(e.target.value)} />
      {formatted?.ok && <p>Valid: {formatted.formatted}</p>}
      {result && !result.ok && <p>{result.message}</p>}
    </div>
  );
}

CI / shell scripts

br-validators cnpj validate "$CNPJ" --quiet || exit 1
br-validators ie validate "$IE" --uf SP --json

Requires Node ≥ 18. ESM only ("type": "module"). Zero runtime dependencies.


Supported document types

Type Library import CLI Playground
CNPJ (numeric + alphanumeric) @br-validators/core/cnpj br-validators cnpj … /cnpj
CPF @br-validators/core/cpf br-validators cpf … /cpf
CEP @br-validators/core/cep br-validators cep … /cep
Telefone (Anatel) @br-validators/core/telefone br-validators telefone … /telefone
CNH @br-validators/core/cnh br-validators cnh … /cnh
RENAVAM @br-validators/core/renavam br-validators renavam … /renavam
Título de eleitor @br-validators/core/titulo-eleitor br-validators titulo … /titulo-eleitor
Processo judicial CNJ @br-validators/core/processo-judicial br-validators processo-judicial … /processo-judicial
RG (identity card, per-UF) @br-validators/core/rg br-validators rg … --uf SP /rg
NF-e chave de acesso @br-validators/core/nfe-chave br-validators nfe … /nfe-chave
License plate (Mercosul + legacy) @br-validators/core/placa br-validators placa … /placa
PIS / PASEP / NIS @br-validators/core/pis-pasep br-validators pis-pasep … /pis
PIX key @br-validators/core/pix br-validators pix … /pix
BR Code (PIX QR) @br-validators/core/brcode br-validators brcode … /brcode
Boleto cobrança (Situação 1 + 2) @br-validators/core/boleto br-validators boleto … /boleto
Boleto arrecadação (48/44, product 8) @br-validators/core/boleto br-validators boleto … /boleto
Credit card (Luhn / ISO 7812) @br-validators/core/cartao-credito br-validators cartao … /cartao-credito
Inscrição Estadual (27 UFs) @br-validators/core/inscricao-estadual br-validators ie … --uf SP /ie
IE SP produtor rural @br-validators/core/inscricao-estadual-produtor-rural br-validators ie … (auto P) /ie
Platform APIs see below partial partial

Platform APIs (@br-validators/core)

API Subpath CLI Playground Purpose
detect() /detect br-validators detect … /detect Auto-classify raw input
sanitize() /sanitize br-validators sanitize <type> … /sanitize ETL fixes + validate
mask() /mask br-validators mask <type> … via format actions Unified display mask
compare() /compare br-validators compare <type> … /compare Normalized equality
batch() /batch br-validators batch <type> … /batch Bulk validate + summary
diff() /diff br-validators diff <type> … /diff Field-level structural diff
generate() /generate br-validators generate … /generate Synthetic test fixtures — 17/18 document types (alphanumeric CPF blocked until RFB spec)
import { compare, batch, diff, mask } from '@br-validators/core';

compare('123.456.789-09', '12345678909', 'cpf'); // { equal: true }
batch(['12345678909', 'bad'], 'cpf');             // { valid, invalid, summary }
diff('12345678909', '12345678901', 'cpf');        // { changed, fields: [{ field: 'dv', … }] }
mask('12345678909', 'cpf');                       // { ok: true, formatted: '123.456.789-09' }

PIX static QR Code (playground)

The playground /pix builds static PIX BR Code payloads (Bacen EMV TLV + CRC16) from a validated PIX key:

Mode Amount field Use case
Permanent (static) Leave empty Payer chooses the amount at payment time
Fixed value e.g. 10.50 QR encodes tag 54 with the transaction amount

Payload is validated with validateBrCode before rendering the QR image. Official sources: Bacen Manual BR Code, Manual de Padrões PIX.

Core library ships buildStaticPixBrCode, validateBrCode / parseBrCode, and computeCrc16Ccitt via @br-validators/core/brcode. QR image rendering remains playground-only (QrCodePanel on /pix).

Official sources per type: docs/OFFICIAL-SOURCES.md

Reference data (offline lookup)

Government classification tables embedded in the library — zero runtime fetch, tree-shakeable subpaths, daily freshness (ANP LPC weekly).

Dataset Library import CLI Playground Key APIs Official source
IBGE states + municipalities @br-validators/core/ibge ibge lookup · ibge list /data/ibge getEstados, getMunicipios, getMunicipioPorCodigo IBGE localidades
Bacen STR banks @br-validators/core/bancos bancos lookup · bancos list /data/bancos getBancos, getBancoPorCodigo, getBancoPorIspb Bacen STR CSV
ANAC public aerodromos @br-validators/core/aeroportos aeroportos lookup /data/logistics getAeroportos, getAeroportoPorIata, getAeroportoPorIcao, getAeroportosPorMunicipio ANAC aeródromos CSV
ANTAQ port installations @br-validators/core/portos portos lookup /data/logistics getPortoPorCodigo, searchPortos, getPortosPorMunicipio ANTAQ instalações portuárias zip
ANP fuel prices (LPC) @br-validators/core/anp-combustiveis — /data/logistics getAnpPrecosMedios, getAnpPrecosMediosPorIbge, getAnpSemanaAtual ANP levantamento LPC
TSE ↔ IBGE municipality codes @br-validators/core/tse-municipios tse-municipios lookup /data/ibge (cross-ref) getMunicipioIbgePorCodigoTse, getCodigosTsePorMunicipio TSE municipio_tse_ibge.zip
DDD geographic lookup @br-validators/core/telefone ddd lookup — getDddInfo Anatel DDD panel
National holidays @br-validators/core/feriados feriados list --year /data/calendar isFeriadoNacional, getFeriadosNacionais, getProximoDiaUtil Lei 662/1949
CNAE 2.3 subclasses @br-validators/core/cnaes cnae lookup · cnae search /data/fiscal getCnaePorCodigo, searchCnaes IBGE CNAE API
CFOP fiscal operations @br-validators/core/cfop cfop lookup · cfop search /data/fiscal getCfopPorCodigo, searchCfop CONFAZ CFOP
CST (ICMS, IPI, PIS, COFINS) @br-validators/core/cst — /data/fiscal getCstIcmsPorCodigo, getCstIpiPorCodigo, searchCstIcms RFB SPED CST tables
LC 116 ISS services @br-validators/core/lc116 — /data/fiscal getLc116PorCodigo, searchLc116 LC 116/2003 Planalto
eSocial (categorias + rubricas) @br-validators/core/esocial — /data/payroll getEsocialCategoriaPorCodigo, getEsocialRubricaPorCodigo, searchEsocialRubricas eSocial S-1.3 Tabelas
NCM Mercosur codes @br-validators/core/ncm ncm lookup · ncm search /data/fiscal getNcmPorCodigo, searchNcm Siscomex NCM JSON
Natureza jurídica (CNPJ) @br-validators/core/natureza-juridica natureza-juridica lookup /data/fiscal getNaturezaJuridicaPorCodigo RFB Naturezas.zip
NBS (NFSe) @br-validators/core/nbs nbs lookup /data/fiscal getNbsPorCodigo, searchNbs NFSe Anexo B NBS2 xlsx
CEST (ST) @br-validators/core/cest cest lookup /data/fiscal getCestPorCodigo, getCestPorNcm, searchCest CONFAZ ICMS 142/2018
ISO 4217 + Bacen PTAX moedas @br-validators/core/moedas moedas lookup /data/trade getMoedaPorCodigo, searchMoedas Bacen PTAX Moedas API
Bacen PTAX Fechamento @br-validators/core/ptax ptax lookup · ptax historico /data/trade getPtaxCotacao, getPtaxHistorico, getPtaxUltimoDiaUtil (+ dataReferencia, isStale) Bacen Olinda PTAX API
NF-e Bacen country codes @br-validators/core/paises-bacen paises-bacen lookup /data/trade getPaisPorCodigoBacen, getPaisesBacen NF-e country table
NF-e cUF (IBGE state codes) @br-validators/core/nfe-cuf nfe-cuf lookup /data/fiscal getCufPorCodigo, lookupCufPorCodigo NF-e cUF table
IRPF progressive brackets @br-validators/core/irpf irpf tabela · irpf calc /data/payroll getIrpfTabelaProgressiva, calcularIrpfMensal RFB IRPF tables
INSS contribution brackets @br-validators/core/inss inss tabela · inss calc /data/payroll getInssTabelaContribuicao, calcularInssMensal INSS contribution rates
Bacen SELIC meta @br-validators/core/selic selic /data/finance getSelicMeta, getSelicMetaPorData Bacen SGS série 432
ISS municipal rates (top 500 PIB) @br-validators/core/iss-municipal iss-municipal lookup · list · search [--uf] /data/fiscal getIssMunicipalPorIbge — check fonte + warning (473/500 estimativa) IBGE SIDRA PIB 5938
ICC Incoterms 2020 @br-validators/core/incoterms incoterms lookup /data/trade getIncotermPorCodigo, getIncoterms ICC Incoterms rules
CBO 2002 occupations @br-validators/core/cbo cbo lookup · cbo search /data/fiscal getCboPorCodigo, searchCbo MTE CBO CSV
CEP prefix lookup @br-validators/core/cep cep faixa — getCepFaixaInfo, getCepFaixas IBGE CNEFE 2022
Transparency catalog @br-validators/core/data-catalog — /data/catalog getDataCatalog, getDatasetMetadata See DATA-FRESHNESS.md

PTAX embed: last 90 business days (janelaDiasUteis: 90) — not live Bacen. Every cotacao includes dataReferencia and isStale; when stale, warning advises against settlement without a live fetch. Use getPtaxHistorico(moeda, { desde, ate }) for FX variation over contract periods. Details: DATA-FRESHNESS.md (row Bacen PTAX Fechamento).

getAll*(): lookup modules export getAll<Type>() for full embedded tables — see Listing reference data below. Full API list: docs.br-validators.dev/api-reference.

import { getNcmPorCodigo } from '@br-validators/core/ncm';
import { getCfopPorCodigo } from '@br-validators/core/cfop';
import { getCstIcmsPorCodigo } from '@br-validators/core/cst';
import { getLc116PorCodigo } from '@br-validators/core/lc116';
import { getEsocialCategoriaPorCodigo } from '@br-validators/core/esocial';
import { getCnaePorCodigo } from '@br-validators/core/cnaes';
import { getNaturezaJuridicaPorCodigo } from '@br-validators/core/natureza-juridica';
import { getNbsPorCodigo } from '@br-validators/core/nbs';
import { getCestPorCodigo } from '@br-validators/core/cest';
import { getMoedaPorCodigo } from '@br-validators/core/moedas';
import { getPtaxUltimoDiaUtil, getPtaxHistorico } from '@br-validators/core/ptax';
import { getIssMunicipalPorIbge } from '@br-validators/core/iss-municipal';
import { getPaisPorCodigoBacen } from '@br-validators/core/paises-bacen';
import { getIncotermPorCodigo } from '@br-validators/core/incoterms';
import { getAeroportoPorIata } from '@br-validators/core/aeroportos';
import { getPortoPorCodigo } from '@br-validators/core/portos';
import { getAnpPrecosMedios } from '@br-validators/core/anp-combustiveis';
import { getDataCatalog } from '@br-validators/core/data-catalog';

getNcmPorCodigo('01012100');   // NCM leaf code lookup
getCfopPorCodigo('1102');      // fiscal operation code
getCstIcmsPorCodigo('00');     // ICMS CST — tributada integralmente
getLc116PorCodigo('1.01');    // ISS — análise e desenvolvimento de sistemas
getEsocialCategoriaPorCodigo('101'); // eSocial — empregado geral (CLT)
getCnaePorCodigo('6201501');   // economic activity (CNPJ complement)
getNaturezaJuridicaPorCodigo('2062'); // Ltda. legal nature
getNbsPorCodigo('1.1502.50.00');      // NFSe service code
getCestPorCodigo('0302100');          // ST specifier
getMoedaPorCodigo('BRL');             // Real Brasileiro

const ptax = getPtaxUltimoDiaUtil('USD');
ptax.dataReferencia;                 // '2026-06-26' — always expose to callers
ptax.isStale;                        // true when embed > 1 business day old
ptax.warning;                        // present when stale — not for settlement without live fetch

getPtaxHistorico('USD', { desde: '2026-06-01', ate: '2026-06-26' });
// readonly PtaxCotacaoResult[] — each row has dataReferencia, isStale, warning

const iss = getIssMunicipalPorIbge(3509502); // Campinas — estimativa row
if (iss?.fonte === 'estimativa') {
  console.warn(iss.warning);       // do not use estimated alíquota for NFSe emission
}

getPaisPorCodigoBacen('1058');        // Brasil (NF-e cPais)
getIncotermPorCodigo('FOB');          // Free On Board
getAeroportoPorIata('GRU');            // Guarulhos — SP
getPortoPorCodigo('BRSSZ');           // Santos organized port
getAnpPrecosMedios({ uf: 'SP', municipio: 'São Paulo', produto: 'GASOLINE_REGULAR' });
getDataCatalog();              // all dataset metadata + capture dates

Listing reference data (getAll*)

Every lookup module exposes getAll*() to iterate the full embedded table (tree-shakeable per subpath):

import { getAllNcm } from '@br-validators/core/ncm';
import { getAllCfop } from '@br-validators/core/cfop';
import { getAllCstIcms } from '@br-validators/core/cst';

const allNcm = getAllNcm();       // readonly NcmRow[]
const allCfop = getAllCfop();
const allIcms = getAllCstIcms();

Other examples: getAllBancos, getAllEsocialCategorias, getAllIssMunicipal, getAllAeroportos. Deprecated plural names (getNcms, getCfops) remain until v2.0 — see MIGRATION.md.


Develop from source

git clone https://github.com/open-data-brazil/br-validators.git
cd br-validators
pnpm install          # builds @br-validators/core via prepare
pnpm verify           # lint + typecheck + 100% coverage + build
pnpm --filter @br-validators/playground dev   # http://localhost:3000

Monorepo layout

packages/br-validators/   # @br-validators/core — library (GitHub Release tarball)
apps/cli/                 # @br-validators/cli — terminal
apps/playground/          # Web UI (Vercel)

Every shipped type exists in library + CLI + playground. See docs/DELIVERY-SURFACES.md.


Help wanted — contribute

BR Validators is 100% MIT open source. We need community help to close coverage gaps with official sources only — no guessed algorithms.

Area Gap How to help
ISS municipal rates ~5.070 municipalities not in embed; 473 estimation-only rows Issue template iss-municipal-contribution · docs/COVERAGE-GAPS.md
RG check digits 24 UFs format-only (no published official DV) Issue template rg-dv-upgrade · RG contributor guide
Data sources Endpoint moves / fetch failures Issue template data_source · CRITICAL-ALERTS.md

Before opening a PR: read CONTRIBUTING.md, docs/OFFICIAL-SOURCES.md, and AGENTS.md. Every change needs golden test vectors, CHANGELOG.md entry, and pnpm verify passing (lint, typecheck, 100% coverage on packages/br-validators/src/**).

Regenerate gap lists after ISS/IBGE updates: pnpm generate:coverage-gaps


Documentation

Doc Description
packages/br-validators/README.md Library install + API quick start
apps/cli/README.md CLI commands
docs/LIBRARY-API.md Public API contract
docs/OFFICIAL-SOURCES.md RFB, Bacen, CONTRAN, SEFAZ sources
apps/docs/ VitePress site — docs.br-validators.dev (API synced from LIBRARY-API.md)
docs/community/RG-GOOD-FIRST-ISSUES.md RG 27/27 UFs shipped — DV algorithm upgrades (good first issue)
docs/COVERAGE-GAPS.md Municipalities without ISS embed / official municipal rate; RG DV gaps
CHANGELOG.md Release history
MIGRATION.md v1.x → v2.0 breaking-change guide (lookup + deprecated getters)
docs/VERSIONING.md SemVer policy and deprecation windows
docs.br-validators.dev/api-reference Auto-generated TypeDoc signatures (pnpm docs:api)

Current release

All six packages share one version and are attached to every GitHub Release — see the latest release.

Package Release asset
@br-validators/core br-validators-core-<version>.tgz
@br-validators/cli br-validators-cli-<version>.tgz
@br-validators/zod br-validators-zod-<version>.tgz
@br-validators/react-hook-form br-validators-react-hook-form-<version>.tgz
@br-validators/express br-validators-express-<version>.tgz
@br-validators/vue br-validators-vue-<version>.tgz
Reference data br-validators-data-<version>.tar.gz + catalog.json

v1.10.1 — Stable roll-up since v1.10.0 (data.47–data.49 never reached npm): ISS municipal upgrades, playground workspaces, CI reliability fixes. See CHANGELOG.md.

See CHANGELOG.md for release notes.

Known gaps

See docs/COVERAGE-GAPS.md for the full index (machine-readable JSON under data/coverage-gaps/).

Gap Status
ISS municipal — 5.071 municipalities not embedded Help wanted — cite municipal legislation
ISS municipal — 473 estimation-only rows Same — replace LC 116 band with verified leiUrl
RG DV — 24 UFs format-only RG contributor guide
Alphanumeric CPF Blocked — RFB spec not published
@br-validators/adapters-correios Planned — CEP HTTP lookup

License

MIT — permanently free and open source. See docs/OPEN-SOURCE.md.

About

MIT · The Brazilian data toolkit for TypeScript — validate 18 document types and query 17 government datasets (IBGE, Bacen, CNAE, NCM, CFOP, Incoterms…) entirely offline. Zero runtime deps, tree-shakeable, never throws.

Resources

Code of conduct

Contributing

Security policy

Stars

9 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages