@eusilvio/cep-lookup 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,67 @@
1
+ # Project License
2
+
3
+ This project was developed with the philosophy that knowledge and tools should be accessible to all. I believe that by sharing our work freely, we can empower other creators to build incredible things.
4
+
5
+ That's why I chose the MIT License for this project. In simple terms, this means you have complete freedom to use, modify, and distribute this code, even for commercial purposes, with a single condition: you must keep the original copyright and license notice included.
6
+
7
+ Thank you for your interest and contributions!
8
+
9
+ ---
10
+
11
+ # Licença do Projeto
12
+
13
+ Este projeto foi desenvolvido com a filosofia de que o conhecimento e as ferramentas devem ser acessíveis a todos. Acredito que, ao compartilhar nosso trabalho livremente, podemos capacitar outros criadores a construir coisas incríveis.
14
+
15
+ Por isso, escolhi a Licença MIT para este projeto. Em termos simples, isso significa que você tem total liberdade para usar, modificar e distribuir este código, até mesmo para fins comerciais, com uma única condição: mantenha o aviso de licença e copyright originais.
16
+
17
+ Agradecemos o seu interesse e contribuição!
18
+
19
+ ---
20
+
21
+ ### MIT License
22
+
23
+ Copyright (c) 2025 Silvio Campos
24
+
25
+ Permission is hereby granted, free of charge, to any person obtaining a copy
26
+ of this software and associated documentation files (the "Software"), to deal
27
+ in the Software without restriction, including without limitation the rights
28
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
29
+ copies of the Software, and to permit persons to whom the Software is
30
+ furnished to do so, subject to the following conditions:
31
+
32
+ The above copyright notice and this permission notice shall be included in all
33
+ copies or substantial portions of the Software.
34
+
35
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
38
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
40
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
41
+ SOFTWARE.
42
+
43
+ ---
44
+
45
+ ### Tradução para Português (Apenas para referência)
46
+
47
+ _Aviso: Esta é uma tradução não oficial e serve apenas para facilitar o entendimento. A versão em inglês é a que possui validade legal._
48
+
49
+ Copyright (c) 2025 Silvio Campos
50
+
51
+ É concedida permissão, gratuitamente, a qualquer pessoa que obtenha uma cópia
52
+ deste software e dos arquivos de documentação associados (o "Software"), para negociar
53
+ o Software sem restrições, incluindo, sem limitação, os direitos
54
+ de usar, copiar, modificar, mesclar, publicar, distribuir, sublicenciar e/ou vender
55
+ cópias do Software, e permitir que as pessoas a quem o Software é
56
+ fornecido o façam, sujeito às seguintes condições:
57
+
58
+ O aviso de copyright acima e este aviso de permissão devem ser incluídos em todas as
59
+ cópias ou partes substanciais do Software.
60
+
61
+ O SOFTWARE É FORNECIDO "COMO ESTÁ", SEM GARANTIA DE QUALQUER TIPO, EXPRESSA OU
62
+ IMPLÍCITA, INCLUINDO, MAS NÃO SE LIMITANDO ÀS GARANTIAS DE COMERCIALIZAÇÃO,
63
+ ADEQUAÇÃO A UM FIM ESPECÍFICO E NÃO VIOLAÇÃO. EM NENHUMA CIRCUNSTÂNCIA OS
64
+ AUTORES OU TITULARES DE DIREITOS AUTORAIS SERÃO RESPONSÁVEIS POR QUALQUER REIVINDICAÇÃO, DANOS OU OUTRA
65
+ RESPONSABILIDADE, SEJA EM UMA AÇÃO DE CONTRATO, ILÍCITO CIVIL OU DE OUTRA FORMA, DECORRENTE DE,
66
+ FORA DE OU EM CONEXÃO COM O SOFTWARE OU O USO OU OUTRAS NEGOCIAÇÕES NO
67
+ SOFTWARE.
package/README.md CHANGED
@@ -1,6 +1,7 @@
1
1
  # @eusilvio/cep-lookup
2
2
 
3
3
  [![NPM Version](https://img.shields.io/npm/v/@eusilvio/cep-lookup.svg)](https://www.npmjs.com/package/@eusilvio/cep-lookup)
4
+ [![NPM Unpacked Size](https://img.shields.io/npm/unpacked-size/@eusilvio/cep-lookup)](https://www.npmjs.com/package/@eusilvio/cep-lookup)
4
5
  [![Build Status](https://img.shields.io/github/workflow/status/eusilvio/cep-lookup/CI)](https://github.com/eusilvio/cep-lookup/actions)
5
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
7
 
package/dist/index.js CHANGED
@@ -1,76 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CepLookup = void 0;
4
- exports.lookupCep = lookupCep;
5
- /**
6
- * @function validateCep
7
- * @description Validates and cleans a CEP string. Removes non-digit characters and checks for an 8-digit length.
8
- * @param {string} cep - The CEP string to validate.
9
- * @returns {string} The cleaned, 8-digit CEP string.
10
- * @throws {Error} If the CEP is invalid (not 8 digits after cleaning).
11
- */
12
- function validateCep(cep) {
13
- const cleanedCep = cep.replace(/\D/g, "");
14
- if (cleanedCep.length !== 8) {
15
- throw new Error("Invalid CEP. It must have 8 digits.");
16
- }
17
- return cleanedCep;
18
- }
19
- /**
20
- * @class CepLookup
21
- * @description A class for looking up Brazilian postal codes (CEPs) using multiple providers.
22
- * It queries multiple services simultaneously and returns the response from the fastest one.
23
- */
24
- class CepLookup {
25
- /**
26
- * @constructor
27
- * @param {CepLookupOptions} options - The options for initializing the CepLookup instance.
28
- */
29
- constructor(options) {
30
- this.providers = options.providers;
31
- this.fetcher = options.fetcher || (async (url) => {
32
- const response = await fetch(url);
33
- if (!response.ok) {
34
- throw new Error(`HTTP error! status: ${response.status}`);
35
- }
36
- return response.json();
37
- });
38
- }
39
- /**
40
- * @method lookup
41
- * @description Looks up an address for a given CEP.
42
- * @template T - The expected return type, defaults to `Address`.
43
- * @param {string} cep - The CEP to be queried.
44
- * @param {(address: Address) => T} [mapper] - An optional function to transform the `Address` object into a custom format `T`.
45
- * @returns {Promise<T>} A Promise that resolves to the address in the default `Address` format or a custom format `T` if a mapper is provided.
46
- * @throws {Error} If the CEP is invalid or if all providers fail to find the CEP.
47
- */
48
- async lookup(cep, mapper) {
49
- const cleanedCep = validateCep(cep);
50
- const promises = this.providers.map((provider) => {
51
- const url = provider.buildUrl(cleanedCep);
52
- return this.fetcher(url)
53
- .then((response) => provider.transform(response))
54
- .then((address) => (mapper ? mapper(address) : address));
55
- });
56
- return Promise.any(promises);
57
- }
58
- }
59
- exports.CepLookup = CepLookup;
60
- /**
61
- * @function lookupCep
62
- * @description Backward-compatible function for looking up a CEP. Internally creates a `CepLookup` instance.
63
- * @template T - The expected return type, defaults to `Address`.
64
- * @param {object} options - Options for the lookup.
65
- * @param {string} options.cep - The CEP to be queried.
66
- * @param {Provider[]} options.providers - An array of `Provider` instances.
67
- * @param {Fetcher} [options.fetcher] - The `Fetcher` function. Defaults to global `fetch` if not provided.
68
- * @param {(address: Address) => T} [options.mapper] - An optional function to transform the `Address` object.
69
- * @returns {Promise<T>} A Promise that resolves to the address.
70
- * @throws {Error} If the CEP is invalid or if all providers fail.
71
- */
72
- function lookupCep(options) {
73
- const { cep, providers, fetcher, mapper } = options;
74
- const cepLookup = new CepLookup({ providers, fetcher });
75
- return cepLookup.lookup(cep, mapper);
76
- }
1
+ "use strict";var c=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var l=(e,r)=>{for(var s in r)c(e,s,{get:r[s],enumerable:!0})},f=(e,r,s,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of u(r))!h.call(e,o)&&o!==s&&c(e,o,{get:()=>r[o],enumerable:!(t=a(r,o))||t.enumerable});return e};var v=e=>f(c({},"__esModule",{value:!0}),e);var T={};l(T,{CepLookup:()=>p,lookupCep:()=>k});module.exports=v(T);function m(e){let r=e.replace(/\D/g,"");if(r.length!==8)throw new Error("Invalid CEP. It must have 8 digits.");return r}var p=class{constructor(r){this.providers=r.providers,this.fetcher=r.fetcher||(async s=>{let t=await fetch(s);if(!t.ok)throw new Error(`HTTP error! status: ${t.status}`);return t.json()})}async lookup(r,s){let t=m(r),o=this.providers.map(i=>{let d=i.buildUrl(t);return this.fetcher(d).then(n=>i.transform(n)).then(n=>s?s(n):n)});return Promise.any(o)}};function k(e){let{cep:r,providers:s,fetcher:t,mapper:o}=e;return new p({providers:s,fetcher:t}).lookup(r,o)}0&&(module.exports={CepLookup,lookupCep});
@@ -1,19 +1 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./viacep"), exports);
18
- __exportStar(require("./brasil-api"), exports);
19
- __exportStar(require("./apicep"), exports);
1
+ "use strict";var e=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var s=Object.prototype.hasOwnProperty;var m=(r,t)=>{for(var o in t)e(r,o,{get:t[o],enumerable:!0})},p=(r,t,o,d)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of c(t))!s.call(r,i)&&i!==o&&e(r,i,{get:()=>t[i],enumerable:!(d=a(t,i))||d.enumerable});return r};var P=r=>p(e({},"__esModule",{value:!0}),r);var f={};m(f,{apicepProvider:()=>l,brasilApiProvider:()=>v,viaCepProvider:()=>n});module.exports=P(f);var n={name:"ViaCEP",buildUrl:r=>`https://viacep.com.br/ws/${r}/json/`,transform:r=>{if(r.erro)throw new Error("CEP not found");return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouro,service:"ViaCEP"}}};var v={name:"BrasilAPI",buildUrl:r=>`https://brasilapi.com.br/api/cep/v1/${r}`,transform:r=>({cep:r.cep,state:r.state,city:r.city,neighborhood:r.neighborhood,street:r.street,service:"BrasilAPI"})};var l={name:"ApiCEP",buildUrl:r=>`https://cdn.apicep.com/file/apicep/${r}.json`,transform:r=>({cep:r.code,state:r.state,city:r.city,neighborhood:r.district,street:r.address,service:"ApiCEP"})};0&&(module.exports={apicepProvider,brasilApiProvider,viaCepProvider});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eusilvio/cep-lookup",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "A modern, flexible, and agnostic CEP lookup library written in TypeScript.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -15,7 +15,9 @@
15
15
  "./providers": "./dist/providers/index.js"
16
16
  },
17
17
  "scripts": {
18
- "build": "tsc",
18
+ "clean": "rm -rf dist",
19
+ "build": "npm run clean && tsc --emitDeclarationOnly --outDir dist && esbuild src/index.ts src/providers/index.ts --outdir=dist --bundle --platform=node --format=cjs",
20
+ "build:prod": "npm run clean && tsc --emitDeclarationOnly --outDir dist && esbuild src/index.ts src/providers/index.ts --outdir=dist --bundle --platform=node --format=cjs --minify",
19
21
  "test": "jest",
20
22
  "example": "ts-node -r tsconfig-paths/register examples/example.ts",
21
23
  "custom-example": "ts-node -r tsconfig-paths/register examples/custom-provider-example.ts",
@@ -28,7 +30,7 @@
28
30
  "address",
29
31
  "correios"
30
32
  ],
31
- "author": "",
33
+ "author": "Silvio Campos",
32
34
  "license": "MIT",
33
35
  "repository": {
34
36
  "type": "git",
@@ -40,6 +42,7 @@
40
42
  "homepage": "https://github.com/eusilvio/cep-lookup#readme",
41
43
  "devDependencies": {
42
44
  "@types/jest": "^30.0.0",
45
+ "esbuild": "^0.20.2",
43
46
  "jest": "^30.1.3",
44
47
  "ts-jest": "^29.4.4",
45
48
  "ts-node": "^10.9.2",
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.apicepProvider = void 0;
4
- /**
5
- * @const {Provider} apicepProvider
6
- * @description Provider for the ApiCEP service.
7
- * @property {string} name - "ApiCEP".
8
- * @property {(cep: string) => string} buildUrl - Constructs the URL for ApiCEP.
9
- * @property {(response: any) => Address} transform - Transforms ApiCEP's response into a standardized `Address` object.
10
- */
11
- exports.apicepProvider = {
12
- name: "ApiCEP",
13
- buildUrl: (cep) => `https://cdn.apicep.com/file/apicep/${cep}.json`,
14
- transform: (response) => {
15
- return {
16
- cep: response.code,
17
- state: response.state,
18
- city: response.city,
19
- neighborhood: response.district,
20
- street: response.address,
21
- service: "ApiCEP",
22
- };
23
- },
24
- };
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.brasilApiProvider = void 0;
4
- /**
5
- * @const {Provider} brasilApiProvider
6
- * @description Provider for the BrasilAPI service.
7
- * @property {string} name - "BrasilAPI".
8
- * @property {(cep: string) => string} buildUrl - Constructs the URL for BrasilAPI.
9
- * @property {(response: any) => Address} transform - Transforms BrasilAPI's response into a standardized `Address` object.
10
- */
11
- exports.brasilApiProvider = {
12
- name: "BrasilAPI",
13
- buildUrl: (cep) => `https://brasilapi.com.br/api/cep/v1/${cep}`,
14
- transform: (response) => {
15
- return {
16
- cep: response.cep,
17
- state: response.state,
18
- city: response.city,
19
- neighborhood: response.neighborhood,
20
- street: response.street,
21
- service: "BrasilAPI",
22
- };
23
- },
24
- };
@@ -1,28 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.viaCepProvider = void 0;
4
- /**
5
- * @const {Provider} viaCepProvider
6
- * @description Provider for the ViaCEP service.
7
- * @property {string} name - "ViaCEP".
8
- * @property {(cep: string) => string} buildUrl - Constructs the URL for ViaCEP API.
9
- * @property {(response: any) => Address} transform - Transforms ViaCEP's response into a standardized `Address` object.
10
- * @throws {Error} If ViaCEP response indicates an error (e.g., CEP not found).
11
- */
12
- exports.viaCepProvider = {
13
- name: "ViaCEP",
14
- buildUrl: (cep) => `https://viacep.com.br/ws/${cep}/json/`,
15
- transform: (response) => {
16
- if (response.erro) {
17
- throw new Error("CEP not found");
18
- }
19
- return {
20
- cep: response.cep,
21
- state: response.uf,
22
- city: response.localidade,
23
- neighborhood: response.bairro,
24
- street: response.logradouro,
25
- service: "ViaCEP",
26
- };
27
- },
28
- };
package/dist/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });