@eusilvio/cep-lookup
v2.10.0
Published
A agnostic, performant and flexible CEP lookup library with race strategy and caching.
Readme
@eusilvio/cep-lookup
Core CEP lookup engine with multi-provider race, resilience controls, and metrics.
Installation
npm install @eusilvio/cep-lookupFeatures
- Multi-provider race strategy.
- Cache and rate limiting.
- Retry with exponential backoff.
- Standardized errors with error codes.
- Circuit breaker per provider.
- Provider health score and runtime metrics.
- Event-based observability.
- Offline fallback: state-level answers with zero network, from the official Correios CEP allocation map.
- Zero-network CEP intelligence (
@eusilvio/cep-lookup/offline): CEP↔state validation, allocation checks, state metadata. - Address verification (
@eusilvio/cep-lookup/verify): the typed address checked against its CEP, the house number against the Correios numbering range, and the right CEP found when the typed one is wrong.
Basic Usage
import { CepLookup } from "@eusilvio/cep-lookup";
import { viaCepProvider, brasilApiProvider } from "@eusilvio/cep-lookup/providers";
const lookup = new CepLookup({
providers: [viaCepProvider, brasilApiProvider],
});
const address = await lookup.lookup("01001-000");
console.log(address);Error Handling
import {
CepLookup,
CepNotFoundError,
ProviderTimeoutError,
RateLimitError,
AllProvidersFailedError,
} from "@eusilvio/cep-lookup";
try {
await lookup.lookup("01001000");
} catch (error) {
if (error instanceof CepNotFoundError) {
console.log(error.code); // NOT_FOUND
} else if (error instanceof ProviderTimeoutError) {
console.log(error.code); // TIMEOUT
} else if (error instanceof RateLimitError) {
console.log(error.code); // RATE_LIMITED
} else if (error instanceof AllProvidersFailedError) {
console.log(error.code); // ALL_PROVIDERS_FAILED
}
}Circuit Breaker
const lookup = new CepLookup({
providers: [viaCepProvider, brasilApiProvider],
circuitBreaker: {
enabled: true,
failureThreshold: 3,
cooldownMs: 30_000,
},
});Health and SLA Metrics
const health = lookup.getProviderHealth();
/*
[
{
provider: 'ViaCEP',
score: 0.94,
isOpen: false,
successCount: 12,
failureCount: 1,
avgLatencyMs: 52.11,
...
}
]
*/
const metrics = lookup.getProviderMetrics();
/*
[
{
provider: 'ViaCEP',
requests: 13,
successes: 12,
failures: 1,
timeoutErrors: 0,
notFoundErrors: 1,
avgLatencyMs: 52.11
}
]
*/Bulk Lookup
const results = await lookup.lookupCeps(["01001-000", "99999-999"], 2);API Summary
new CepLookup(options)
providers: required provider list.fetcher: optional custom HTTP fetch function.cache: optional cache implementation.rateLimit:{ requests, per }.staggerDelay: delay before backup providers.retries: retry count after failure.retryDelay: base retry delay in ms.circuitBreaker:{ enabled, failureThreshold, cooldownMs }.staleIfError: serve an expired cache entry when all providers fail.negativeCacheTtl: remember confirmed not-found CEPs.offlineFallback: synthesize a partial state-level address (partial: true,service: "offline") when everything else fails.
Methods
lookup(cep, mapper?)lookupCeps(ceps, concurrency?)searchByAddress(state, city, street, { signal }?)warmup()getProviderHealth()getProviderMetrics()on(event, listener)/off(event, listener)
@eusilvio/cep-lookup/offline (sync, zero network)
resolveCepOffline(cep)- state, state name, region, capital, DDD and IBGE state code.stateFromCep(cep)- UF that owns the CEP, ornull.isCepAllocated(cep)- whether any provider could possibly resolve it.cepMatchesState(cep, uf)- 0ms cross-field form validation.
@eusilvio/cep-lookup/verify
verifyAddress(lookup, address, options?)- status, score, per-field outcome and a suggestion; searches for the right CEP when the typed one conflicts, does not exist or is malformed.compareAddress(address, reference, options?)- the same comparison against an address you already hold, synchronous and zero network.normalizeAddressText(text)- canonical form:"Av. Brig. Faria Lima"becomes"avenida brigadeiro faria lima".parseNumberRange(complement)/isNumberInRange(number, range)- Correios numbering ranges such as"de 612 a 1510 - lado par".
import { verifyAddress } from "@eusilvio/cep-lookup/verify";
const result = await verifyAddress(lookup, {
cep: "01310-100",
street: "Av. Paulista",
number: "1578",
city: "Sao Paulo",
state: "SP",
});
result.status; // "conflict" - 1578 is outside "de 612 a 1510 - lado par"
result.suggestion?.cep; // "01310200"Compatibility and support
- Node.js:
20.x,22.x,24.x - Maintenance policy: SUPPORT.md
Production docs
License
MIT
