libphonenumber-geo-carrier
Version:
This library includes the geocoding, carrier mapping and timezone mapping functionalities that are available in some of googles libphonenumber libraries but not in libphonenumber-js (a port of libphonenumber).
237 lines (225 loc) • 11.3 kB
JavaScript
;
var fs = require('fs');
var util = require('util');
var bson = require('bson');
var path = require('path');
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var access = util.promisify(fs.access);
var readFile = util.promisify(fs.readFile);
/**
* Maps the dataPath and prefix to geocode, carrier, timezones or null if this info could not be extracted
*
* **Note:** Timezones are returned as single string joined with `&`
*
* @param dataPath Path of the metadata bson file to use
* @param nationalNumber The national (significant) number without whitespaces e.g. `2133734253`
*/
var getCode = function (dataPath, nationalNumber) { return __awaiter(void 0, void 0, void 0, function () {
var bData, data, prefix, description;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 3, , 4]);
return [4 /*yield*/, access(dataPath)];
case 1:
_a.sent();
return [4 /*yield*/, readFile(dataPath)];
case 2:
bData = _a.sent();
data = bson.deserialize(bData);
prefix = nationalNumber;
// Find the longest match
while (prefix.length > 0) {
description = data[prefix];
if (description) {
return [2 /*return*/, description];
}
// Remove a character from the end
prefix = prefix.substring(0, prefix.length - 1);
}
return [3 /*break*/, 4];
case 3:
_a.sent();
return [3 /*break*/, 4];
case 4: return [2 /*return*/, null];
}
});
}); };
/**
* Provides geographical information related to the phone number
*
* @param phonenumber The phone number
* @param locale The preferred locale to use (falls back to `en` if there are no localized carrier infos for the given locale)
*/
var geocoder = function (phonenumber_1) {
var args_1 = [];
for (var _i = 1; _i < arguments.length; _i++) {
args_1[_i - 1] = arguments[_i];
}
return __awaiter(void 0, __spreadArray([phonenumber_1], args_1, true), void 0, function (phonenumber, locale) {
var nationalNumber, countryCallingCode, dataPath, code;
if (locale === void 0) { locale = 'en'; }
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
nationalNumber = phonenumber === null || phonenumber === void 0 ? void 0 : phonenumber.nationalNumber.toString();
countryCallingCode = phonenumber === null || phonenumber === void 0 ? void 0 : phonenumber.countryCallingCode.toString();
if (!nationalNumber || !countryCallingCode) {
return [2 /*return*/, null];
}
dataPath = path.join(__dirname, '../resources/geocodes/', locale, "".concat(countryCallingCode, ".bson"));
return [4 /*yield*/, getCode(dataPath, nationalNumber)];
case 1:
code = _a.sent();
if (code) {
return [2 /*return*/, code];
}
if (!(locale !== 'en')) return [3 /*break*/, 3];
// Try fallback to english
dataPath = path.join(__dirname, '../resources/geocodes/', 'en', "".concat(countryCallingCode, ".bson"));
return [4 /*yield*/, getCode(dataPath, nationalNumber)];
case 2:
// return await getCode(dataPath, prefix)
return [2 /*return*/, _a.sent()];
case 3: return [2 /*return*/, null];
}
});
});
};
/**
* Maps the phone number to the original carrier
*
* **Note:** This method cannot provide data about the current carrier of the phone number,
* only the original carrier who is assigned to the corresponding range.
* @see https://github.com/google/libphonenumber#mapping-phone-numbers-to-original-carriers
*
* @param phonenumber The phone number
* @param locale The preferred locale to use (falls back to `en` if there are no localized carrier infos for the given locale)
*/
var carrier = function (phonenumber_1) {
var args_1 = [];
for (var _i = 1; _i < arguments.length; _i++) {
args_1[_i - 1] = arguments[_i];
}
return __awaiter(void 0, __spreadArray([phonenumber_1], args_1, true), void 0, function (phonenumber, locale) {
var nationalNumber, countryCallingCode, dataPath, code;
if (locale === void 0) { locale = 'en'; }
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!phonenumber) {
return [2 /*return*/, null];
}
nationalNumber = phonenumber === null || phonenumber === void 0 ? void 0 : phonenumber.nationalNumber.toString();
countryCallingCode = phonenumber === null || phonenumber === void 0 ? void 0 : phonenumber.countryCallingCode.toString();
if (!nationalNumber || !countryCallingCode) {
return [2 /*return*/, null];
}
dataPath = path.join(__dirname, '../resources/carrier/', locale, "".concat(countryCallingCode, ".bson"));
return [4 /*yield*/, getCode(dataPath, nationalNumber)];
case 1:
code = _a.sent();
if (code) {
return [2 /*return*/, code];
}
if (!(locale !== 'en')) return [3 /*break*/, 3];
// Try fallback to english
dataPath = path.join(__dirname, '../resources/carrier/', 'en', "".concat(countryCallingCode, ".bson"));
return [4 /*yield*/, getCode(dataPath, nationalNumber)];
case 2:
// return await getCode(dataPath, prefix)
return [2 /*return*/, _a.sent()];
case 3: return [2 /*return*/, null];
}
});
});
};
/**
* Provides all timezones related to the phone number
* @param phonenumber The phone number
*/
var timezones = function (phonenumber) { return __awaiter(void 0, void 0, void 0, function () {
var nr, dataPath, zones;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
nr = phonenumber === null || phonenumber === void 0 ? void 0 : phonenumber.number.toString();
if (!nr) {
return [2 /*return*/, null];
}
nr = nr.replace(/^\+/, '');
dataPath = path.join(__dirname, '../resources/timezones.bson');
return [4 /*yield*/, getCode(dataPath, nr)];
case 1:
zones = _a.sent();
if (typeof zones === 'string') {
return [2 /*return*/, zones.split('&')];
}
return [2 /*return*/, null];
}
});
}); };
exports.carrier = carrier;
exports.geocoder = geocoder;
exports.timezones = timezones;