1 | (function (global, factory) {
|
2 | typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('node-fetch')) :
|
3 | typeof define === 'function' && define.amd ? define(['node-fetch'], factory) :
|
4 | (global = global || self, global.cep = factory(global.fetch));
|
5 | }(this, (function (fetch) { 'use strict';
|
6 |
|
7 | fetch = fetch && Object.prototype.hasOwnProperty.call(fetch, 'default') ? fetch['default'] : fetch;
|
8 |
|
9 | function _typeof(obj) {
|
10 | "@babel/helpers - typeof";
|
11 |
|
12 | return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
|
13 | return typeof obj;
|
14 | } : function (obj) {
|
15 | return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
|
16 | }, _typeof(obj);
|
17 | }
|
18 |
|
19 | function _classCallCheck(instance, Constructor) {
|
20 | if (!(instance instanceof Constructor)) {
|
21 | throw new TypeError("Cannot call a class as a function");
|
22 | }
|
23 | }
|
24 |
|
25 | function _defineProperties(target, props) {
|
26 | for (var i = 0; i < props.length; i++) {
|
27 | var descriptor = props[i];
|
28 | descriptor.enumerable = descriptor.enumerable || false;
|
29 | descriptor.configurable = true;
|
30 | if ("value" in descriptor) descriptor.writable = true;
|
31 | Object.defineProperty(target, descriptor.key, descriptor);
|
32 | }
|
33 | }
|
34 |
|
35 | function _createClass(Constructor, protoProps, staticProps) {
|
36 | if (protoProps) _defineProperties(Constructor.prototype, protoProps);
|
37 | if (staticProps) _defineProperties(Constructor, staticProps);
|
38 | Object.defineProperty(Constructor, "prototype", {
|
39 | writable: false
|
40 | });
|
41 | return Constructor;
|
42 | }
|
43 |
|
44 | function _inherits(subClass, superClass) {
|
45 | if (typeof superClass !== "function" && superClass !== null) {
|
46 | throw new TypeError("Super expression must either be null or a function");
|
47 | }
|
48 |
|
49 | subClass.prototype = Object.create(superClass && superClass.prototype, {
|
50 | constructor: {
|
51 | value: subClass,
|
52 | writable: true,
|
53 | configurable: true
|
54 | }
|
55 | });
|
56 | Object.defineProperty(subClass, "prototype", {
|
57 | writable: false
|
58 | });
|
59 | if (superClass) _setPrototypeOf(subClass, superClass);
|
60 | }
|
61 |
|
62 | function _getPrototypeOf(o) {
|
63 | _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
|
64 | return o.__proto__ || Object.getPrototypeOf(o);
|
65 | };
|
66 | return _getPrototypeOf(o);
|
67 | }
|
68 |
|
69 | function _setPrototypeOf(o, p) {
|
70 | _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
|
71 | o.__proto__ = p;
|
72 | return o;
|
73 | };
|
74 |
|
75 | return _setPrototypeOf(o, p);
|
76 | }
|
77 |
|
78 | function _isNativeReflectConstruct() {
|
79 | if (typeof Reflect === "undefined" || !Reflect.construct) return false;
|
80 | if (Reflect.construct.sham) return false;
|
81 | if (typeof Proxy === "function") return true;
|
82 |
|
83 | try {
|
84 | Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
|
85 | return true;
|
86 | } catch (e) {
|
87 | return false;
|
88 | }
|
89 | }
|
90 |
|
91 | function _construct(Parent, args, Class) {
|
92 | if (_isNativeReflectConstruct()) {
|
93 | _construct = Reflect.construct;
|
94 | } else {
|
95 | _construct = function _construct(Parent, args, Class) {
|
96 | var a = [null];
|
97 | a.push.apply(a, args);
|
98 | var Constructor = Function.bind.apply(Parent, a);
|
99 | var instance = new Constructor();
|
100 | if (Class) _setPrototypeOf(instance, Class.prototype);
|
101 | return instance;
|
102 | };
|
103 | }
|
104 |
|
105 | return _construct.apply(null, arguments);
|
106 | }
|
107 |
|
108 | function _isNativeFunction(fn) {
|
109 | return Function.toString.call(fn).indexOf("[native code]") !== -1;
|
110 | }
|
111 |
|
112 | function _wrapNativeSuper(Class) {
|
113 | var _cache = typeof Map === "function" ? new Map() : undefined;
|
114 |
|
115 | _wrapNativeSuper = function _wrapNativeSuper(Class) {
|
116 | if (Class === null || !_isNativeFunction(Class)) return Class;
|
117 |
|
118 | if (typeof Class !== "function") {
|
119 | throw new TypeError("Super expression must either be null or a function");
|
120 | }
|
121 |
|
122 | if (typeof _cache !== "undefined") {
|
123 | if (_cache.has(Class)) return _cache.get(Class);
|
124 |
|
125 | _cache.set(Class, Wrapper);
|
126 | }
|
127 |
|
128 | function Wrapper() {
|
129 | return _construct(Class, arguments, _getPrototypeOf(this).constructor);
|
130 | }
|
131 |
|
132 | Wrapper.prototype = Object.create(Class.prototype, {
|
133 | constructor: {
|
134 | value: Wrapper,
|
135 | enumerable: false,
|
136 | writable: true,
|
137 | configurable: true
|
138 | }
|
139 | });
|
140 | return _setPrototypeOf(Wrapper, Class);
|
141 | };
|
142 |
|
143 | return _wrapNativeSuper(Class);
|
144 | }
|
145 |
|
146 | function _assertThisInitialized(self) {
|
147 | if (self === void 0) {
|
148 | throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
|
149 | }
|
150 |
|
151 | return self;
|
152 | }
|
153 |
|
154 | function _possibleConstructorReturn(self, call) {
|
155 | if (call && (typeof call === "object" || typeof call === "function")) {
|
156 | return call;
|
157 | } else if (call !== void 0) {
|
158 | throw new TypeError("Derived constructors may only return object or undefined");
|
159 | }
|
160 |
|
161 | return _assertThisInitialized(self);
|
162 | }
|
163 |
|
164 | function _createSuper(Derived) {
|
165 | var hasNativeReflectConstruct = _isNativeReflectConstruct();
|
166 |
|
167 | return function _createSuperInternal() {
|
168 | var Super = _getPrototypeOf(Derived),
|
169 | result;
|
170 |
|
171 | if (hasNativeReflectConstruct) {
|
172 | var NewTarget = _getPrototypeOf(this).constructor;
|
173 |
|
174 | result = Reflect.construct(Super, arguments, NewTarget);
|
175 | } else {
|
176 | result = Super.apply(this, arguments);
|
177 | }
|
178 |
|
179 | return _possibleConstructorReturn(this, result);
|
180 | };
|
181 | }
|
182 |
|
183 | function _toConsumableArray(arr) {
|
184 | return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
|
185 | }
|
186 |
|
187 | function _arrayWithoutHoles(arr) {
|
188 | if (Array.isArray(arr)) return _arrayLikeToArray(arr);
|
189 | }
|
190 |
|
191 | function _iterableToArray(iter) {
|
192 | if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
|
193 | }
|
194 |
|
195 | function _unsupportedIterableToArray(o, minLen) {
|
196 | if (!o) return;
|
197 | if (typeof o === "string") return _arrayLikeToArray(o, minLen);
|
198 | var n = Object.prototype.toString.call(o).slice(8, -1);
|
199 | if (n === "Object" && o.constructor) n = o.constructor.name;
|
200 | if (n === "Map" || n === "Set") return Array.from(o);
|
201 | if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
|
202 | }
|
203 |
|
204 | function _arrayLikeToArray(arr, len) {
|
205 | if (len == null || len > arr.length) len = arr.length;
|
206 |
|
207 | for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
|
208 |
|
209 | return arr2;
|
210 | }
|
211 |
|
212 | function _nonIterableSpread() {
|
213 | throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
214 | }
|
215 |
|
216 | function _createForOfIteratorHelper(o, allowArrayLike) {
|
217 | var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
|
218 |
|
219 | if (!it) {
|
220 | if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
|
221 | if (it) o = it;
|
222 | var i = 0;
|
223 |
|
224 | var F = function () {};
|
225 |
|
226 | return {
|
227 | s: F,
|
228 | n: function () {
|
229 | if (i >= o.length) return {
|
230 | done: true
|
231 | };
|
232 | return {
|
233 | done: false,
|
234 | value: o[i++]
|
235 | };
|
236 | },
|
237 | e: function (e) {
|
238 | throw e;
|
239 | },
|
240 | f: F
|
241 | };
|
242 | }
|
243 |
|
244 | throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
245 | }
|
246 |
|
247 | var normalCompletion = true,
|
248 | didErr = false,
|
249 | err;
|
250 | return {
|
251 | s: function () {
|
252 | it = it.call(o);
|
253 | },
|
254 | n: function () {
|
255 | var step = it.next();
|
256 | normalCompletion = step.done;
|
257 | return step;
|
258 | },
|
259 | e: function (e) {
|
260 | didErr = true;
|
261 | err = e;
|
262 | },
|
263 | f: function () {
|
264 | try {
|
265 | if (!normalCompletion && it.return != null) it.return();
|
266 | } finally {
|
267 | if (didErr) throw err;
|
268 | }
|
269 | }
|
270 | };
|
271 | }
|
272 |
|
273 | var CepPromiseError = function (_Error) {
|
274 | _inherits(CepPromiseError, _Error);
|
275 |
|
276 | var _super = _createSuper(CepPromiseError);
|
277 |
|
278 | function CepPromiseError() {
|
279 | var _this;
|
280 |
|
281 | var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
|
282 | message = _ref.message,
|
283 | type = _ref.type,
|
284 | errors = _ref.errors;
|
285 |
|
286 | _classCallCheck(this, CepPromiseError);
|
287 |
|
288 | _this = _super.call(this);
|
289 | _this.name = 'CepPromiseError';
|
290 | _this.message = message;
|
291 | _this.type = type;
|
292 | _this.errors = errors;
|
293 | return _this;
|
294 | }
|
295 |
|
296 | return _createClass(CepPromiseError);
|
297 | }( _wrapNativeSuper(Error));
|
298 |
|
299 | var ServiceError = function (_Error) {
|
300 | _inherits(ServiceError, _Error);
|
301 |
|
302 | var _super = _createSuper(ServiceError);
|
303 |
|
304 | function ServiceError() {
|
305 | var _this;
|
306 |
|
307 | var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
|
308 | message = _ref.message,
|
309 | service = _ref.service;
|
310 |
|
311 | _classCallCheck(this, ServiceError);
|
312 |
|
313 | _this = _super.call(this);
|
314 | _this.name = 'ServiceError';
|
315 | _this.message = message;
|
316 | _this.service = service;
|
317 | return _this;
|
318 | }
|
319 |
|
320 | return _createClass(ServiceError);
|
321 | }( _wrapNativeSuper(Error));
|
322 |
|
323 | function fetchCorreiosService(cepWithLeftPad, configurations) {
|
324 | var url = 'https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente';
|
325 | var options = {
|
326 | method: 'POST',
|
327 | body: "<?xml version=\"1.0\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cli=\"http://cliente.bean.master.sigep.bsb.correios.com.br/\">\n <soapenv:Header />\n <soapenv:Body>\n <cli:consultaCEP>\n <cep>".concat(cepWithLeftPad, "</cep>\n </cli:consultaCEP>\n </soapenv:Body>\n</soapenv:Envelope>"),
|
328 | headers: {
|
329 | 'Content-Type': 'text/xml;charset=UTF-8',
|
330 | 'cache-control': 'no-cache'
|
331 | },
|
332 | timeout: configurations.timeout || 30000
|
333 | };
|
334 | return fetch(url, options).then(analyzeAndParseResponse)["catch"](throwApplicationError);
|
335 | }
|
336 |
|
337 | function analyzeAndParseResponse(response) {
|
338 | if (response.ok) {
|
339 | return response.text().then(parseSuccessXML).then(extractValuesFromSuccessResponse);
|
340 | }
|
341 |
|
342 | return response.text().then(parseAndextractErrorMessage).then(throwCorreiosError);
|
343 | }
|
344 |
|
345 | function parseSuccessXML(xmlString) {
|
346 | try {
|
347 | var _xmlString$replace$ma;
|
348 |
|
349 | var returnStatement = (_xmlString$replace$ma = xmlString.replace(/\r?\n|\r/g, '').match(/<return>(.*)<\/return>/)[0]) !== null && _xmlString$replace$ma !== void 0 ? _xmlString$replace$ma : '';
|
350 | var cleanReturnStatement = returnStatement.replace('<return>', '').replace('</return>', '');
|
351 | var parsedReturnStatement = cleanReturnStatement.split(/</).reduce(function (result, exp) {
|
352 | var splittenExp = exp.split('>');
|
353 |
|
354 | if (splittenExp.length > 1 && splittenExp[1].length) {
|
355 | result[splittenExp[0]] = splittenExp[1];
|
356 | }
|
357 |
|
358 | return result;
|
359 | }, {});
|
360 | return parsedReturnStatement;
|
361 | } catch (e) {
|
362 | throw new Error('Não foi possível interpretar o XML de resposta.');
|
363 | }
|
364 | }
|
365 |
|
366 | function parseAndextractErrorMessage(xmlString) {
|
367 | try {
|
368 | var _xmlString$match$;
|
369 |
|
370 | var returnStatement = (_xmlString$match$ = xmlString.match(/<faultstring>(.*)<\/faultstring>/)[0]) !== null && _xmlString$match$ !== void 0 ? _xmlString$match$ : '';
|
371 | var cleanReturnStatement = returnStatement.replace('<faultstring>', '').replace('</faultstring>', '');
|
372 | return cleanReturnStatement;
|
373 | } catch (e) {
|
374 | throw new Error('Não foi possível interpretar o XML de resposta.');
|
375 | }
|
376 | }
|
377 |
|
378 | function throwCorreiosError(translatedErrorMessage) {
|
379 | throw new Error(translatedErrorMessage);
|
380 | }
|
381 |
|
382 | function extractValuesFromSuccessResponse(xmlObject) {
|
383 | return {
|
384 | cep: xmlObject.cep,
|
385 | state: xmlObject.uf,
|
386 | city: xmlObject.cidade,
|
387 | neighborhood: xmlObject.bairro,
|
388 | street: xmlObject.end,
|
389 | service: 'correios'
|
390 | };
|
391 | }
|
392 |
|
393 | function throwApplicationError(error) {
|
394 | var serviceError = new ServiceError({
|
395 | message: error.message,
|
396 | service: 'correios'
|
397 | });
|
398 |
|
399 | if (error.name === 'FetchError') {
|
400 | serviceError.message = 'Erro ao se conectar com o serviço dos Correios.';
|
401 | }
|
402 |
|
403 | throw serviceError;
|
404 | }
|
405 |
|
406 | function fetchViaCepService(cepWithLeftPad, configurations) {
|
407 | var url = "https://viacep.com.br/ws/".concat(cepWithLeftPad, "/json/");
|
408 | var options = {
|
409 | method: 'GET',
|
410 | mode: 'cors',
|
411 | headers: {
|
412 | 'content-type': 'application/json;charset=utf-8'
|
413 | },
|
414 | timeout: configurations.timeout || 30000
|
415 | };
|
416 |
|
417 | if (typeof window == 'undefined') {
|
418 | options.headers['user-agent'] = 'cep-promise';
|
419 | }
|
420 |
|
421 | return fetch(url, options).then(analyzeAndParseResponse$1).then(checkForViaCepError).then(extractCepValuesFromResponse)["catch"](throwApplicationError$1);
|
422 | }
|
423 |
|
424 | function analyzeAndParseResponse$1(response) {
|
425 | if (response.ok) {
|
426 | return response.json();
|
427 | }
|
428 |
|
429 | throw Error('Erro ao se conectar com o serviço ViaCEP.');
|
430 | }
|
431 |
|
432 | function checkForViaCepError(responseObject) {
|
433 | if (responseObject.erro === true) {
|
434 | throw new Error('CEP não encontrado na base do ViaCEP.');
|
435 | }
|
436 |
|
437 | return responseObject;
|
438 | }
|
439 |
|
440 | function extractCepValuesFromResponse(responseObject) {
|
441 | return {
|
442 | cep: responseObject.cep.replace('-', ''),
|
443 | state: responseObject.uf,
|
444 | city: responseObject.localidade,
|
445 | neighborhood: responseObject.bairro,
|
446 | street: responseObject.logradouro,
|
447 | service: 'viacep'
|
448 | };
|
449 | }
|
450 |
|
451 | function throwApplicationError$1(error) {
|
452 | var serviceError = new ServiceError({
|
453 | message: error.message,
|
454 | service: 'viacep'
|
455 | });
|
456 |
|
457 | if (error.name === 'FetchError') {
|
458 | serviceError.message = 'Erro ao se conectar com o serviço ViaCEP.';
|
459 | }
|
460 |
|
461 | throw serviceError;
|
462 | }
|
463 |
|
464 | function fetchWideNetService(cepWithLeftPad, configurations) {
|
465 | var url = "https://ws.apicep.com/busca-cep/api/cep/".concat(cepWithLeftPad, ".json");
|
466 | var options = {
|
467 | method: 'GET',
|
468 | mode: 'cors',
|
469 | headers: {
|
470 | 'content-type': 'application/json;charset=utf-8'
|
471 | },
|
472 | timeout: configurations.timeout || 30000
|
473 | };
|
474 | return fetch(url, options).then(analyzeAndParseResponse$2).then(checkForWideNetError).then(extractCepValuesFromResponse$1)["catch"](throwApplicationError$2);
|
475 | }
|
476 |
|
477 | function analyzeAndParseResponse$2(response) {
|
478 | if (response.ok) {
|
479 | return response.json();
|
480 | }
|
481 |
|
482 | throw Error('Erro ao se conectar com o serviço WideNet.');
|
483 | }
|
484 |
|
485 | function checkForWideNetError(object) {
|
486 | if (object.ok === false || object.status !== 200) {
|
487 | throw new Error('CEP não encontrado na base do WideNet.');
|
488 | }
|
489 |
|
490 | return object;
|
491 | }
|
492 |
|
493 | function extractCepValuesFromResponse$1(object) {
|
494 | return {
|
495 | cep: object.code.replace('-', ''),
|
496 | state: object.state,
|
497 | city: object.city,
|
498 | neighborhood: object.district,
|
499 | street: object.address,
|
500 | service: 'widenet'
|
501 | };
|
502 | }
|
503 |
|
504 | function throwApplicationError$2(error) {
|
505 | var serviceError = new ServiceError({
|
506 | message: error.message,
|
507 | service: 'widenet'
|
508 | });
|
509 |
|
510 | if (error.name === 'FetchError') {
|
511 | serviceError.message = 'Erro ao se conectar com o serviço WideNet.';
|
512 | }
|
513 |
|
514 | throw serviceError;
|
515 | }
|
516 |
|
517 | function fetchBrasilAPIService(cepWithLeftPad, configurations) {
|
518 | var url = "https://brasilapi.com.br/api/cep/v1/".concat(cepWithLeftPad);
|
519 | var options = {
|
520 | method: 'GET',
|
521 | mode: 'cors',
|
522 | headers: {
|
523 | 'content-type': 'application/json;charset=utf-8'
|
524 | },
|
525 | timeout: configurations.timeout || 30000
|
526 | };
|
527 | return fetch(url, options).then(parseResponse).then(extractCepValuesFromResponse$2)["catch"](throwApplicationError$3);
|
528 | }
|
529 |
|
530 | function parseResponse(response) {
|
531 | if (response.ok === false || response.status !== 200) {
|
532 | throw new Error('CEP não encontrado na base do BrasilAPI.');
|
533 | }
|
534 |
|
535 | return response.json();
|
536 | }
|
537 |
|
538 | function extractCepValuesFromResponse$2(response) {
|
539 | return {
|
540 | cep: response.cep,
|
541 | state: response.state,
|
542 | city: response.city,
|
543 | neighborhood: response.neighborhood,
|
544 | street: response.street,
|
545 | service: 'brasilapi'
|
546 | };
|
547 | }
|
548 |
|
549 | function throwApplicationError$3(error) {
|
550 | var serviceError = new ServiceError({
|
551 | message: error.message,
|
552 | service: 'brasilapi'
|
553 | });
|
554 |
|
555 | if (error.name === 'FetchError') {
|
556 | serviceError.message = 'Erro ao se conectar com o serviço BrasilAPI.';
|
557 | }
|
558 |
|
559 | throw serviceError;
|
560 | }
|
561 |
|
562 | function getAvailableServices() {
|
563 | var isBrowser = typeof window !== 'undefined';
|
564 |
|
565 | if (isBrowser) {
|
566 | return {
|
567 | viacep: fetchViaCepService,
|
568 | widenet: fetchWideNetService,
|
569 | brasilapi: fetchBrasilAPIService
|
570 | };
|
571 | }
|
572 |
|
573 | return {
|
574 | correios: fetchCorreiosService,
|
575 | viacep: fetchViaCepService,
|
576 | widenet: fetchWideNetService,
|
577 | brasilapi: fetchBrasilAPIService
|
578 | };
|
579 | }
|
580 |
|
581 | var reverse = function reverse(promise) {
|
582 | return new Promise(function (resolve, reject) {
|
583 | return Promise.resolve(promise).then(reject, resolve);
|
584 | });
|
585 | };
|
586 |
|
587 | Promise.any = function (iterable) {
|
588 | return reverse(Promise.all(_toConsumableArray(iterable).map(reverse)));
|
589 | };
|
590 |
|
591 | var Promise$1 = Promise;
|
592 |
|
593 | var CEP_SIZE = 8;
|
594 | function cepPromise (cepRawValue) {
|
595 | var configurations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
596 | return Promise$1.resolve(cepRawValue).then(validateInputType).then(function (cepRawValue) {
|
597 | configurations.providers = configurations.providers ? configurations.providers : [];
|
598 | validateProviders(configurations.providers);
|
599 | return cepRawValue;
|
600 | }).then(removeSpecialCharacters).then(validateInputLength).then(leftPadWithZeros).then(function (cepWithLeftPad) {
|
601 | return fetchCepFromServices(cepWithLeftPad, configurations);
|
602 | })["catch"](handleServicesError)["catch"](throwApplicationError$4);
|
603 | }
|
604 |
|
605 | function validateProviders(providers) {
|
606 | var availableProviders = Object.keys(getAvailableServices());
|
607 |
|
608 | if (!Array.isArray(providers)) {
|
609 | throw new CepPromiseError({
|
610 | message: 'Erro ao inicializar a instância do CepPromise.',
|
611 | type: 'validation_error',
|
612 | errors: [{
|
613 | message: 'O parâmetro providers deve ser uma lista.',
|
614 | service: 'providers_validation'
|
615 | }]
|
616 | });
|
617 | }
|
618 |
|
619 | var _iterator = _createForOfIteratorHelper(providers),
|
620 | _step;
|
621 |
|
622 | try {
|
623 | for (_iterator.s(); !(_step = _iterator.n()).done;) {
|
624 | var provider = _step.value;
|
625 |
|
626 | if (!availableProviders.includes(provider)) {
|
627 | throw new CepPromiseError({
|
628 | message: 'Erro ao inicializar a instância do CepPromise.',
|
629 | type: 'validation_error',
|
630 | errors: [{
|
631 | message: "O provider \"".concat(provider, "\" \xE9 inv\xE1lido. Os providers dispon\xEDveis s\xE3o: [\"").concat(availableProviders.join('", "'), "\"]."),
|
632 | service: 'providers_validation'
|
633 | }]
|
634 | });
|
635 | }
|
636 | }
|
637 | } catch (err) {
|
638 | _iterator.e(err);
|
639 | } finally {
|
640 | _iterator.f();
|
641 | }
|
642 | }
|
643 |
|
644 | function validateInputType(cepRawValue) {
|
645 | var cepTypeOf = _typeof(cepRawValue);
|
646 |
|
647 | if (cepTypeOf === 'number' || cepTypeOf === 'string') {
|
648 | return cepRawValue;
|
649 | }
|
650 |
|
651 | throw new CepPromiseError({
|
652 | message: 'Erro ao inicializar a instância do CepPromise.',
|
653 | type: 'validation_error',
|
654 | errors: [{
|
655 | message: 'Você deve chamar o construtor utilizando uma String ou um Number.',
|
656 | service: 'cep_validation'
|
657 | }]
|
658 | });
|
659 | }
|
660 |
|
661 | function removeSpecialCharacters(cepRawValue) {
|
662 | return cepRawValue.toString().replace(/\D+/g, '');
|
663 | }
|
664 |
|
665 | function leftPadWithZeros(cepCleanValue) {
|
666 | return '0'.repeat(CEP_SIZE - cepCleanValue.length) + cepCleanValue;
|
667 | }
|
668 |
|
669 | function validateInputLength(cepWithLeftPad) {
|
670 | if (cepWithLeftPad.length <= CEP_SIZE) {
|
671 | return cepWithLeftPad;
|
672 | }
|
673 |
|
674 | throw new CepPromiseError({
|
675 | message: "CEP deve conter exatamente ".concat(CEP_SIZE, " caracteres."),
|
676 | type: 'validation_error',
|
677 | errors: [{
|
678 | message: "CEP informado possui mais do que ".concat(CEP_SIZE, " caracteres."),
|
679 | service: 'cep_validation'
|
680 | }]
|
681 | });
|
682 | }
|
683 |
|
684 | function fetchCepFromServices(cepWithLeftPad, configurations) {
|
685 | var providersServices = getAvailableServices();
|
686 |
|
687 | if (configurations.providers.length === 0) {
|
688 | return Promise$1.any(Object.values(providersServices).map(function (provider) {
|
689 | return provider(cepWithLeftPad, configurations);
|
690 | }));
|
691 | }
|
692 |
|
693 | return Promise$1.any(configurations.providers.map(function (provider) {
|
694 | return providersServices[provider](cepWithLeftPad, configurations);
|
695 | }));
|
696 | }
|
697 |
|
698 | function handleServicesError(aggregatedErrors) {
|
699 | if (aggregatedErrors.length !== undefined) {
|
700 | throw new CepPromiseError({
|
701 | message: 'Todos os serviços de CEP retornaram erro.',
|
702 | type: 'service_error',
|
703 | errors: aggregatedErrors
|
704 | });
|
705 | }
|
706 |
|
707 | throw aggregatedErrors;
|
708 | }
|
709 |
|
710 | function throwApplicationError$4(_ref) {
|
711 | var message = _ref.message,
|
712 | type = _ref.type,
|
713 | errors = _ref.errors;
|
714 | throw new CepPromiseError({
|
715 | message: message,
|
716 | type: type,
|
717 | errors: errors
|
718 | });
|
719 | }
|
720 |
|
721 | return cepPromise;
|
722 |
|
723 | })));
|