@malga-checkout/core
Version:
Core components for Malga Checkout
1,852 lines (1,754 loc) • 101 kB
JavaScript
'use strict';
const _commonjsHelpers = require('./_commonjsHelpers-bcc1208a.js');
class ValidationError extends Error {
constructor(msg) {
super(msg);
this.name = 'ValidationError';
}
}
class InvalidFormat extends ValidationError {
constructor(msg = 'The number has an invlidad format.') {
super(msg);
this.name = 'InvalidFormat';
}
}
class InvalidChecksum extends ValidationError {
constructor(msg = "The number number's checksum or check digit is invalid.") {
super(msg);
this.name = 'InvalidChecksum';
}
}
class InvalidLength extends ValidationError {
constructor(msg = 'The number has an invalid length.') {
super(msg);
this.name = 'InvalidLength';
}
}
class InvalidComponent extends ValidationError {
constructor(msg = 'One of the parts of the number are invalid or unknown.') {
super(msg);
this.name = 'InvalidComponent';
}
}
const digitRE = /^[0-9]+$/;
function isdigits(value) {
return digitRE.test(value);
}
const mapped = {
'-': '-',
'\u{00AD}': '-',
'\u{00AF}': '-',
'\u{02D7}': '-',
'\u{058A}': '-',
'\u{05BE}': '-',
'\u{180A}': '-',
'\u{2010}': '-',
'\u{2011}': '-',
'\u{2012}': '-',
'\u{2013}': '-',
'\u{2014}': '-',
'\u{2015}': '-',
'\u{203E}': '-',
'\u{2043}': '-',
'\u{207B}': '-',
'\u{208B}': '-',
'\u{2212}': '-',
'\u{23AF}': '-',
'\u{23BA}': '-',
'\u{23BB}': '-',
'\u{23BC}': '-',
'\u{23BD}': '-',
'\u{23E4}': '-',
'\u{FF0D}': '-',
'\u{FE63}': '-',
'\u{FFE3}': '-',
'*': '*',
'\u{066D}': '*',
'\u{070D}': '*',
'\u{2055}': '*',
'\u{A60E}': '*',
'\u{2217}': '*',
'\u{22C6}': '*',
'\u{204E}': '*',
'\u{2731}': '*',
'\u{2732}': '*',
'\u{2733}': '*',
'\u{273A}': '*',
'\u{273B}': '*',
'\u{273C}': '*',
'\u{273D}': '*',
'\u{2743}': '*',
'\u{2749}': '*',
'\u{274A}': '*',
'\u{274B}': '*',
'\u{FE61}': '*',
'\u{FF0A}': '*',
',': ',',
'\u{00B8}': ',',
'\u{060C}': ',',
'\u{066B}': ',',
'\u{066C}': ',',
'\u{201A}': ',',
'\u{2032}': ',',
'\u{2E34}': ',',
'\u{3001}': ',',
'\u{FF0C}': ',',
'\u{FE11}': ',',
'\u{FE50}': ',',
'\u{FE51}': ',',
'\u{FF64}': ',',
'.': '.',
'\u{00B7}': '.',
'\u{02D9}': '.',
'\u{0387}': '.',
'\u{06D4}': '.',
'\u{0701}': '.',
'\u{0702}': '.',
'\u{0830}': '.',
'\u{0F0B}': '.',
'\u{0F0C}': '.',
"\u{1427}": ".",
'\u{16EB}': '.',
'\u{2219}': '.',
'\u{2022}': '.',
'\u{2024}': '.',
'\u{2027}': '.',
'\u{22C5}': '.',
'\u{2E31}': '.',
'\u{2E33}': '.',
'\u{3002}': '.',
'\u{30FB}': '.',
'\u{FE52}': '.',
'\u{FF0E}': '.',
'\u{FF65}': '.',
'\u{FBB2}': '.',
'\u{FBB3}': '.',
'\u{10101}': '.',
'\u{1091F}': '.',
'\u{10A50}': '.',
'/': '/',
'\u{2044}': '/',
'\u{2215}': '/',
'\u{29F8}': '/',
'\u{FF0F}': '/',
'\u{083C}': '/',
'\u{27CB}': '/',
':': ':',
'\u{1361}': ':',
'\u{16EC}': ':',
'\u{1804}': ':',
'\u{FE13}': ':',
'\u{FE30}': ':',
'\u{FF1A}': ':',
'\u{FE55}': ':',
' ': ' ',
'\u{0009}': ' ',
'\u{000B}': ' ',
'\u{000C}': ' ',
'\u{00A0}': ' ',
'\u{1680}': ' ',
'\u{2000}': ' ',
'\u{2001}': ' ',
'\u{2002}': ' ',
'\u{2003}': ' ',
'\u{2004}': ' ',
'\u{2005}': ' ',
'\u{2006}': ' ',
'\u{2007}': ' ',
'\u{2008}': ' ',
'\u{2009}': ' ',
'\u{200A}': ' ',
'\u{2028}': ' ',
'\u{2029}': ' ',
'\u{202F}': ' ',
'\u{205F}': ' ',
'\u{3000}': ' ',
"'": "'",
'\u{0060}': "'",
'\u{00B4}': "'",
"\u{02BE}": "'",
"\u{02BF}": "'",
"\u{02B9}": "'",
"\u{02BB}": "'",
"\u{02BC}": "'",
"\u{02C8}": "'",
"\u{0300}": "'",
'\u{0301}': "'",
'\u{0312}': "'",
'\u{0313}': "'",
'\u{055A}': "'",
'\u{201B}': "'",
'\u{2018}': "'",
'\u{2019}': "'",
'0': '0',
'\u{0660}': '0',
'\u{06F0}': '0',
'\u{FF10}': '0',
'\u{1D7CE}': '0',
'\u{1D7D8}': '0',
'\u{1D7E2}': '0',
'\u{1D7EC}': '0',
'\u{1D7F6}': '0',
'1': '1',
'\u{0661}': '1',
'\u{06F1}': '1',
'\u{FF11}': '1',
'\u{1D7CF}': '1',
'\u{1D7D9}': '1',
'\u{1D7E3}': '1',
'\u{1D7ED}': '1',
'\u{1D7F7}': '1',
'2': '2',
'\u{06F2}': '2',
'\u{0662}': '2',
'\u{FF12}': '2',
'\u{1D7D0}': '2',
'\u{1D7DA}': '2',
'\u{1D7E4}': '2',
'\u{1D7EE}': '2',
'\u{1D7F8}': '2',
'3': '3',
'\u{06F3}': '3',
'\u{0663}': '3',
'\u{FF13}': '3',
'\u{1D7D1}': '3',
'\u{1D7DB}': '3',
'\u{1D7E5}': '3',
'\u{1D7EF}': '3',
'\u{1D7F9}': '3',
'4': '4',
'\u{06F4}': '4',
'\u{0664}': '4',
'\u{FF14}': '4',
'\u{1D7D2}': '4',
'\u{1D7DC}': '4',
'\u{1D7E6}': '4',
'\u{1D7F0}': '4',
'\u{1D7FA}': '4',
'5': '5',
'\u{06F5}': '5',
'\u{0665}': '5',
'\u{FF15}': '5',
'\u{1D7D3}': '5',
'\u{1D7DD}': '5',
'\u{1D7E7}': '5',
'\u{1D7F1}': '5',
'\u{1D7FB}': '5',
'6': '6',
'\u{06F6}': '6',
'\u{0666}': '6',
'\u{FF16}': '6',
'\u{1D7D4}': '6',
'\u{1D7DE}': '6',
'\u{1D7E8}': '6',
'\u{1D7F2}': '6',
'\u{1D7FC}': '6',
'7': '7',
'\u{06F7}': '7',
'\u{0667}': '7',
'\u{FF17}': '7',
'\u{1D7D5}': '7',
'\u{1D7DF}': '7',
'\u{1D7E9}': '7',
'\u{1D7F3}': '7',
'\u{1D7FD}': '7',
'8': '8',
'\u{06F8}': '8',
'\u{0668}': '8',
'\u{FF18}': '8',
'\u{1D7D6}': '8',
'\u{1D7E0}': '8',
'\u{1D7EA}': '8',
'\u{1D7F4}': '8',
'\u{1D7FE}': '8',
'9': '9',
'\u{06F9}': '9',
'\u{0669}': '9',
'\u{FF19}': '9',
'\u{1D7D7}': '9',
'\u{1D7E1}': '9',
'\u{1D7EB}': '9',
'\u{1D7F5}': '9',
'\u{1D7FF}': '9',
};
function cleanUnicode(value, deletechars = ' ', stripPrefix) {
if (typeof value !== 'string') {
return ['', new InvalidFormat()];
}
const cleaned = [...value]
.map(c => { var _a; return (_a = mapped[c]) !== null && _a !== void 0 ? _a : c; })
.filter(c => !deletechars.includes(c))
.join('')
.toLocaleUpperCase();
if (stripPrefix && cleaned.startsWith(stripPrefix)) {
return [cleaned.substr(stripPrefix.length), null];
}
return [cleaned, null];
}
function splitAt(value, ...points) {
const parts = [0, ...points].map((p, idx) => {
const nvalue = idx >= points.length ? value.length : points[idx];
const np = nvalue < 0 ? value.length + nvalue : nvalue;
const pp = p < 0 ? value.length + p : p;
return value.substr(pp, np - pp);
});
return parts.filter(v => v.length !== 0);
}
function weightedSum(value, { alphabet = '0123456789', reverse = false, weights = [1], modulus = 0, }) {
const wlen = weights.length;
const numbers = value.split('').map(v => alphabet.indexOf(v));
const weighted = (reverse ? numbers.reverse() : numbers).map((v, idx) => v * weights[idx % wlen]);
return weighted.reduce((acc, v) => {
let vv = v;
while (vv < 0) {
vv += modulus;
}
return (acc + vv) % modulus;
}, 0);
}
function isValidDate(yy, mm, dd) {
const yyN = parseInt(yy, 10);
const mmN = parseInt(mm, 10) - 1;
const ddN = parseInt(dd, 10);
if (Number.isNaN(yyN) || Number.isNaN(mmN) || Number.isNaN(ddN)) {
return false;
}
let d;
if (yyN < 20) {
d = new Date(2000 + yyN, mmN, ddN);
}
else if (yyN < 100) {
d = new Date(1900 + yyN, mmN, ddN);
}
else {
d = new Date(yyN, mmN, ddN);
}
if (Number.isNaN(d.getFullYear())) {
return false;
}
if (d.getDate() !== ddN || d.getMonth() !== mmN) {
return false;
}
return true;
}
function isValidDateCompactYYYYMMDD(yyyymmdd) {
const [year, mon, day] = splitAt(yyyymmdd, 4, 6);
return isValidDate(year, mon, day);
}
function clean$3(input) {
return cleanUnicode(input, ' -');
}
const impl$3 = {
name: 'Bosnia Unique Master Citizen Number',
localName: 'Jedinstveni matični broj građana',
abbreviation: 'JMBG',
compact(input) {
const [value, err] = clean$3(input);
if (err) {
throw err;
}
return value;
},
format(input) {
const [value] = clean$3(input);
return value;
},
validate(input) {
const [value, error] = clean$3(input);
if (error) {
return { isValid: false, error };
}
if (value.length !== 13) {
return { isValid: false, error: new InvalidLength() };
}
if (!isdigits(value)) {
return { isValid: false, error: new InvalidFormat() };
}
const [front, check] = splitAt(value, 12);
const sum = 11 -
weightedSum(front, {
modulus: 11,
weights: [7, 6, 5, 4, 3, 2, 7, 6, 5, 4, 3, 2],
});
if (String(sum % 10) !== check) {
return { isValid: false, error: new InvalidChecksum() };
}
return {
isValid: true,
compact: value,
isIndividual: true,
isCompany: false,
};
},
};
const { name: name$3, localName: localName$3, abbreviation: abbreviation$3, validate: validate$3, format: format$3, compact: compact$3, } = impl$3;
const jmbg = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$3,
localName: localName$3,
abbreviation: abbreviation$3,
validate: validate$3,
format: format$3,
compact: compact$3
});
function clean$2(input) {
const [v, err] = cleanUnicode(input, ' -');
if (err) {
return ['', err];
}
if (v.startsWith('CL')) {
return [v.substr(2), null];
}
return [v, null];
}
const impl$2 = {
name: 'Chilean National Tax Number',
localName: 'Rol Único Tributario ',
abbreviation: 'RUT',
compact(input) {
const [value, err] = clean$2(input);
if (err) {
throw err;
}
return value;
},
format(input) {
const [value] = clean$2(input);
const [a, b, c, d] = splitAt(value, 2, 5, 8);
return `${a}.${b}.${c}-${d}`;
},
validate(input) {
const [value, error] = clean$2(input);
if (error) {
return { isValid: false, error };
}
if (value.length !== 8 && value.length !== 9) {
return { isValid: false, error: new InvalidLength() };
}
const [front, check] = splitAt(value, value.length - 1);
if (!isdigits(front)) {
return { isValid: false, error: new InvalidComponent() };
}
const sum = weightedSum(front, {
reverse: true,
weights: [9, 8, 7, 6, 5, 4, 9, 8, 7],
modulus: 11,
});
const digit = '0123456789K'[sum];
if (check !== digit) {
return { isValid: false, error: new InvalidChecksum() };
}
return {
isValid: true,
compact: value,
isIndividual: true,
isCompany: true,
};
},
};
const { name: name$2, localName: localName$2, abbreviation: abbreviation$2, validate: validate$2, format: format$2, compact: compact$2, } = impl$2;
const rut = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$2,
localName: localName$2,
abbreviation: abbreviation$2,
validate: validate$2,
format: format$2,
compact: compact$2
});
Object.assign(Object.assign({}, rut), { name: 'Chilean National Identification Number', localName: 'Rol Único Nacional ', abbreviation: 'RUN' });
function clean$1(input) {
return cleanUnicode(input, ' /');
}
const impl$1 = {
name: 'Czech Birth Number',
localName: 'Rodné číslo',
abbreviation: 'RČ',
compact(input) {
const [value, err] = clean$1(input);
if (err) {
throw err;
}
return value;
},
format(input) {
const [value] = clean$1(input);
return splitAt(value, 6).join('/');
},
validate(input) {
const [value, error] = clean$1(input);
if (error) {
return { isValid: false, error };
}
if (value.length !== 10 && value.length !== 9) {
return { isValid: false, error: new InvalidLength() };
}
if (!isdigits(value)) {
return { isValid: false, error: new InvalidFormat() };
}
const [yy, mm, dd] = splitAt(value, 2, 4, 6);
const mon = (parseInt(mm, 10) % 50) % 20;
let year = parseInt(yy, 10) + 1900;
if (value.length === 9) {
if (year > 1980) {
year -= 100;
}
if (year > 1953) {
return { isValid: false, error: new InvalidComponent() };
}
}
else if (year < 1954) {
year += 100;
}
if (!isValidDateCompactYYYYMMDD(`${year}${String(mon).padStart(2, '0')}${dd}`)) {
return { isValid: false, error: new InvalidComponent() };
}
if (value.length === 10) {
const [front, check] = splitAt(value, -1);
const sum = (parseInt(front, 10) % 11) % (year < 1985 ? 10 : 11);
if (String(sum) !== check) {
return { isValid: false, error: new InvalidChecksum() };
}
}
return {
isValid: true,
compact: value,
isIndividual: true,
isCompany: false,
};
},
};
const { name: name$1, localName: localName$1, abbreviation: abbreviation$1, validate: validate$1, format: format$1, compact: compact$1, } = impl$1;
const rc = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$1,
localName: localName$1,
abbreviation: abbreviation$1,
validate: validate$1,
format: format$1,
compact: compact$1
});
function buildMatch(fmt) {
const pattern = fmt.replace(/([FBUP])\1*/g, m => {
return `(\\d{${m.length}})`;
});
const matcher = new RegExp(`^${pattern}$`);
return (value) => {
var _a, _b, _c, _d;
const m = matcher.exec(value);
if (!m) {
return { match: false };
}
return {
match: true,
f: (_a = m[1]) !== null && _a !== void 0 ? _a : '',
b: (_b = m[2]) !== null && _b !== void 0 ? _b : '',
u: (_c = m[3]) !== null && _c !== void 0 ? _c : '',
p: (_d = m[4]) !== null && _d !== void 0 ? _d : '',
};
};
}
function buildMatcher(rfmt, cfmt) {
return {
region: buildMatch(rfmt),
country: buildMatch(cfmt),
};
}
({
'DE-BW': buildMatcher('FFBBBUUUUP', '28FF0BBBUUUUP'),
'DE-BY': buildMatcher('FFFBBBUUUUP', '9FFF0BBBUUUUP'),
'DE-BE': buildMatcher('FFBBBUUUUP', '11FF0BBBUUUUP'),
'DE-BB': buildMatcher('0FFBBBUUUUP', '30FF0BBBUUUUP'),
'DE-HB': buildMatcher('FFBBBUUUUP', '24FF0BBBUUUUP'),
'DE-HH': buildMatcher('FFBBBUUUUP', '22FF0BBBUUUUP'),
'DE-HE': buildMatcher('0FFBBBUUUUP', '26FF0BBBUUUUP'),
'DE-MV': buildMatcher('0FFBBBUUUUP', '40FF0BBBUUUUP'),
'DE-NI': buildMatcher('FFBBBUUUUP', '23FF0BBBUUUUP'),
'DE-NW': buildMatcher('FFFBBBBUUUP', '5FFF0BBBBUUUP'),
'DE-RP': buildMatcher('FFBBBUUUUP', '27FF0BBBUUUUP'),
'DE-SL': buildMatcher('0FFBBBUUUUP', '10FF0BBBUUUUP'),
'DE-SN': buildMatcher('2FFBBBUUUUP', '32FF0BBBUUUUP'),
'DE-ST': buildMatcher('1FFBBBUUUUP', '31FF0BBBUUUUP'),
'DE-SH': buildMatcher('FFBBBUUUUP', '21FF0BBBUUUUP'),
'DE-TH': buildMatcher('1FFBBBUUUUP', '41FF0BBBUUUUP'),
});
Object.assign(Object.assign({}, jmbg), { name: 'Montenegrin Unique Master Citizen Number', localName: ' Јединствени матични број грађана', abbreviation: 'ЈМБГ' });
Object.assign(Object.assign({}, jmbg), { name: 'Macedonian Unique Master Citizen Number', localName: 'Единствен матичен број на граѓанинот', abbreviation: 'ЕМБГ' });
const citiesPairs = [
[10, 'Aguascalientes'],
[12, 'Calvillo'],
[14, 'Jesús María'],
[20, 'Mexicali'],
[22, 'Ensenada'],
[27, 'Tecate'],
[27, 'Tijuana'],
[28, 'La Mesa'],
[28, 'Rosarito'],
[28, 'Tijuana [alternate]'],
[40, 'La Paz'],
[41, 'Cabo San Lucas'],
[42, 'Ciudad Constitución'],
[43, 'Guerrero Negro'],
[45, 'San José del Cabo'],
[46, 'Santa Rosalía'],
[50, 'Campeche'],
[51, 'Calkiní'],
[52, 'Ciudad del Carmen'],
[53, 'Champotón'],
[60, 'Gómez Palacio'],
[60, 'Torreón'],
[62, 'Ciudad Acuña'],
[68, 'Monclova'],
[71, 'Nava'],
[72, 'Nueva Rosita'],
[74, 'Parras de la Fuente'],
[75, 'Piedras Negras'],
[76, 'Ramos Arizpe'],
[77, 'Sabinas'],
[78, 'Saltillo'],
[80, 'San Pedro de las Colonias'],
[90, 'Colima'],
[95, 'Manzanillo'],
[97, 'Tecomán'],
[100, 'Terán'],
[100, 'Tuxtla Gutiérrez'],
[103, 'Arriaga'],
[107, 'Cintalapa'],
[109, 'Comitán'],
[109, 'Villa Las Rosas'],
[111, 'Chiapa de Corso'],
[113, 'F. Comalapa'],
[114, 'Huixtla'],
[123, 'Ocosingo'],
[124, 'Ocozocuautla'],
[125, 'Palenque'],
[126, 'Pichucalco'],
[127, 'Pijijiapan'],
[128, 'Reforma'],
[130, 'San Cristóbal de las Casas'],
[131, 'Simojovel'],
[133, 'Tapachula'],
[135, 'Tonala'],
[137, 'Venustiano Carranza'],
[138, 'Villa Flores'],
[140, 'Yajalón'],
[150, 'Chihuahua'],
[150, 'Ciudad Delicias'],
[152, 'Ciudad Anáhuac'],
[155, 'Ciudad Camargo'],
[158, 'Ciudad Cuauhtémoc'],
[161, 'Ciudad Guerrero'],
[162, 'Parral'],
[163, 'Ciudad Jiménez'],
[164, 'Ciudad Juárez'],
[165, 'Ciudad Madera'],
[167, 'El Molino de Namiquipa'],
[168, 'Nuevo Casas Grandes'],
[180, 'Atizapan'],
[180, 'Chalco'],
[180, 'Ciudad de México'],
[180, 'Coacalco'],
[180, 'Cuautitlán Izcalli'],
[180, 'Cuautitlán'],
[180, 'Ecatepec'],
[180, 'Huehuetoca'],
[180, 'Huixquilucan'],
[180, 'Ixtapaluca'],
[180, 'Los Reyes La Paz'],
[180, 'Naucalpan'],
[180, 'Nezahualcóyotl'],
[180, 'Tecamac'],
[180, 'Teotihuacán'],
[180, 'Texcoco'],
[180, 'Tlalnepantla'],
[190, 'Durango'],
[198, 'N/A'],
[201, 'Tepehuanes'],
[202, 'Vicente Guerrero'],
[210, 'Guanajuato'],
[211, 'Abasolo'],
[212, 'Acámbaro'],
[213, 'Apaseo el Alto'],
[214, 'Apaseo el Grande'],
[215, 'Celaya'],
[216, 'Comonfort'],
[217, 'Coroneo'],
[218, 'Cortazar'],
[219, 'Cuerámaro'],
[220, 'Dolores Hidalgo'],
[222, 'Irapuato'],
[223, 'Jaral del Progreso'],
[224, 'Jerécuaro'],
[225, 'León'],
[226, 'Cd. Manuel Doblado'],
[227, 'Moroleón'],
[229, 'Pénjamo'],
[232, 'Romita'],
[233, 'Salamanca'],
[234, 'Salvatierra'],
[236, 'San Felipe'],
[237, 'Purísima de Bustos'],
[237, 'San Francisco del Rincoón'],
[238, 'San José Iturbide'],
[239, 'San Luis de la Paz'],
[240, 'San Miguel Allende'],
[244, 'Silao'],
[247, 'Uriangato'],
[248, 'Valle de Santiago'],
[249, 'Yuriria'],
[260, 'Chilpancingo'],
[261, 'Acapulco'],
[263, 'Arcelia'],
[264, 'Atoyac de Álvarez'],
[266, 'Ciudad Altamirano'],
[267, 'Coyuca de Benítez'],
[270, 'Chilapa'],
[271, 'Huitzuco'],
[272, 'Iguala'],
[272, 'La Sabana'],
[274, 'Cuajinicuilapa'],
[274, 'Ometepec'],
[275, 'San Marcos'],
[276, 'Taxco'],
[278, 'Teloloapan'],
[281, 'Tlapa'],
[282, 'Ixtapa Zihuatanejo'],
[282, 'Zihuatanejo'],
[290, 'Pachuca'],
[291, 'Actopan'],
[292, 'Apam'],
[293, 'Atotonilco el Grande'],
[294, 'Ciudad Sahagún'],
[294, 'Teocaltiche'],
[295, 'Cuautepec'],
[296, 'Huejutla'],
[297, 'Huichapan'],
[298, 'Ixmiquilpan'],
[303, 'Progreso de Obregón'],
[305, 'Tepeapulco'],
[308, 'Tizayuca'],
[311, 'Tula de Allende'],
[312, 'Tulancingo'],
[313, 'Zacualtipán'],
[314, 'Zimapán'],
[320, 'El Salto'],
[320, 'Guadalajara'],
[320, 'San Pedro Tlaquepaque'],
[320, 'Tlajomulco'],
[320, 'Tonala [alternate]'],
[320, 'Zapopan'],
[326, 'Ameca'],
[327, 'Arandas'],
[330, 'Atotonilco el Alto'],
[331, 'Atequiza'],
[333, 'Autlán'],
[334, 'Azteca'],
[340, 'Casimiro Castillo'],
[341, 'Cihuatlán'],
[342, 'Ciudad Guzmán'],
[346, 'Chapala'],
[348, 'El Grullo'],
[355, 'Ixtlahuacán del Río'],
[356, 'Jalostotitlán'],
[357, 'Jamay'],
[361, 'La Barca'],
[362, 'Lagos de Moreno'],
[370, 'Ocotlán'],
[373, 'Pihuamo'],
[375, 'Las Juntas'],
[375, 'Nuevo Vallarta'],
[375, 'Pitillal'],
[375, 'Puerto Vallarta'],
[381, 'San Juan de los Lagos'],
[382, 'N/A'],
[384, 'San Miguel el Alto'],
[385, 'San Patricio Melaque'],
[386, 'Sayula'],
[387, 'Tala'],
[389, 'Tamazula de Gordiano'],
[391, 'Tecalitlán'],
[396, 'Tepatitlán'],
[397, 'Tequila'],
[403, 'Tototlán'],
[404, 'Túxpam'],
[411, 'Villa Hidalgo'],
[413, 'Zacoalco de Torres'],
[414, 'Zapotiltic'],
[416, 'Zapotlanejo'],
[420, 'Toluca'],
[421, 'Acambay'],
[422, 'Almoloya de Juárez'],
[424, 'Amecameca'],
[425, 'Apaxco'],
[426, 'Atlacomulco'],
[428, 'Coatepec de Harinas'],
[430, 'Chicoloapan'],
[431, 'Chiconcuac'],
[432, 'El Oro'],
[433, 'Ixtapan de la Sal'],
[434, 'Ixtlahuaca'],
[435, 'Jilotepec'],
[438, 'Lerma'],
[441, 'Metepec'],
[443, 'Otumba'],
[445, 'San Mateo Atenco'],
[446, 'Tejupilco'],
[448, 'Temascaltepec'],
[449, 'Temoaya'],
[450, 'Tenancingo'],
[451, 'Tenago del Valle'],
[453, 'Santiago Tiangistenco'],
[455, 'Tultepec'],
[456, 'Tultitlán'],
[457, 'Valle de Bravo'],
[460, 'Villa Nicolás Romero'],
[463, 'Zumpango'],
[470, 'Morelia'],
[472, 'Aguililla'],
[476, 'Apatzingán'],
[480, 'Ciudad Hidalgo'],
[483, 'Cotija'],
[484, 'Cuitzeo'],
[492, 'Huetamo'],
[493, 'Jacona'],
[494, 'Jiquilpan'],
[496, 'La Piedad'],
[497, 'Lázaro Cárdenas'],
[498, 'Los Reyes'],
[499, 'Maravatío'],
[501, 'Nueva Italia'],
[506, 'Pátzcuaro'],
[508, 'Purépero'],
[509, 'Puruandiro'],
[512, 'Sahuayo'],
[515, 'Tacámbaro'],
[517, 'Tangancícuaro'],
[519, 'Tepalcatepec'],
[523, 'Tlazazalca'],
[528, 'Uruapan'],
[533, 'Yurécuaro'],
[534, 'Zacapu'],
[535, 'Zamora'],
[536, 'Zinapécuaro'],
[537, 'Zitácuaro'],
[540, 'Cuernavaca'],
[542, 'Cuautla'],
[542, 'Oaxtepec, Morelos'],
[543, 'Jiutepec'],
[544, 'Jojutla'],
[545, 'Puente de Ixtla'],
[546, 'Temixco'],
[548, 'Tetecala'],
[549, 'Yautepec'],
[552, 'Zacatepec'],
[560, 'Tepic'],
[561, 'Acaponeta'],
[562, 'Ahuacatlán'],
[564, 'Compostela'],
[566, 'Ixtlán del Río'],
[571, 'San Blas'],
[573, 'Santiago Ixcuintla'],
[575, 'Túxpam [alternate]'],
[580, 'Apodaca'],
[580, 'Cadereyta'],
[580, 'Cd. Guadalupe'],
[580, 'General Escobedo'],
[580, 'Monterrey'],
[580, 'San Nicolás de los Garza'],
[580, 'San Pedro Garza García'],
[580, 'Santa Catarina'],
[583, 'Allende'],
[592, 'General Zuazua'],
[595, 'Linares'],
[597, 'Montemorelos'],
[599, 'Sabinas Hidalgo'],
[600, 'Salinas Victoria'],
[601, 'El Cercado'],
[601, 'Villa de Santiago'],
[610, 'Oaxaca'],
[613, 'Tlaxiaco'],
[614, 'Huajuapan de León'],
[616, 'Ixtepec'],
[617, 'Juchitán'],
[619, 'Loma Bonita'],
[620, 'Matías Romero'],
[621, 'Miahuatlán'],
[622, 'Ocotlán [alternate]'],
[624, 'Puerto Escondido'],
[626, 'Salina Cruz'],
[627, 'Lagunas'],
[628, 'Tuxtepec'],
[630, 'Pochutla'],
[631, 'San Pedro Tapanatepec'],
[632, 'Santa Lucía del Camino'],
[634, 'Bahías de Huatulco'],
[635, 'Santiago Juxtlahuaca'],
[636, 'Pinotepa Nacional'],
[637, 'Tehuantepec'],
[638, 'Tlacolula'],
[640, 'Zimatlán'],
[650, 'Cholula'],
[650, 'La Resurrección'],
[650, 'Puebla'],
[650, 'San Baltazar Campeche'],
[651, 'N/A'],
[652, 'Acatzingo'],
[654, 'Atlixco'],
[656, 'Cuetzalan'],
[659, 'Huauchinango'],
[660, 'Huejotzingo'],
[662, 'Izúcar de Matamoros'],
[667, 'San Martín Texmelucan'],
[668, 'San Felipe Hueyotlipan'],
[669, 'Tecamachalco'],
[670, 'Tehuacán'],
[671, 'San Lorenzo'],
[672, 'Teziutlán'],
[674, 'Xicotepec de Juárez'],
[676, 'Zacatlán'],
[680, 'Pedro Escobedo'],
[680, 'Querétaro'],
[680, 'Villa Corregidora'],
[681, 'Amealco'],
[685, 'San Juan del Río'],
[686, 'Tequisquiapan'],
[690, 'Chetumal'],
[691, 'Cancún'],
[691, 'Col. Puerto Juárez'],
[692, 'Cozumel'],
[693, 'N/A'],
[694, 'Playa del Carmen'],
[700, 'San Luis Potosí'],
[703, 'Cerritos'],
[705, 'Ciudad Valles'],
[709, 'Matehuala'],
[711, 'Río Verde'],
[716, 'Tamuín'],
[730, 'Culiacán'],
[735, 'Concordia'],
[736, 'Cosala'],
[737, 'Choix'],
[738, 'El Fuerte'],
[739, 'Escuinapa'],
[740, 'Guamúchil'],
[741, 'Guasave'],
[743, 'Los Mochis'],
[743, 'Topolobampo'],
[744, 'Mazatlán'],
[745, 'Mocorito'],
[746, 'Navolato'],
[760, 'Hermosillo'],
[761, 'Agua Prieta'],
[765, 'Caborca'],
[766, 'Cananea'],
[767, 'Ciudad Obregón'],
[767, 'Esperanza'],
[769, 'Empalme'],
[770, 'Guaymas'],
[770, 'San Carlos'],
[771, 'Huatabampo'],
[773, 'Magdalena'],
[776, 'Nacozari de García'],
[777, 'Navojoa'],
[778, 'Nogales'],
[779, 'Puerto Peñasco'],
[780, 'San Luis Río Colorado'],
[790, 'Tamulte'],
[790, 'Villa Hermosa'],
[792, 'Cárdenas'],
[793, 'Ciudad Pemex'],
[794, 'Comalcalco'],
[796, 'Emiliano Zapata'],
[797, 'Frontera'],
[798, 'Huimanguillo'],
[800, 'Jalpa de Méndez'],
[802, 'Macuspana'],
[803, 'Nacajuca'],
[804, 'Paraíso'],
[805, 'Tacotalpa'],
[806, 'Teapa'],
[807, 'Tenosique'],
[810, 'Ciudad Victoria'],
[811, 'Altamira'],
[813, 'Ciudad Madero'],
[813, 'Tampico'],
[814, 'Ciudad Mante'],
[818, 'Matamoros'],
[821, 'Colombia'],
[821, 'Nuevo Laredo'],
[822, 'Reynosa'],
[823, 'Río Bravo'],
[825, 'Soto La Marina'],
[826, 'Valle Hermoso'],
[830, 'Tlaxcala'],
[832, 'Apizaco'],
[834, 'Santa Ana Chiautempan'],
[840, 'Jalapa'],
[841, 'Acayucan'],
[843, 'Agua Dulce'],
[845, 'Álamo'],
[846, 'Altotonga'],
[848, 'Banderilla'],
[849, 'Boca del Río'],
[852, 'Ciudad Mendoza'],
[853, 'Coatepec'],
[854, 'Coatzacoalcos'],
[855, 'Córdoba'],
[856, 'Cosamaloapan'],
[860, 'Cuitláhuac'],
[863, 'Fortín de las Flores'],
[864, 'Gutiérrez Zamora'],
[865, 'Huatusco'],
[867, 'Isla'],
[868, 'Ixtaczoquitlán'],
[869, 'Jáltipan'],
[871, 'Juan Rodríguez Clara'],
[872, 'Villa José Cardel'],
[873, 'Las Choapas'],
[875, 'Naranjos'],
[876, 'Martínez de la Torre'],
[877, 'Minatitlán'],
[878, 'Misantla'],
[879, 'Nanchital'],
[882, 'Orizaba'],
[885, 'Papantla'],
[886, 'Perote'],
[888, 'Poza Rica'],
[889, 'Río Blanco'],
[890, 'San Andrés Tuxtla'],
[891, 'San Rafael'],
[894, 'Platón Sánchez'],
[894, 'Tantoyuca'],
[895, 'Tempoal'],
[898, 'Tierra Blanca'],
[901, 'Tlapacoyan'],
[903, 'Túxpam de Rodríguez Cano'],
[905, 'Cd. Industrial Framboyan'],
[905, 'Veracruz'],
[910, 'Mérida'],
[913, 'Motul'],
[914, 'Oxkutzcab'],
[915, 'Progreso'],
[917, 'Ticul'],
[918, 'Tizimín'],
[920, 'Valladolid'],
[930, 'Zacatecas'],
[933, 'Fresnillo'],
[934, 'Guadalupe'],
[935, 'Jalpa'],
[936, 'Jerez de G. Salinas'],
[938, 'Juchipila'],
[939, 'Loreto'],
[946, 'Nochistlán'],
[958, 'Valparaíso'],
[960, 'Calera de V. Rosales'],
];
citiesPairs.reduce((acc, [k, v]) => (Object.assign(Object.assign({}, acc), { [k]: v })), {});
const checkAlphabet = '0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ';
checkAlphabet
.split('')
.reduce((acc, c, idx) => (Object.assign(Object.assign({}, acc), { [c]: idx })), {});
function clean(input) {
return cleanUnicode(input, ' -.', 'PT');
}
const impl = {
name: 'Portuguese Tax Identification Number',
localName: 'Número de Identificação Fiscal',
abbreviation: 'NIF',
compact(input) {
const [value, err] = clean(input);
if (err) {
throw err;
}
return value;
},
format(input) {
const [value] = clean(input);
return splitAt(value, 3, 6).join(' ');
},
validate(input) {
const [value, error] = clean(input);
if (error) {
return { isValid: false, error };
}
if (value.length !== 9) {
return { isValid: false, error: new InvalidLength() };
}
if (!isdigits(value) || value[0] === '0') {
return { isValid: false, error: new InvalidFormat() };
}
const [front, check] = splitAt(value, -1);
const sum = weightedSum(front, {
weights: [9, 8, 7, 6, 5, 4, 3, 2, 1],
modulus: 11,
});
if (String((11 - sum) % 10) !== check) {
return { isValid: false, error: new InvalidChecksum() };
}
return {
isValid: true,
compact: value,
isIndividual: '1234'.includes(value[0]),
isCompany: !'1234'.includes(value[0]),
};
},
};
const { name, localName, abbreviation, validate, format, compact, } = impl;
const nif = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name,
localName: localName,
abbreviation: abbreviation,
validate: validate,
format: format,
compact: compact
});
Object.assign(Object.assign({}, nif), { name: 'Portuguese Legal Person Identification Number', localName: 'Número de Identificação de Pessoa Colectiva', abbreviation: 'NIPC' });
Object.assign(Object.assign({}, jmbg), { name: 'Serbian Unique Master Citizen Number', localName: 'Јединствени матични број грађана', abbreviation: 'ЈМБГ' });
Object.assign(Object.assign({}, jmbg), { name: 'Slovene Unique Master Citizen Number', localName: 'Enotna Matična Številka Občana', abbreviation: 'EMŠO' });
Object.assign(Object.assign({}, rc), { name: 'Slovak Birth Number', localName: 'Rodné číslo', abbreviation: 'RC' });
var bind = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
/*global toString:true*/
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray$1(val) {
return toString.call(val) === '[object Array]';
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is a Buffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
function isArrayBuffer(val) {
return toString.call(val) === '[object ArrayBuffer]';
}
/**
* Determine if a value is a FormData
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return (typeof FormData !== 'undefined') && (val instanceof FormData);
}
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a plain Object
*
* @param {Object} val The value to test
* @return {boolean} True if value is a plain Object, otherwise false
*/
function isPlainObject(val) {
if (toString.call(val) !== '[object Object]') {
return false;
}
var prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString.call(val) === '[object Blob]';
}
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
function isURLSearchParams(val) {
return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.replace(/^\s*/, '').replace(/\s*$/, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*/
function isStandardBrowserEnv() {
if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
navigator.product === 'NativeScript' ||
navigator.product === 'NS')) {
return false;
}
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray$1(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (isPlainObject(result[key]) && isPlainObject(val)) {
result[key] = merge(result[key], val);
} else if (isPlainObject(val)) {
result[key] = merge({}, val);
} else if (isArray$1(val)) {
result[key] = val.slice();
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
* @return {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
* @return {string} content value without BOM
*/
function stripBOM(content) {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
var utils = {
isArray: isArray$1,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isPlainObject: isPlainObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
extend: extend,
trim: trim,
stripBOM: stripBOM
};
function encode(val) {
return encodeURIComponent(val).
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
var buildURL = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
} else {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
var hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
var InterceptorManager_1 = InterceptorManager;
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
var transformData = function transformData(data, headers, fns) {
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn(data, headers);
});
return data;
};
var isCancel = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
var normalizeHeaderName = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
/**
* Update an Error with the specified config, error code, and response.
*
* @param {Error} error The error to update.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The error.
*/
var enhanceError = function enhanceError(error, config, code, request, response) {
error.config = config;
if (code) {
error.code = code;
}
error.request = request;
error.response = response;
error.isAxiosError = true;
error.toJSON = function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code
};
};
return error;
};
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
var createError = function createError(message, config, code, request, response) {
var error = new Error(message);
return enhanceError(error, config, code, request, response);
};
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
var settle = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
}
};
var cookies = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
var isAbsoluteURL = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
var combineURLs = function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
var buildFullPath = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
// Headers whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
var parseHeaders = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ',