Leniency.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  2. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  3. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  4. import isValidNumber from '../isValid.js';
  5. import parseDigits from '../helpers/parseDigits.js';
  6. import matchPhoneNumberStringAgainstPhoneNumber from './matchPhoneNumberStringAgainstPhoneNumber.js';
  7. import Metadata from '../metadata.js';
  8. import getCountryByCallingCode from '../helpers/getCountryByCallingCode.js';
  9. import { chooseFormatForNumber } from '../format.js';
  10. import { startsWith, endsWith } from './util.js';
  11. /**
  12. * Leniency when finding potential phone numbers in text segments
  13. * The levels here are ordered in increasing strictness.
  14. */
  15. export default {
  16. /**
  17. * Phone numbers accepted are "possible", but not necessarily "valid".
  18. */
  19. POSSIBLE: function POSSIBLE(phoneNumber, _ref) {
  20. var candidate = _ref.candidate,
  21. metadata = _ref.metadata;
  22. return true;
  23. },
  24. /**
  25. * Phone numbers accepted are "possible" and "valid".
  26. * Numbers written in national format must have their national-prefix
  27. * present if it is usually written for a number of this type.
  28. */
  29. VALID: function VALID(phoneNumber, _ref2) {
  30. var candidate = _ref2.candidate,
  31. defaultCountry = _ref2.defaultCountry,
  32. metadata = _ref2.metadata;
  33. if (!phoneNumber.isValid() || !containsOnlyValidXChars(phoneNumber, candidate, metadata)) {
  34. return false;
  35. } // Skipped for simplicity.
  36. // return isNationalPrefixPresentIfRequired(phoneNumber, { defaultCountry, metadata })
  37. return true;
  38. },
  39. /**
  40. * Phone numbers accepted are "valid" and
  41. * are grouped in a possible way for this locale. For example, a US number written as
  42. * "65 02 53 00 00" and "650253 0000" are not accepted at this leniency level, whereas
  43. * "650 253 0000", "650 2530000" or "6502530000" are.
  44. * Numbers with more than one '/' symbol in the national significant number
  45. * are also dropped at this level.
  46. *
  47. * Warning: This level might result in lower coverage especially for regions outside of
  48. * country code "+1". If you are not sure about which level to use,
  49. * email the discussion group libphonenumber-discuss@googlegroups.com.
  50. */
  51. STRICT_GROUPING: function STRICT_GROUPING(phoneNumber, _ref3) {
  52. var candidate = _ref3.candidate,
  53. defaultCountry = _ref3.defaultCountry,
  54. metadata = _ref3.metadata,
  55. regExpCache = _ref3.regExpCache;
  56. if (!phoneNumber.isValid() || !containsOnlyValidXChars(phoneNumber, candidate, metadata) || containsMoreThanOneSlashInNationalNumber(phoneNumber, candidate) || !isNationalPrefixPresentIfRequired(phoneNumber, {
  57. defaultCountry: defaultCountry,
  58. metadata: metadata
  59. })) {
  60. return false;
  61. }
  62. return checkNumberGroupingIsValid(phoneNumber, candidate, metadata, allNumberGroupsRemainGrouped, regExpCache);
  63. },
  64. /**
  65. * Phone numbers accepted are "valid" and are grouped in the same way
  66. * that we would have formatted it, or as a single block.
  67. * For example, a US number written as "650 2530000" is not accepted
  68. * at this leniency level, whereas "650 253 0000" or "6502530000" are.
  69. * Numbers with more than one '/' symbol are also dropped at this level.
  70. *
  71. * Warning: This level might result in lower coverage especially for regions outside of
  72. * country code "+1". If you are not sure about which level to use, email the discussion group
  73. * libphonenumber-discuss@googlegroups.com.
  74. */
  75. EXACT_GROUPING: function EXACT_GROUPING(phoneNumber, _ref4) {
  76. var candidate = _ref4.candidate,
  77. defaultCountry = _ref4.defaultCountry,
  78. metadata = _ref4.metadata,
  79. regExpCache = _ref4.regExpCache;
  80. if (!phoneNumber.isValid() || !containsOnlyValidXChars(phoneNumber, candidate, metadata) || containsMoreThanOneSlashInNationalNumber(phoneNumber, candidate) || !isNationalPrefixPresentIfRequired(phoneNumber, {
  81. defaultCountry: defaultCountry,
  82. metadata: metadata
  83. })) {
  84. return false;
  85. }
  86. return checkNumberGroupingIsValid(phoneNumber, candidate, metadata, allNumberGroupsAreExactlyPresent, regExpCache);
  87. }
  88. };
  89. function containsOnlyValidXChars(phoneNumber, candidate, metadata) {
  90. // The characters 'x' and 'X' can be (1) a carrier code, in which case they always precede the
  91. // national significant number or (2) an extension sign, in which case they always precede the
  92. // extension number. We assume a carrier code is more than 1 digit, so the first case has to
  93. // have more than 1 consecutive 'x' or 'X', whereas the second case can only have exactly 1 'x'
  94. // or 'X'. We ignore the character if it appears as the last character of the string.
  95. for (var index = 0; index < candidate.length - 1; index++) {
  96. var charAtIndex = candidate.charAt(index);
  97. if (charAtIndex === 'x' || charAtIndex === 'X') {
  98. var charAtNextIndex = candidate.charAt(index + 1);
  99. if (charAtNextIndex === 'x' || charAtNextIndex === 'X') {
  100. // This is the carrier code case, in which the 'X's always precede the national
  101. // significant number.
  102. index++;
  103. if (matchPhoneNumberStringAgainstPhoneNumber(candidate.substring(index), phoneNumber, metadata) !== 'NSN_MATCH') {
  104. return false;
  105. } // This is the extension sign case, in which the 'x' or 'X' should always precede the
  106. // extension number.
  107. } else {
  108. var ext = parseDigits(candidate.substring(index));
  109. if (ext) {
  110. if (phoneNumber.ext !== ext) {
  111. return false;
  112. }
  113. } else {
  114. if (phoneNumber.ext) {
  115. return false;
  116. }
  117. }
  118. }
  119. }
  120. }
  121. return true;
  122. }
  123. function isNationalPrefixPresentIfRequired(phoneNumber, _ref5) {
  124. var defaultCountry = _ref5.defaultCountry,
  125. _metadata = _ref5.metadata;
  126. // First, check how we deduced the country code. If it was written in international format, then
  127. // the national prefix is not required.
  128. if (phoneNumber.__countryCallingCodeSource !== 'FROM_DEFAULT_COUNTRY') {
  129. return true;
  130. }
  131. var metadata = new Metadata(_metadata);
  132. metadata.selectNumberingPlan(phoneNumber.countryCallingCode);
  133. var phoneNumberRegion = phoneNumber.country || getCountryByCallingCode(phoneNumber.countryCallingCode, {
  134. nationalNumber: phoneNumber.nationalNumber,
  135. defaultCountry: defaultCountry,
  136. metadata: metadata
  137. }); // Check if a national prefix should be present when formatting this number.
  138. var nationalNumber = phoneNumber.nationalNumber;
  139. var format = chooseFormatForNumber(metadata.numberingPlan.formats(), nationalNumber); // To do this, we check that a national prefix formatting rule was present
  140. // and that it wasn't just the first-group symbol ($1) with punctuation.
  141. if (format.nationalPrefixFormattingRule()) {
  142. if (metadata.numberingPlan.nationalPrefixIsOptionalWhenFormattingInNationalFormat()) {
  143. // The national-prefix is optional in these cases, so we don't need to check if it was present.
  144. return true;
  145. }
  146. if (!format.usesNationalPrefix()) {
  147. // National Prefix not needed for this number.
  148. return true;
  149. }
  150. return Boolean(phoneNumber.nationalPrefix);
  151. }
  152. return true;
  153. }
  154. export function containsMoreThanOneSlashInNationalNumber(phoneNumber, candidate) {
  155. var firstSlashInBodyIndex = candidate.indexOf('/');
  156. if (firstSlashInBodyIndex < 0) {
  157. // No slashes, this is okay.
  158. return false;
  159. } // Now look for a second one.
  160. var secondSlashInBodyIndex = candidate.indexOf('/', firstSlashInBodyIndex + 1);
  161. if (secondSlashInBodyIndex < 0) {
  162. // Only one slash, this is okay.
  163. return false;
  164. } // If the first slash is after the country calling code, this is permitted.
  165. var candidateHasCountryCode = phoneNumber.__countryCallingCodeSource === 'FROM_NUMBER_WITH_PLUS_SIGN' || phoneNumber.__countryCallingCodeSource === 'FROM_NUMBER_WITHOUT_PLUS_SIGN';
  166. if (candidateHasCountryCode && parseDigits(candidate.substring(0, firstSlashInBodyIndex)) === phoneNumber.countryCallingCode) {
  167. // Any more slashes and this is illegal.
  168. return candidate.slice(secondSlashInBodyIndex + 1).indexOf('/') >= 0;
  169. }
  170. return true;
  171. }
  172. function checkNumberGroupingIsValid(number, candidate, metadata, checkGroups, regExpCache) {
  173. throw new Error('This part of code hasn\'t been ported');
  174. var normalizedCandidate = normalizeDigits(candidate, true
  175. /* keep non-digits */
  176. );
  177. var formattedNumberGroups = getNationalNumberGroups(metadata, number, null);
  178. if (checkGroups(metadata, number, normalizedCandidate, formattedNumberGroups)) {
  179. return true;
  180. } // If this didn't pass, see if there are any alternate formats that match, and try them instead.
  181. var alternateFormats = MetadataManager.getAlternateFormatsForCountry(number.getCountryCode());
  182. var nationalSignificantNumber = util.getNationalSignificantNumber(number);
  183. if (alternateFormats) {
  184. for (var _iterator = _createForOfIteratorHelperLoose(alternateFormats.numberFormats()), _step; !(_step = _iterator()).done;) {
  185. var alternateFormat = _step.value;
  186. if (alternateFormat.leadingDigitsPatterns().length > 0) {
  187. // There is only one leading digits pattern for alternate formats.
  188. var leadingDigitsRegExp = regExpCache.getPatternForRegExp('^' + alternateFormat.leadingDigitsPatterns()[0]);
  189. if (!leadingDigitsRegExp.test(nationalSignificantNumber)) {
  190. // Leading digits don't match; try another one.
  191. continue;
  192. }
  193. }
  194. formattedNumberGroups = getNationalNumberGroups(metadata, number, alternateFormat);
  195. if (checkGroups(metadata, number, normalizedCandidate, formattedNumberGroups)) {
  196. return true;
  197. }
  198. }
  199. }
  200. return false;
  201. }
  202. /**
  203. * Helper method to get the national-number part of a number, formatted without any national
  204. * prefix, and return it as a set of digit blocks that would be formatted together following
  205. * standard formatting rules.
  206. */
  207. function getNationalNumberGroups(metadata, number, formattingPattern) {
  208. throw new Error('This part of code hasn\'t been ported');
  209. if (formattingPattern) {
  210. // We format the NSN only, and split that according to the separator.
  211. var nationalSignificantNumber = util.getNationalSignificantNumber(number);
  212. return util.formatNsnUsingPattern(nationalSignificantNumber, formattingPattern, 'RFC3966', metadata).split('-');
  213. } // This will be in the format +CC-DG1-DG2-DGX;ext=EXT where DG1..DGX represents groups of digits.
  214. var rfc3966Format = formatNumber(number, 'RFC3966', metadata); // We remove the extension part from the formatted string before splitting it into different
  215. // groups.
  216. var endIndex = rfc3966Format.indexOf(';');
  217. if (endIndex < 0) {
  218. endIndex = rfc3966Format.length;
  219. } // The country-code will have a '-' following it.
  220. var startIndex = rfc3966Format.indexOf('-') + 1;
  221. return rfc3966Format.slice(startIndex, endIndex).split('-');
  222. }
  223. function allNumberGroupsAreExactlyPresent(metadata, number, normalizedCandidate, formattedNumberGroups) {
  224. throw new Error('This part of code hasn\'t been ported');
  225. var candidateGroups = normalizedCandidate.split(NON_DIGITS_PATTERN); // Set this to the last group, skipping it if the number has an extension.
  226. var candidateNumberGroupIndex = number.hasExtension() ? candidateGroups.length - 2 : candidateGroups.length - 1; // First we check if the national significant number is formatted as a block.
  227. // We use contains and not equals, since the national significant number may be present with
  228. // a prefix such as a national number prefix, or the country code itself.
  229. if (candidateGroups.length == 1 || candidateGroups[candidateNumberGroupIndex].contains(util.getNationalSignificantNumber(number))) {
  230. return true;
  231. } // Starting from the end, go through in reverse, excluding the first group, and check the
  232. // candidate and number groups are the same.
  233. var formattedNumberGroupIndex = formattedNumberGroups.length - 1;
  234. while (formattedNumberGroupIndex > 0 && candidateNumberGroupIndex >= 0) {
  235. if (candidateGroups[candidateNumberGroupIndex] !== formattedNumberGroups[formattedNumberGroupIndex]) {
  236. return false;
  237. }
  238. formattedNumberGroupIndex--;
  239. candidateNumberGroupIndex--;
  240. } // Now check the first group. There may be a national prefix at the start, so we only check
  241. // that the candidate group ends with the formatted number group.
  242. return candidateNumberGroupIndex >= 0 && endsWith(candidateGroups[candidateNumberGroupIndex], formattedNumberGroups[0]);
  243. }
  244. function allNumberGroupsRemainGrouped(metadata, number, normalizedCandidate, formattedNumberGroups) {
  245. throw new Error('This part of code hasn\'t been ported');
  246. var fromIndex = 0;
  247. if (number.getCountryCodeSource() !== CountryCodeSource.FROM_DEFAULT_COUNTRY) {
  248. // First skip the country code if the normalized candidate contained it.
  249. var countryCode = String(number.getCountryCode());
  250. fromIndex = normalizedCandidate.indexOf(countryCode) + countryCode.length();
  251. } // Check each group of consecutive digits are not broken into separate groupings in the
  252. // {@code normalizedCandidate} string.
  253. for (var i = 0; i < formattedNumberGroups.length; i++) {
  254. // Fails if the substring of {@code normalizedCandidate} starting from {@code fromIndex}
  255. // doesn't contain the consecutive digits in formattedNumberGroups[i].
  256. fromIndex = normalizedCandidate.indexOf(formattedNumberGroups[i], fromIndex);
  257. if (fromIndex < 0) {
  258. return false;
  259. } // Moves {@code fromIndex} forward.
  260. fromIndex += formattedNumberGroups[i].length();
  261. if (i == 0 && fromIndex < normalizedCandidate.length()) {
  262. // We are at the position right after the NDC. We get the region used for formatting
  263. // information based on the country code in the phone number, rather than the number itself,
  264. // as we do not need to distinguish between different countries with the same country
  265. // calling code and this is faster.
  266. var region = util.getRegionCodeForCountryCode(number.getCountryCode());
  267. if (util.getNddPrefixForRegion(region, true) != null && Character.isDigit(normalizedCandidate.charAt(fromIndex))) {
  268. // This means there is no formatting symbol after the NDC. In this case, we only
  269. // accept the number if there is no formatting symbol at all in the number, except
  270. // for extensions. This is only important for countries with national prefixes.
  271. var nationalSignificantNumber = util.getNationalSignificantNumber(number);
  272. return startsWith(normalizedCandidate.slice(fromIndex - formattedNumberGroups[i].length), nationalSignificantNumber);
  273. }
  274. }
  275. } // The check here makes sure that we haven't mistakenly already used the extension to
  276. // match the last group of the subscriber number. Note the extension cannot have
  277. // formatting in-between digits.
  278. return normalizedCandidate.slice(fromIndex).contains(number.getExtension());
  279. }
  280. //# sourceMappingURL=Leniency.js.map