UNPKG

@dotgov/core

Version:

DGS core.

1,147 lines (1,133 loc) 55.9 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common/http'), require('@angular/common'), require('@ngx-translate/core')) : typeof define === 'function' && define.amd ? define('@dotgov/core', ['exports', '@angular/core', '@angular/common/http', '@angular/common', '@ngx-translate/core'], factory) : (global = global || self, factory((global.dotgov = global.dotgov || {}, global.dotgov.core = {}), global.ng.core, global.ng.common.http, global.ng.common, global.ngxt)); }(this, (function (exports, i0, http, common, core) { 'use strict'; /*! ***************************************************************************** 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 */ var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } 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; return g = { next: verb(0), "throw": verb(1), "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 (_) 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 }; } } var __createBinding = Object.create ? (function (o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } }); }) : (function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } ; function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } ; var __setModuleDefault = Object.create ? (function (o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function (o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); } function __classPrivateFieldSet(receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; } var StorageService = /** @class */ (function () { function StorageService() { this._storage = {}; this._inProgress = {}; } StorageService.prototype.get = function (key) { return this._storage[key]; }; StorageService.prototype.set = function (key, value) { this._storage[key] = value; }; StorageService.prototype.remove = function (key, taskId) { var found = this._storage[key]; if (taskId && found && Array.isArray(found)) { var index = found.findIndex(function (f) { return f.taskId === taskId; }); if (index > -1) { found.splice(index, 1); if (found.length > 0) { this._storage[key] = found; return; } } else { return found; } } delete this._storage[key]; }; StorageService.prototype.removeMatched = function (match) { var _this = this; Object.keys(this._storage).forEach(function (key) { if (key.indexOf(match) !== -1) { _this.remove(key); } }); Object.keys(this._inProgress).forEach(function (key) { if (key.indexOf(match) !== -1) { _this.deleteProgress(key); } }); }; StorageService.prototype.clearCache = function () { this._inProgress = {}; this._storage = {}; }; StorageService.prototype.getProgress = function (key) { return this._inProgress[key]; }; StorageService.prototype.deleteProgress = function (key) { delete this._inProgress[key]; }; StorageService.prototype.setProgress = function (key) { this._inProgress[key] = new i0.EventEmitter(); }; return StorageService; }()); StorageService.decorators = [ { type: i0.Injectable } ]; StorageService.ctorParameters = function () { return []; }; var LoginMetadata = /** @class */ (function () { function LoginMetadata() { } return LoginMetadata; }()); LoginMetadata.samlRequestIdKey = 'EP_samlRequestID_key'; LoginMetadata.samlRelayStateKey = 'RelayState'; LoginMetadata.samlResponsePrefixKey = 'SAMLResponse_'; LoginMetadata.samlResponsePartsCountKey = 'SAMLResponsePartsCount'; LoginMetadata.externalSessionIndexKey = 'externalSessionIndex'; LoginMetadata.userContext = 'userContext'; LoginMetadata.activeRole = 'activeRole'; var Debugger = /** @class */ (function () { function Debugger() { } Debugger.prototype.init = function (environment) { var debugAll = environment.debug === true; this._environment = environment; this._buttonsDebug = debugAll || (environment.debug && environment.debug['buttons'] === true); this._missingFieldsDebug = debugAll || (environment.debug && environment.debug['missingFields'] === true); }; Debugger.prototype.log = function () { var messages = []; for (var _i = 0; _i < arguments.length; _i++) { messages[_i] = arguments[_i]; } this.action.apply(this, __spread(['log'], messages)); }; Debugger.prototype.warn = function () { var messages = []; for (var _i = 0; _i < arguments.length; _i++) { messages[_i] = arguments[_i]; } this.action.apply(this, __spread(['warn'], messages)); }; Debugger.prototype.error = function () { var messages = []; for (var _i = 0; _i < arguments.length; _i++) { messages[_i] = arguments[_i]; } this.action.apply(this, __spread(['error'], messages)); }; Debugger.prototype.info = function () { var messages = []; for (var _i = 0; _i < arguments.length; _i++) { messages[_i] = arguments[_i]; } this.action.apply(this, __spread(['info'], messages)); }; Debugger.prototype.debug = function () { var messages = []; for (var _i = 0; _i < arguments.length; _i++) { messages[_i] = arguments[_i]; } this.action.apply(this, __spread(['debug'], messages)); }; Debugger.prototype.action = function (method) { var messages = []; for (var _i = 1; _i < arguments.length; _i++) { messages[_i - 1] = arguments[_i]; } var shouldRuntimeDebug = window['dgs_debug'] === true; var debug = this._environment.debug; if (!debug || (typeof debug !== 'object' && typeof debug !== 'boolean')) { return; } var shouldDebug = debug === true || debug['logs'] === true || (debug['logs'] && debug['logs'][method] === true); if (shouldDebug || shouldRuntimeDebug) { console[method].apply(console, __spread(messages)); } }; return Debugger; }()); var Helper = /** @class */ (function () { function Helper() { } Helper.validValue = function (val) { var type = typeof val; if (val === undefined) { return false; } else if (type === 'string') { return val !== ''; } else if (type === 'number') { return Number.isFinite(val); } else { return true; } }; /** * @param _date * @param showTime Decide if we should show the time as well or not * @param forControl Decide if should return format dd/mm/yyyy * @returns YYYY-MM-DD HH:mm */ Helper.formatDate = function (_date, showTime, forControl) { if (showTime === void 0) { showTime = true; } if (forControl === void 0) { forControl = false; } if (!_date) { return; } var date = Helper.convertToDate(_date); var pad = function (n) { return (n <= 9 ? "0" + n : n); }; var time = " " + pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds()); if (forControl) { return (pad(date.getDate()) + "/" + pad(date.getMonth() + 1) + "/" + date.getFullYear() + (showTime ? time : '')).trim(); } // For .post send MM/dd/yyyy HH:mm:ss. return (pad(date.getMonth() + 1) + "/" + pad(date.getDate()) + "/" + date.getFullYear() + (showTime ? time : '')).trim(); }; Helper.stringToDate = function (strDate, dayFirst) { var _a, _b; if (dayFirst === void 0) { dayFirst = false; } // IE11 fix, if match: "2018-03-14 04:31:56.142" // Invalid date fix: 01/02/2018 => 01, 02, 2017; 2018-02-01 => 2018, 02, 01 var res = strDate.match(/\d+/gim).map(function (res) { return Number(res); }); var _c = __read(res, 6), MM = _c[0], dd = _c[1], YYYY = _c[2], HH = _c[3], mm = _c[4], ss = _c[5]; if (dayFirst) { _a = __read(res, 3), dd = _a[0], MM = _a[1], YYYY = _a[2]; } else if (MM > 12) { // First was year, transforming to correspond. _b = __read(res, 3), YYYY = _b[0], MM = _b[1], dd = _b[2]; } var sanitize = function (num) { return (num !== undefined ? num : 0); }; return new Date(sanitize(YYYY), sanitize(Number(MM) - 1), sanitize(dd), sanitize(HH), sanitize(mm), sanitize(ss)); }; Helper.convertToDate = function (d) { if (d === undefined || d === null) { return NaN; } var isDate = d.constructor === Date; var isArray = d.constructor === Array; var isNum = d.constructor === Number; var isString = d.constructor === String; var isObject = typeof d === 'object'; return ((isDate && d) || (isArray && new Date(d[0], d[1], d[2])) || (isNum && new Date(d)) || (isString && Helper.stringToDate(d)) || (isObject && new Date(d.year, d.month, d.date)) || NaN); }; Helper.camelize = function (str) { var capitalize = function (_str) { return _str.charAt(0).toUpperCase() + _str.toLowerCase().slice(1); }; var string = str .toLowerCase() .replace(/[^A-Za-z0-9]/g, ' ') .split(' ') .reduce(function (result, word) { return result + capitalize(word.toLowerCase()); }); return string.charAt(0).toLowerCase() + string.slice(1); }; Helper.isValidUrl = function (uri) { try { new URL(uri); } catch (_) { return false; } return true; }; return Helper; }()); var AppConfigService = /** @class */ (function () { function AppConfigService(environment) { this.environment = environment; } AppConfigService.prototype.load = function () { var _this = this; var jsonFile = this.environment.settingsUrl; return new Promise(function (resolve, reject) { fetch(jsonFile) .then(function (response) { return response.json(); }) .then(function (data) { AppConfigService.settings = data; if (!Helper.isValidUrl(AppConfigService.settings.apiUrl)) { _this.setEnvironmentAPIURI(); } ; resolve(); }) .catch(function (response) { reject("Could not load file '" + jsonFile + "': " + JSON.stringify(response)); }); }); }; AppConfigService.prototype.setEnvironmentAPIURI = function () { AppConfigService.settings['apiUrl'] = this.environment.apiUrl; }; return AppConfigService; }()); AppConfigService.settings = {}; AppConfigService.ɵprov = i0.ɵɵdefineInjectable({ factory: function AppConfigService_Factory() { return new AppConfigService(i0.ɵɵinject("environment")); }, token: AppConfigService, providedIn: "platform" }); AppConfigService.decorators = [ { type: i0.Injectable, args: [{ providedIn: 'platform', },] } ]; AppConfigService.ctorParameters = function () { return [ { type: undefined, decorators: [{ type: i0.Inject, args: ['environment',] }] } ]; }; var ApiResponse = /** @class */ (function () { function ApiResponse(data, error) { this.data = data; this.error = error; } return ApiResponse; }()); var ApiService = /** @class */ (function (_super) { __extends(ApiService, _super); function ApiService(httpClient, appConfig, customAuthenticator, environment) { var _this = _super.call(this) || this; _this.httpClient = httpClient; _this.appConfig = appConfig; _this.customAuthenticator = customAuthenticator; _this.environment = environment; _this.sanitizeMark = '___mk___'; return _this; } /** * Make GET request to api * @param point * @param args * @param parameters * @param options */ ApiService.prototype.get = function (point, args, parameters, options) { if (args === void 0) { args = []; } if (parameters === void 0) { parameters = {}; } if (options === void 0) { options = {}; } return this.request.apply(this, __spread(['GET', point, parameters, options, undefined], args)); }; /** * Make DELETE request to api * @param point * @param args * @param parameters * @param options */ ApiService.prototype.delete = function (point, args, parameters, options, body) { if (args === void 0) { args = []; } if (parameters === void 0) { parameters = {}; } if (options === void 0) { options = {}; } if (body === void 0) { body = {}; } return this.request.apply(this, __spread(['DELETE', point, parameters, options, body], args)); }; /** * Make OPTIONS request to api * @param point * @param args * @param parameters * @param options */ ApiService.prototype.options = function (point, args, parameters, options) { if (args === void 0) { args = []; } if (parameters === void 0) { parameters = {}; } if (options === void 0) { options = {}; } return this.request.apply(this, __spread(['OPTIONS', point, parameters, options, undefined], args)); }; /** * Make POST request to api * @param point * @param args * @param parameters * @param options */ ApiService.prototype.post = function (point, args, parameters, body, options) { if (args === void 0) { args = []; } if (parameters === void 0) { parameters = {}; } if (body === void 0) { body = {}; } if (options === void 0) { options = {}; } return this.request.apply(this, __spread(['POST', point, parameters, options, body], args)); }; /** * Make PATCH request to api * @param point * @param args * @param parameters * @param options */ ApiService.prototype.patch = function (point, args, parameters, body, options) { if (args === void 0) { args = []; } if (parameters === void 0) { parameters = {}; } if (body === void 0) { body = {}; } if (options === void 0) { options = {}; } return this.request.apply(this, __spread(['PATCH', point, parameters, options, body], args)); }; /** * Make PUT request to api * @param point * @param args * @param parameters * @param options */ ApiService.prototype.put = function (point, args, parameters, body, options) { if (args === void 0) { args = []; } if (parameters === void 0) { parameters = {}; } if (body === void 0) { body = {}; } if (options === void 0) { options = {}; } return this.request.apply(this, __spread(['PUT', point, parameters, options, body], args)); }; /** * Return generated url * @param point * @param args * @param parameters * @param body * @param options */ ApiService.prototype.getURL = function (point, args, parameters, body, options) { if (args === void 0) { args = []; } if (parameters === void 0) { parameters = {}; } if (body === void 0) { body = {}; } if (options === void 0) { options = {}; } return this.request.apply(this, __spread(['getURL', point, parameters, options, body], args)); }; Object.defineProperty(ApiService.prototype, "apiRenameList", { get: function () { return ['Name', 'Title']; }, enumerable: false, configurable: true }); Object.defineProperty(ApiService.prototype, "API", { get: function () { return AppConfigService.settings.apiUrl; }, enumerable: false, configurable: true }); ApiService.prototype.rename = function (origin, target) { this.languages.forEach(function (lang) { var from = origin + "_" + lang; var to = "" + origin; if (target) { return; } if (target.hasOwnProperty(from) && !target.hasOwnProperty(to)) { target[to] = target[from]; delete target[from]; } }); }; /** * Generates final url from api_url + view + query parameters; * @param url * @param parameters * @param args */ ApiService.prototype.generateUrl = function (url, parameters) { var _this = this; var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } var endUrl = "" + url + (args.length ? "/" + args.join('/') : ''); var queryParams = Object.keys(parameters) .map(function (key) { return key + "=" + _this.sanitize(parameters[key]); }) .join('&'); return "" + endUrl + (queryParams ? "?" + queryParams : ''); }; ApiService.prototype.sanitize = function (item) { var exists = item !== undefined && item !== null; var isNum = function (val) { return val.constructor === Number; }; var isString = function (val) { return val.constructor === String; }; if (!exists) { return item; } if (isString(item)) { return item.trim(); } if (isNum(item)) { return item; } if (item && Array.isArray(item)) { item = item.map(function (curr) { if (!curr) { return curr; } if (curr.hasOwnProperty('value')) { curr.value = !!curr.value ? curr.value.toString() : null; } return curr; }); } return JSON.stringify(item); }; /** * If data contains fields like Name_ru/Name_ro/Name_en transform it into Name. * @param data */ ApiService.prototype.resolve = function (response) { var _a; var _this = this; if (response && response.data && Array.isArray(response.data)) { response.data.forEach(function (item) { _this.apiRenameList.forEach(function (renameOrigin) { _this.rename(renameOrigin, item); }); }); } // Already been sanitized if (response && response.hasOwnProperty(this.sanitizeMark)) { return response; } return _a = { data: response, error: null }, _a[this.sanitizeMark] = true, _a; }; /** * Private Abstract request function * @param method * @param point * @param parameters * @param options * @param args */ ApiService.prototype.request = function (method, point, parameters, options, body) { var _this = this; if (body === void 0) { body = null; } var args = []; for (var _i = 5; _i < arguments.length; _i++) { args[_i - 5] = arguments[_i]; } if (!method) { console.warn('Something went wrong with API service.'); return; } var apiUrl = this.API; // If is already complete url i should not concat with api url. var fullUrl = new RegExp('^(?:[a-z]+:)?//', 'i'); if (fullUrl.test(point)) { apiUrl = ''; } method = method.toLowerCase(); var url = this.generateUrl.apply(this, __spread([(options['apiUrl'] || apiUrl) + point, parameters], args)); if (method === 'geturl') { return url; } var cacheUrl = url + "|" + method; return new Promise(function (resolve) { var _a; var cache = _super.prototype.get.call(_this, cacheUrl); var progress = _super.prototype.getProgress.call(_this, cacheUrl); var skipCache = options['skipCache'] || false; if (cache && skipCache !== true) { // Extract response from already finished request return resolve(cache); } else if (progress && skipCache !== true) { // Extract response from already existing request in progress progress.subscribe(function (response) { _super.prototype.deleteProgress.call(_this, cacheUrl); var resolvedData = _this.resolve(response); return resolve(resolvedData); }); } else { var cachingMethod_1 = method === 'get' || method === 'options'; var callParameters = []; // Add headers var defaultHeaders = { 'Pragma': 'no-cache', 'Cache-control': -1, 'ngsw-bypass': '' }; var headers = Object.assign(defaultHeaders, options['headers'] || {}); _this.authenticator(headers, options); options['headers'] = new http.HttpHeaders(_this.cleanHeaders(headers)); if (cachingMethod_1) { callParameters = [url, options]; // Request not in cache/progress so we set it. _super.prototype.setProgress.call(_this, cacheUrl); } else if (method === 'delete') { callParameters = [url, options, body || {}]; } else { callParameters = [url, body || {}, options]; } (_a = _this.httpClient)[method].apply(_a, __spread(callParameters)).toPromise() .then(function (rawData) { var resolvedData = _this.resolve(rawData); if (cachingMethod_1) { _super.prototype.set.call(_this, cacheUrl, resolvedData); } var getProgress = _super.prototype.getProgress.call(_this, cacheUrl); if (getProgress) { getProgress.emit(resolvedData); _super.prototype.deleteProgress.call(_this, cacheUrl); } return resolve(resolvedData); }) .catch(function (error) { var res = { data: null, error: error }; var getProgress = _super.prototype.getProgress.call(_this, cacheUrl); if (getProgress) { getProgress.emit(res); _super.prototype.deleteProgress.call(_this, cacheUrl); } return resolve(res); }); } }); }; ApiService.prototype.authenticator = function (headers, options) { if (!this.customAuthenticator) { return this.defaultAuthenticator(headers, options); } return this.customAuthenticator(headers, options); }; ApiService.prototype.defaultAuthenticator = function (headers, options) { var auth = JSON.parse(localStorage.getItem('auth')); var externalSessionIndex = JSON.parse(localStorage.getItem(LoginMetadata.externalSessionIndexKey)); if (auth && !headers.hasOwnProperty('Authorization')) { headers['Authorization'] = auth.tokenType + " " + auth.token; } if (externalSessionIndex && !headers.hasOwnProperty(LoginMetadata.externalSessionIndexKey)) { headers["x-" + LoginMetadata.externalSessionIndexKey] = "" + externalSessionIndex; } var contextFromStorage = localStorage.getItem(LoginMetadata.userContext); var userContext = localStorage.getItem(LoginMetadata.activeRole) || (contextFromStorage && contextFromStorage !== 'undefined' && contextFromStorage !== 'null' ? JSON.parse(contextFromStorage) : {}).role; if (!options['skipRole'] && userContext) { headers['x-Current-Role'] = "" + userContext; } }; ApiService.prototype.cleanHeaders = function (headers) { var cleaned = {}; Object.keys(headers).forEach(function (key) { var value = headers[key]; if (value !== null && value !== undefined) { cleaned[key] = value; } }); return cleaned; }; Object.defineProperty(ApiService.prototype, "languages", { get: function () { return ['en', 'ro', 'ru']; }, enumerable: false, configurable: true }); return ApiService; }(StorageService)); ApiService.decorators = [ { type: i0.Injectable } ]; ApiService.ctorParameters = function () { return [ { type: http.HttpClient }, { type: AppConfigService }, { type: undefined, decorators: [{ type: i0.Inject, args: ['authenticator',] }] }, { type: undefined, decorators: [{ type: i0.Inject, args: ['environment',] }] } ]; }; var FactoryService = /** @class */ (function () { function FactoryService(resolver, environment) { if (environment === void 0) { environment = {}; } this.resolver = resolver; this.environment = environment; this.debug = Boolean(this.environment.debug); } /** * How to use: * // html * <div #container></div> * // class * @ViewChild('container', { read: ViewContainerRef }) container; * // ngAfterViewInit * const factory = this.factoryService.componentByName('ComponentName'); * this.container.createComponent(factory); * this.ref.detectChanges(); * * @param componentName */ FactoryService.prototype.componentByName = function (componentName, target, inputs) { var factories = Array.from(this.resolver['_factories'].keys()); var factoryClass = factories.find(function (x) { return x.name === componentName; }); if (!factoryClass) { if (this.debug) { console.warn("Could not load " + componentName); } return; } return this.createComponent(factoryClass, inputs, target); }; /** * How to use: * // html * <div #container></div> * // class * @ViewChild('container', { read: ViewContainerRef }) container; * // ngAfterViewInit * const factory = this.factoryService.componentbySelector('component-selector'); * this.container.createComponent(factory); * this.ref.detectChanges(); * * @param componentName */ FactoryService.prototype.componentbySelector = function (componentSelector, componentFactories, target, inputs) { var _this = this; if (inputs === void 0) { inputs = {}; } if (!componentSelector) { if (this.debug) { console.warn('Started client-control with no target component.'); } return FactoryService.NOT_FOUND; } var res; componentFactories.forEach(function (value) { if (value && value.selector === componentSelector) { res = _this.createComponent(value.factoryClass, inputs, target); return; } }); if (!res) { if (this.debug) { console.warn("Could not load " + componentSelector); } return FactoryService.NOT_FOUND; } if (!res.create) { return FactoryService.HAS_ROUTE; } return res; }; FactoryService.prototype.createComponent = function (factoryClass, inputs, target) { if (!target || !target.insert) { if (this.debug) { console.warn("Could not get target for ", factoryClass, '|', target); } return FactoryService.NOT_FOUND; } if (!factoryClass) { if (this.debug) { console.warn("Could not load factory class"); } return FactoryService.NOT_FOUND; } var inputProviders = Object.keys(inputs).map(function (inputName) { return { provide: inputName, useValue: inputs[inputName] }; }); var resolvedInputs = i0.ReflectiveInjector.resolve(inputProviders); // We create an injector out of the data we want to pass down and this components injector var injector = i0.ReflectiveInjector.fromResolvedProviders(resolvedInputs, target.parentInjector); // We create a factory out of the component we want to create var factory = this.resolver.resolveComponentFactory(factoryClass); // We create the component using the factory and the injector var component = factory.create(injector); // We insert the component into the dom container target.insert(component.hostView); Object.keys(inputs).forEach(function (input) { component.instance[input] = inputs[input]; }); return component; }; return FactoryService; }()); FactoryService.HAS_ROUTE = null; FactoryService.NOT_FOUND = undefined; FactoryService.decorators = [ { type: i0.Injectable } ]; FactoryService.ctorParameters = function () { return [ { type: i0.ComponentFactoryResolver }, { type: undefined, decorators: [{ type: i0.Inject, args: ['environment',] }] } ]; }; var DGSNotificationService = /** @class */ (function () { function DGSNotificationService() { this.notifyEvent = new i0.EventEmitter(); } DGSNotificationService.prototype.error = function (message, title) { this.emit({ type: 'error', message: message, title: title }); }; DGSNotificationService.prototype.info = function (message, title) { this.emit({ type: 'info', message: message, title: title }); }; DGSNotificationService.prototype.success = function (message, title) { this.emit({ type: 'success', message: message, title: title }); }; DGSNotificationService.prototype.warning = function (message, title) { this.emit({ type: 'warning', message: message, title: title }); }; DGSNotificationService.prototype.subscription = function (cb) { return this.notifyEvent.subscribe(cb); }; DGSNotificationService.prototype.emit = function (data) { this.notifyEvent.emit(data); }; return DGSNotificationService; }()); DGSNotificationService.decorators = [ { type: i0.Injectable } ]; var DGSLowerTranslatePipe = /** @class */ (function () { function DGSLowerTranslatePipe(translate, _ref) { this.translate = translate; this._ref = _ref; this.translatePipe = new core.TranslatePipe(this.translate, this._ref); } DGSLowerTranslatePipe.prototype.transform = function (value) { var _a; if (value === void 0) { value = ''; } var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var isString = typeof value === 'string'; var newValue = value; if (isString) { newValue = value.toLowerCase() || ' '; } var translation = (_a = this.translatePipe).transform.apply(_a, __spread([newValue], args)); if (translation === newValue && isString) { return value; } return translation; }; return DGSLowerTranslatePipe; }()); DGSLowerTranslatePipe.decorators = [ { type: i0.Pipe, args: [{ name: 'ltranslate', pure: false },] } ]; DGSLowerTranslatePipe.ctorParameters = function () { return [ { type: core.TranslateService }, { type: i0.ChangeDetectorRef } ]; }; function init_app(appConfig) { var config = function () { return appConfig.load(); }; return config; } var DGSCoreModule = /** @class */ (function () { function DGSCoreModule() { } DGSCoreModule.forRoot = function (environment, authenticator) { return { ngModule: DGSCoreModule, providers: [ AppConfigService, { provide: i0.APP_INITIALIZER, useFactory: init_app, deps: [AppConfigService], multi: true }, ApiService, StorageService, FactoryService, DGSNotificationService, { provide: 'environment', useValue: environment }, { provide: 'authenticator', useValue: authenticator }, ], }; }; return DGSCoreModule; }()); DGSCoreModule.decorators = [ { type: i0.NgModule, args: [{ declarations: [ DGSLowerTranslatePipe, ], imports: [ common.CommonModule, http.HttpClientModule, ], exports: [ DGSLowerTranslatePipe, ], providers: [],