@elastic/ems-client
Version:
JavaScript client library for the Elastic Maps Service
605 lines (599 loc) • 25.4 kB
JavaScript
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import _ from 'lodash';
import { TMSService } from './tms_service';
import { FileLayer } from './file_layer';
import semverCoerce from 'semver/functions/coerce';
import semverValid from 'semver/functions/valid';
import semverMajor from 'semver/functions/major';
import semverMinor from 'semver/functions/minor';
import { format as formatUrl, parse as parseUrl } from 'url';
import { toAbsoluteUrl } from './utils';
import { LRUCache } from 'lru-cache';
var REST_API_REGEX = /\d{4}-\d{2}-\d{2}/;
export var LATEST_API_URL_PATH = 'latest';
/**
* plugins cannot have upstream dependencies on core/*-kibana.
* Work-around by copy-pasting modifyUrl routine here.
* @param url
* @param block
*/
function modifyUrlLocal(url, block) {
var parsed = parseUrl(url, true);
// copy over the most specific version of each
// property. By default, the parsed url includes
// several conflicting properties (like path and
// pathname + search, or search and query) and keeping
// track of which property is actually used when they
// are formatted is harder than necessary
var meaningfulParts = {
protocol: parsed.protocol,
slashes: parsed.slashes,
auth: parsed.auth,
hostname: parsed.hostname,
port: parsed.port,
pathname: parsed.pathname,
query: parsed.query || {},
hash: parsed.hash
};
// the block modifies the meaningfulParts object, or returns a new one
var modifiedParts = block(meaningfulParts) || meaningfulParts;
// format the modified/replaced meaningfulParts back into a url
return formatUrl({
protocol: modifiedParts.protocol,
slashes: modifiedParts.slashes,
auth: modifiedParts.auth,
hostname: modifiedParts.hostname,
port: modifiedParts.port,
pathname: modifiedParts.pathname,
query: modifiedParts.query,
hash: modifiedParts.hash
});
}
var extendUrl = function extendUrl(url, props) {
return modifyUrlLocal(url, function (parsed) {
return _.merge(parsed, props);
});
};
/**
* Unescape a url template that was escaped by encodeURI() so leaflet
* will be able to correctly locate the variables in the template
* @param {String} url
* @return {String}
*/
var unescapeTemplateVars = function unescapeTemplateVars(url) {
var ENCODED_TEMPLATE_VARS_RE = /%7B(\w+?)%7D/g;
return url.replace(ENCODED_TEMPLATE_VARS_RE, function (total, varName) {
return "{".concat(varName, "}");
});
};
//this is not the default locale from Kibana, but the default locale supported by the Elastic Maps Service
var DEFAULT_LANGUAGE = 'en';
export var EMSClient = /*#__PURE__*/function () {
function EMSClient(config) {
_classCallCheck(this, EMSClient);
_defineProperty(this, "EMS_LOAD_TIMEOUT", 32000);
_defineProperty(this, "_queryParams", void 0);
_defineProperty(this, "_appVersion", void 0);
_defineProperty(this, "_fetchFunction", void 0);
_defineProperty(this, "_sanitizer", void 0);
_defineProperty(this, "_fileApiUrl", void 0);
_defineProperty(this, "_tileApiUrl", void 0);
_defineProperty(this, "_emsVersion", void 0);
_defineProperty(this, "_emsLandingPageUrl", void 0);
_defineProperty(this, "_language", void 0);
_defineProperty(this, "_proxyPath", void 0);
_defineProperty(this, "_cache", void 0);
_defineProperty(this, "_isRestApi", false);
/**
* these methods are assigned outside the constructor
*/
_defineProperty(this, "_getMainCatalog", void 0);
_defineProperty(this, "_getDefaultTMSCatalog", void 0);
_defineProperty(this, "_getDefaultFileCatalog", void 0);
_defineProperty(this, "_loadTMSServices", void 0);
_defineProperty(this, "_loadFileLayers", void 0);
// Remove kbnVersion in 8.0
if ('kbnVersion' in config) {
console.warn('The "kbnVersion" parameter for ems-client is deprecated. Please use "appVersion" instead.');
this._appVersion = config.kbnVersion;
} else {
this._appVersion = config.appVersion;
}
this._queryParams = {
elastic_tile_service_tos: 'agree',
my_app_name: config.appName || 'kibana',
my_app_version: this._appVersion
};
this._sanitizer = config.htmlSanitizer ? config.htmlSanitizer : function (x) {
return x;
};
this._tileApiUrl = config.tileApiUrl;
this._fileApiUrl = config.fileApiUrl;
this._emsVersion = this._getEmsVersion(config.emsVersion);
this._isRestApi = this._emsVersion == config.emsVersion;
this._emsLandingPageUrl = config.landingPageUrl || '';
this._language = config.language || DEFAULT_LANGUAGE;
this._fetchFunction = config.fetchFunction;
this._proxyPath = config.proxyPath || '';
this._cache = new LRUCache({
max: config.cacheSize || 10
});
this._invalidateSettings();
}
return _createClass(EMSClient, [{
key: "getDefaultLocale",
value: function getDefaultLocale() {
return DEFAULT_LANGUAGE;
}
}, {
key: "getLocale",
value: function getLocale() {
return this._language;
}
}, {
key: "getValueInLanguage",
value: function getValueInLanguage(i18nObject) {
if (!i18nObject) {
return '';
}
return i18nObject[this._language] ? i18nObject[this._language] : i18nObject[DEFAULT_LANGUAGE];
}
/**
* this internal method is overridden by the tests to simulate custom manifest.
*/
}, {
key: "getManifest",
value: (function () {
var _getManifest = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(endpointUrl) {
var url, response, _t;
return _regenerator().w(function (_context) {
while (1) switch (_context.p = _context.n) {
case 0:
_context.p = 0;
url = extendUrl(endpointUrl, {
query: this._queryParams
});
_context.n = 1;
return this._fetchWithTimeout(url);
case 1:
response = _context.v;
if (response.ok) {
_context.n = 2;
break;
}
throw new Error(response.statusText);
case 2:
if (!response) {
_context.n = 4;
break;
}
_context.n = 3;
return response.json();
case 3:
return _context.a(2, _context.v);
case 4:
throw new Error('Response not found');
case 5:
_context.n = 8;
break;
case 6:
_context.p = 6;
_t = _context.v;
if (!(_t instanceof Error)) {
_context.n = 7;
break;
}
throw _t;
case 7:
throw new Error('Unknown error', {
cause: _t
});
case 8:
return _context.a(2);
}
}, _callee, this, [[0, 6]]);
}));
function getManifest(_x) {
return _getManifest.apply(this, arguments);
}
return getManifest;
}()
/**
* Add optional query-parameters to all requests
*
* @param additionalQueryParams
*/
)
}, {
key: "addQueryParams",
value: function addQueryParams(additionalQueryParams) {
for (var _key in additionalQueryParams) {
if (Object.prototype.hasOwnProperty.call(additionalQueryParams, _key)) {
if (additionalQueryParams[_key] !== this._queryParams[_key]) {
//changes detected.
this._queryParams = _.assign({}, this._queryParams, additionalQueryParams);
this._invalidateSettings();
break;
}
}
}
}
}, {
key: "getMainManifest",
value: function () {
var _getMainManifest = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
return _regenerator().w(function (_context2) {
while (1) switch (_context2.n) {
case 0:
_context2.n = 1;
return this._getMainCatalog();
case 1:
return _context2.a(2, _context2.v);
}
}, _callee2, this);
}));
function getMainManifest() {
return _getMainManifest.apply(this, arguments);
}
return getMainManifest;
}()
}, {
key: "getDefaultFileManifest",
value: function () {
var _getDefaultFileManifest = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3() {
return _regenerator().w(function (_context3) {
while (1) switch (_context3.n) {
case 0:
_context3.n = 1;
return this._getDefaultFileCatalog();
case 1:
return _context3.a(2, _context3.v);
}
}, _callee3, this);
}));
function getDefaultFileManifest() {
return _getDefaultFileManifest.apply(this, arguments);
}
return getDefaultFileManifest;
}()
}, {
key: "getDefaultTMSManifest",
value: function () {
var _getDefaultTMSManifest = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4() {
return _regenerator().w(function (_context4) {
while (1) switch (_context4.n) {
case 0:
_context4.n = 1;
return this._getDefaultTMSCatalog();
case 1:
return _context4.a(2, _context4.v);
}
}, _callee4, this);
}));
function getDefaultTMSManifest() {
return _getDefaultTMSManifest.apply(this, arguments);
}
return getDefaultTMSManifest;
}()
}, {
key: "getFileLayers",
value: function () {
var _getFileLayers = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() {
return _regenerator().w(function (_context5) {
while (1) switch (_context5.n) {
case 0:
_context5.n = 1;
return this._loadFileLayers();
case 1:
return _context5.a(2, _context5.v);
}
}, _callee5, this);
}));
function getFileLayers() {
return _getFileLayers.apply(this, arguments);
}
return getFileLayers;
}()
}, {
key: "getTMSServices",
value: function () {
var _getTMSServices = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6() {
return _regenerator().w(function (_context6) {
while (1) switch (_context6.n) {
case 0:
_context6.n = 1;
return this._loadTMSServices();
case 1:
return _context6.a(2, _context6.v);
}
}, _callee6, this);
}));
function getTMSServices() {
return _getTMSServices.apply(this, arguments);
}
return getTMSServices;
}()
}, {
key: "cacheGeoJson",
value: function cacheGeoJson(layerId, geoJson) {
this._cache.set(layerId, geoJson);
return;
}
}, {
key: "getCachedGeoJson",
value: function getCachedGeoJson(layerId) {
return this._cache.get(layerId);
}
}, {
key: "getEmsVersion",
value: function getEmsVersion() {
return this._emsVersion;
}
}, {
key: "getTileApiUrl",
value: function getTileApiUrl() {
return this._tileApiUrl;
}
}, {
key: "getFileApiUrl",
value: function getFileApiUrl() {
return this._fileApiUrl;
}
}, {
key: "getLandingPageUrl",
value: function getLandingPageUrl() {
return this._emsLandingPageUrl;
}
}, {
key: "sanitizeHtml",
value: function sanitizeHtml(html) {
return this._sanitizer(html);
}
}, {
key: "extendUrlWithParams",
value: function extendUrlWithParams(url) {
return unescapeTemplateVars(extendUrl(url, {
query: this._queryParams
}));
}
}, {
key: "findFileLayerById",
value: function () {
var _findFileLayerById = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(id) {
var fileLayers, i;
return _regenerator().w(function (_context7) {
while (1) switch (_context7.n) {
case 0:
_context7.n = 1;
return this.getFileLayers();
case 1:
fileLayers = _context7.v;
i = 0;
case 2:
if (!(i < fileLayers.length)) {
_context7.n = 4;
break;
}
if (!fileLayers[i].hasId(id)) {
_context7.n = 3;
break;
}
return _context7.a(2, fileLayers[i]);
case 3:
i++;
_context7.n = 2;
break;
case 4:
return _context7.a(2);
}
}, _callee7, this);
}));
function findFileLayerById(_x2) {
return _findFileLayerById.apply(this, arguments);
}
return findFileLayerById;
}()
}, {
key: "findTMSServiceById",
value: function () {
var _findTMSServiceById = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8(id) {
var tmsServices, i;
return _regenerator().w(function (_context8) {
while (1) switch (_context8.n) {
case 0:
_context8.n = 1;
return this.getTMSServices();
case 1:
tmsServices = _context8.v;
i = 0;
case 2:
if (!(i < tmsServices.length)) {
_context8.n = 4;
break;
}
if (!tmsServices[i].hasId(id)) {
_context8.n = 3;
break;
}
return _context8.a(2, tmsServices[i]);
case 3:
i++;
_context8.n = 2;
break;
case 4:
return _context8.a(2);
}
}, _callee8, this);
}));
function findTMSServiceById(_x3) {
return _findTMSServiceById.apply(this, arguments);
}
return findTMSServiceById;
}()
}, {
key: "_getEmsVersion",
value: function _getEmsVersion(version) {
if (version !== null && version !== void 0 && version.match(REST_API_REGEX)) {
return version;
}
var semverVersion = semverValid(semverCoerce(version));
if (semverVersion) {
return "v".concat(semverMajor(semverVersion), ".").concat(semverMinor(semverVersion));
} else {
throw new Error("Invalid version: ".concat(version));
}
}
}, {
key: "_fetchWithTimeout",
value: function _fetchWithTimeout(url) {
var _this = this;
return new Promise(function (resolve, reject) {
var timer = setTimeout(function () {
return reject(new Error("Request to ".concat(url, " timed out")));
}, _this.EMS_LOAD_TIMEOUT);
_this._fetchFunction(url).then(function (response) {
clearTimeout(timer);
resolve(response);
}, function (err) {
clearTimeout(timer);
reject(err);
});
});
}
}, {
key: "_invalidateSettings",
value: function _invalidateSettings() {
var _this2 = this;
this._cache.clear();
this._getMainCatalog = _.once(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee9() {
var services, version, _version;
return _regenerator().w(function (_context9) {
while (1) switch (_context9.n) {
case 0:
services = [];
if (_this2._tileApiUrl) {
version = _this2._isRestApi ? LATEST_API_URL_PATH : _this2._emsVersion;
services.push({
type: 'tms',
manifest: toAbsoluteUrl(_this2._tileApiUrl, "".concat(version, "/manifest"))
});
}
if (_this2._fileApiUrl) {
_version = _this2._isRestApi ? LATEST_API_URL_PATH : _this2._emsVersion;
services.push({
type: 'file',
manifest: toAbsoluteUrl(_this2._fileApiUrl, "".concat(_version, "/manifest"))
});
}
return _context9.a(2, {
services: services
});
}
}, _callee9);
})));
this._getDefaultTMSCatalog = _.once(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee0() {
var catalogue, firstService, url;
return _regenerator().w(function (_context0) {
while (1) switch (_context0.n) {
case 0:
_context0.n = 1;
return _this2._getMainCatalog();
case 1:
catalogue = _context0.v;
firstService = catalogue.services.find(function (service) {
return service.type === 'tms';
});
if (firstService) {
_context0.n = 2;
break;
}
return _context0.a(2, {
services: []
});
case 2:
url = _this2._proxyPath + firstService.manifest;
_context0.n = 3;
return _this2.getManifest(url);
case 3:
return _context0.a(2, _context0.v);
}
}, _callee0);
})));
this._getDefaultFileCatalog = _.once(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee1() {
var catalogue, firstService, url;
return _regenerator().w(function (_context1) {
while (1) switch (_context1.n) {
case 0:
_context1.n = 1;
return _this2._getMainCatalog();
case 1:
catalogue = _context1.v;
firstService = catalogue.services.find(function (service) {
return service.type === 'file';
});
if (firstService) {
_context1.n = 2;
break;
}
return _context1.a(2, {
layers: []
});
case 2:
url = _this2._proxyPath + firstService.manifest;
_context1.n = 3;
return _this2.getManifest(url);
case 3:
return _context1.a(2, _context1.v);
}
}, _callee1);
})));
//Cache the actual instances of TMSService as these in turn cache sub-manifests for the style-files
this._loadTMSServices = _.once(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee10() {
var tmsManifest;
return _regenerator().w(function (_context10) {
while (1) switch (_context10.n) {
case 0:
_context10.n = 1;
return _this2._getDefaultTMSCatalog();
case 1:
tmsManifest = _context10.v;
return _context10.a(2, tmsManifest.services.map(function (serviceConfig) {
return new TMSService(serviceConfig, _this2, _this2._proxyPath);
}));
}
}, _callee10);
})));
this._loadFileLayers = _.once(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee11() {
var fileManifest;
return _regenerator().w(function (_context11) {
while (1) switch (_context11.n) {
case 0:
_context11.n = 1;
return _this2._getDefaultFileCatalog();
case 1:
fileManifest = _context11.v;
return _context11.a(2, fileManifest.layers.map(function (layerConfig) {
return new FileLayer(layerConfig, _this2, _this2._proxyPath);
}));
}
}, _callee11);
})));
}
}]);
}();