UNPKG

@versatiledatakit/shared

Version:

Versatile Data Kit Shared library enables reusability of shared features like: NgRx Redux, Error Handlers, Utils, Generic Components, etc.

1,729 lines (1,671 loc) 615 kB
import { isEqual, cloneDeep, get } from 'lodash'; import { v4 } from 'uuid'; import * as i0 from '@angular/core'; import { Directive, Injectable, NgModule, Optional, SkipSelf, ViewContainerRef, Component, ViewChild, Input, NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA, Pipe, EventEmitter, ElementRef, HostBinding, Output, ChangeDetectionStrategy, Host, HostListener, TemplateRef, ContentChild, InjectionToken, Inject } from '@angular/core'; import { Subscription, of, iif, throwError, timer, BehaviorSubject, combineLatest, Subject } from 'rxjs'; import { HttpErrorResponse } from '@angular/common/http'; import { map, tap, catchError, switchMap, mergeMap, take, withLatestFrom, filter, debounceTime } from 'rxjs/operators'; import * as i1 from '@ngrx/effects'; import { createEffect, ofType, EffectsModule } from '@ngrx/effects'; import * as i2 from '@angular/router'; import { ActivatedRoute, RouterModule, UrlSegment, ActivatedRouteSnapshot } from '@angular/router'; import * as i2$1 from '@angular/common'; import { CommonModule } from '@angular/common'; import * as i4 from '@ngrx/router-store'; import { ROUTER_NAVIGATION, ROUTER_CANCEL, ROUTER_ERROR, StoreRouterConnectingModule } from '@ngrx/router-store'; import * as i1$1 from '@ngrx/store'; import { StoreModule } from '@ngrx/store'; import { __decorate } from 'tslib'; import 'reflect-metadata'; import * as i3$2 from 'ngx-cookie-service'; import { CookieService } from 'ngx-cookie-service'; import * as i3 from '@ngrx/store-devtools'; import { StoreDevtoolsModule } from '@ngrx/store-devtools'; import * as i2$2 from '@clr/angular'; import { ClarityModule, ClrLoadingState, ClrTooltipModule, ClrDropdownModule, ClrLoadingModule, ClrLoadingButtonModule } from '@clr/angular'; import * as i3$1 from '@angular/forms'; import { FormsModule, FormControl, ReactiveFormsModule } from '@angular/forms'; import { trigger, state, style, transition, animate, group, query, animateChild, keyframes, stagger } from '@angular/animations'; import { ClarityIcons, angleIcon, arrowIcon, checkCircleIcon, checkIcon, copyToClipboardIcon, exclamationCircleIcon, searchIcon, timesCircleIcon, timesIcon } from '@cds/core/icon'; import * as i2$3 from 'ngx-clipboard'; import { ClipboardModule } from 'ngx-clipboard'; /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /** * ** Utility Class for Collections. */ class CollectionsUtil { /** * ** Check if value is of type undefined. */ static isUndefined(value) { return typeof value === 'undefined'; } /** * ** Check if value has value null. */ static isNull(value) { return value === null; } /** * ** Check if value is undefined or null. */ static isNil(value) { return CollectionsUtil.isNull(value) || CollectionsUtil.isUndefined(value); } /** * ** Check if value is defined (opposite of isNil). * * - Not null. * - Not undefined. */ static isDefined(value) { return !CollectionsUtil.isNull(value) && !CollectionsUtil.isUndefined(value); } /** * ** Check if value T is of type Number. */ static isNumber(num) { return typeof num === 'number'; } /** * ** Check if value T is of type String. */ static isString(str) { return typeof str === 'string'; } /** * ** Check if value T is of type Boolean. */ static isBoolean(bool) { return typeof bool === 'boolean'; } /** * ** Check if value is Primitive. * * - String, Number, Boolean, null or undefined. */ static isPrimitive(value) { return (CollectionsUtil.isString(value) || CollectionsUtil.isBoolean(value) || CollectionsUtil.isNumber(value) || CollectionsUtil.isUndefined(value)); } /** * ** Check if value is NaN. */ static isNaN(value) { return Number.isNaN(value); } /** * ** Check if value is of type Date. */ static isDate(value) { return value instanceof Date; } /** * ** Check if value is Primitive or Date. * * - String, Number, Boolean, null, undefined or Date. */ static isPrimitiveOrDate(value) { return CollectionsUtil.isPrimitive(value) || CollectionsUtil.isDate(value); } /** * ** Check if value T is a reference that points to function (Class/Method). */ // eslint-disable-next-line static isFunction(value) { return typeof value === 'function'; } /** * ** Check if value T is of type Object. */ static isObject(obj) { return typeof obj === 'object'; } /** * ** Check if value T is instance of Array. */ static isArray(arr) { return arr instanceof Array; } /** * ** Check if value T is not instance of Array or there are no elements in Array. */ static isArrayEmpty(arr) { return !CollectionsUtil.isArray(arr) || arr.length === 0; } /** * ** Returns new Array where items will be filtered by reference and will leave distinct values. */ static uniqueArray(arr) { return arr.filter((value, index, self) => { return self.indexOf(value) === index; }); } /** * ** Check if value is Map. */ static isMap(obj) { return obj instanceof Map; } /** * ** Check if value is WeakMap. */ static isWeakMap(obj) { return obj instanceof WeakMap; } /** * ** Check if value is Set. */ static isSet(obj) { return obj instanceof Set; } /** * ** Check if value T is of type String and has length bigger than 0 after whitespace trim. */ static isStringWithContent(str) { return CollectionsUtil.isString(str) && str.trim().length > 0; } /** * ** Check if value is Collection (literal Object, Array, Map, WeakMap or Set). */ static isCollection(obj) { return (CollectionsUtil.isArray(obj) || CollectionsUtil.isMap(obj) || CollectionsUtil.isWeakMap(obj) || CollectionsUtil.isSet(obj) || CollectionsUtil.isLiteralObject(obj)); } /** * ** Check if value is of type Object and not null. */ static isObjectNotNull(obj) { return CollectionsUtil.isObject(obj) && !CollectionsUtil.isNull(obj); } /** * ** Check if some variable is of type Boolean and is true. */ static isBooleanAndTrue(bool) { return CollectionsUtil.isBoolean(bool) && bool; } /** * ** Check if value is literal Object or null. * * - Not an Array, Map, WeakMap or Set. */ static isLiteralObjectOrNull(obj) { return (CollectionsUtil.isObject(obj) && !CollectionsUtil.isArray(obj) && !CollectionsUtil.isMap(obj) && !CollectionsUtil.isWeakMap(obj) && !CollectionsUtil.isSet(obj)); } /** * ** Check if provided value is literal Object. * * - Not and Array, Map, WeakMap, Set or null. */ static isLiteralObject(obj) { return CollectionsUtil.isLiteralObjectOrNull(obj) && !CollectionsUtil.isNull(obj); } /** * ** Check if value is Object and has properties. */ static isObjectWithProperties(obj) { return CollectionsUtil.isObjectNotNull(obj) && Object.keys(obj).length > 0; } /** * ** Return current Date in ISO string format. */ static dateISO() { return new Date().toISOString(); } /** * ** Return current Date milliseconds from 1970. */ static dateNow() { return Date.now(); } /** * ** Performs deep comparison between two values to determine if the are equivalent. */ static isEqual(value1, value2) { return isEqual(value1, value2); } /** * ** Create recursive deep cloned value from provided one. */ static cloneDeep(value) { return cloneDeep(value); } /** * ** Generate UUID that meats RFC4122 compliance. */ static generateUUID() { // eslint-disable-next-line @typescript-eslint/no-unsafe-call return v4(); } /** * ** Generate Object UUID that meats RFC4122 compliance and also has Class name identifier inside. * * <br/> * <i>pattern</i>: * <p> * <Class Name><strong>_</strong><UUID RFC4122> * </p> */ static generateObjectUUID(className) { return `${className}_${CollectionsUtil.generateUUID()}`; } /** * ** Creates random string. */ static generateRandomString() { return (Math.random() + 1).toString(36).substring(2); } /** * ** Iterates own enumerable properties in Object. * * - use Object.keys method for extraction, and executes provided iteratorFn. * - if iteratorFn returns false or -1 it will break iteration. * - all other return values continue until last property. * * - flag as third parameter is optional: * - Without flag or with flag and has value 'plainObject, method will iterate only through literal Objects. * - With flag and has value 'objectLookLike', method will try to iterate through everything * that passes type value === 'object' (literal Object, Array, Map, Set, WeakMap, etc..). */ static iterateObject(obj, iteratorFn, flag = 'plainObject') { if (!CollectionsUtil.isFunction(iteratorFn)) { return null; } if (flag === 'objectLookLike') { if (!CollectionsUtil.isObjectNotNull(obj)) { return null; } } else { if (!CollectionsUtil.isLiteralObject(obj)) { return null; } } const objectKeys = Object.keys(obj); for (const key of objectKeys) { const resultOfIteratorFn = iteratorFn(obj[key], key, obj); if (resultOfIteratorFn === false || resultOfIteratorFn === -1) { break; } } return obj; } /** * ** Check if value is Literal Object and has properties. */ static isLiteralObjectWithProperties(obj) { return CollectionsUtil.isLiteralObject(obj) && Object.keys(obj).length > 0; } /** * ** Iterates over object properties and return Array of its values. */ static objectValues(obj) { const _result = []; CollectionsUtil.iterateObject(obj, (value) => { _result.push(value); }); return _result; } /** * ** Transform given Map to Object. */ static transformMapToObject(map) { const obj = {}; map.forEach((value, key) => (obj[key] = value)); return obj; } /** * ** Transform given Object to Map. */ static transformObjectToMap(obj) { const map = new Map(); CollectionsUtil.iterateObject(obj, (value, key) => { map.set(key, value); }); return map; } /** * ** Iterates over object properties and return Array of its keys/values in pairs. * <p> * - Returns Array of subArrays that have 2 elements each, first element key and second element value. */ static objectPairs(obj) { if (!CollectionsUtil.isLiteralObject(obj)) { return []; } return Object.entries(obj); } /** * ** Return own property Descriptor from provided object/function. */ static getObjectPropertyDescriptor(obj, key) { if (!((CollectionsUtil.isFunction(obj) || CollectionsUtil.isObject(obj)) && CollectionsUtil.isString(key))) { return null; } return Object.getOwnPropertyDescriptor(obj, key); } /** * ** Iterates own enumerable properties (statics) of Function (Class). * * - use Object.getOwnPropertyDescriptors method for extraction, and executes provided iteratorFn. * - if iteratorFn returns false or -1 will break iteration. * - all other return values means continue until last property. */ static iterateClassStatics(fn, iteratorFn) { if (!CollectionsUtil.isFunction(fn) || !CollectionsUtil.isFunction(iteratorFn)) { return null; } const descriptors = Object.getOwnPropertyDescriptors(fn); CollectionsUtil.iterateObject(descriptors, (descriptor, key) => iteratorFn(descriptor, key, fn)); return fn; } /** * ** Check if two Maps are Equal. * * - They are equal if they have same references. * - They are equal if they have same keys and same values for compared keys. */ static areMapsEqual(m1, m2) { const evaluateDeepComparison = () => { for (const [key, val] of m1) { const compareVal = m2.get(key); if (CollectionsUtil.isMap(val)) { if (!CollectionsUtil.areMapsEqual(val, compareVal)) { return false; } continue; } if (!CollectionsUtil.isEqual(val, compareVal) || (CollectionsUtil.isUndefined(compareVal) && !m2.has(key))) { return false; } } return true; }; return CollectionsUtil.isMap(m1) && CollectionsUtil.isMap(m2) && (m1 === m2 || (m1.size === m2.size && evaluateDeepComparison())); } /** * @inheritDoc */ static interpolateString(target, ...replacers) { let response = target; replacers.forEach((replacer) => { if (CollectionsUtil.isString(replacer)) { response = response.replace('%s', replacer); } else { response = response.replace(replacer.searchValue, replacer.replaceValue); } }); return response; } } /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ const FORWARD_SLASH = '/'; const TIE_SWAGGER_DOC_LOCATION = 'swagger-ui.html#'; class UrlUtil { static normalizeEndpoint(endPoint) { if (!endPoint) { return ''; } if (endPoint.endsWith(FORWARD_SLASH)) { return endPoint; } return endPoint + FORWARD_SLASH; } static constructTieSwaggerUiEndpoint(endpointBasePath) { return UrlUtil.normalizeEndpoint(endpointBasePath) + TIE_SWAGGER_DOC_LOCATION; } } /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /** * ** Primitive Criteria that check equals by reference or if primitive by value, using === */ class PrimitiveCriteria { /** * ** Constructor. */ constructor(property, assertionValue) { this._property = property; this._assertionValue = assertionValue; } /** * @inheritDoc */ meetCriteria(elements) { return [...(elements !== null && elements !== void 0 ? elements : [])].filter((element) => { const value = get(element, this._property); return value === this._assertionValue; }); } } /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /** * ** And criteria that filters elements in Array and remove those that does not meet all criterias. */ class AndCriteria { /** * ** Constructor. */ constructor(...criterias) { this.criterias = criterias; } /** * @inheritDoc */ meetCriteria(elements) { let elementsMeetCriteria = [...elements]; for (const criteria of this.criterias) { elementsMeetCriteria = criteria.meetCriteria(elementsMeetCriteria); if (elementsMeetCriteria.length === 0) { break; } } return elementsMeetCriteria; } } /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /** * ** Or criteria that filters elements in Array and remove those that does not meet at least one criterias. */ class OrCriteria { /** * ** Constructor. */ constructor(...criterias) { this.criterias = criterias; } /** * @inheritDoc */ meetCriteria(elements) { return this.criterias.reduce((elementsMeetCriteria, criteria) => { const singleCriteriaMetElements = criteria.meetCriteria(elements); for (const element of singleCriteriaMetElements) { if (!elementsMeetCriteria.includes(element)) { elementsMeetCriteria.push(element); } } return elementsMeetCriteria; }, []); } } /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /** * ** Generates Error code (token). * * - Code (token) starts with * - Class name, * - then followed by underscore and class PUBLIC_NAME, * - then followed by underscore and method name or underscore with some error specifics, * - then followed by underscore and additional details to avoid overlaps with other Class errors. * <b>(for http requests it should be HTTP Status Code)</b> * * <br/> * <i>returned value pattern</i>: * <p> * <Class Name><b>_</b><Class PUBLIC_NAME><b>_</b><Class method name><b>_</b><additional details, like HTTP Status Code> * </p> */ const generateErrorCode = (className, classPublicName, methodName, additionalDetails) => { let errorCode = ''; if (CollectionsUtil.isString(className)) { errorCode += `${className}`; } else { errorCode += CollectionsUtil.generateRandomString(); } if (CollectionsUtil.isString(classPublicName)) { errorCode += `_${classPublicName}`; } if (CollectionsUtil.isString(methodName)) { errorCode += `_${methodName}`; } if (CollectionsUtil.isString(additionalDetails)) { errorCode += `_${additionalDetails}`; } else { errorCode += '_'; } return errorCode; }; /** * ** Generates supported error codes for provided className, publicName and methodName. */ /* eslint-disable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ const generateSupportedHttpErrorCodes = (className, publicName, method) => { const errorCodes = {}; errorCodes.All = generateErrorCode(className, publicName, method, null); errorCodes.ClientErrors = generateErrorCode(className, publicName, method, '4\\d\\d'); errorCodes.BadRequest = generateErrorCode(className, publicName, method, `${400 /* BadRequest */}`); errorCodes.Unauthorized = generateErrorCode(className, publicName, method, `${401 /* Unauthorized */}`); errorCodes.Forbidden = generateErrorCode(className, publicName, method, `${403 /* Forbidden */}`); errorCodes.NotFound = generateErrorCode(className, publicName, method, `${404 /* NotFound */}`); errorCodes.MethodNotAllowed = generateErrorCode(className, publicName, method, `${405 /* MethodNotAllowed */}`); errorCodes.Conflict = generateErrorCode(className, publicName, method, `${409 /* Conflict */}`); errorCodes.UnprocessableEntity = generateErrorCode(className, publicName, method, `${422 /* UnprocessableEntity */}`); errorCodes.ServerErrors = generateErrorCode(className, publicName, method, '5\\d\\d'); errorCodes.InternalServerError = generateErrorCode(className, publicName, method, `${500 /* InternalServerError */}`); errorCodes.ServiceUnavailable = generateErrorCode(className, publicName, method, `${503 /* ServiceUnavailable */}`); errorCodes.Unknown = generateErrorCode(className, publicName, method, 'unknown'); return errorCodes; }; /* eslint-enable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /** * ** Request Page DTO. */ class RequestPageImpl { constructor(page, size) { this.page = page !== null && page !== void 0 ? page : 1; this.size = size !== null && size !== void 0 ? size : 25; } /** * ** Factory method. */ static of(page, size) { return new RequestPageImpl(page, size); } /** * ** Factory method for empty RequestPageDTO. */ static empty() { return new RequestPageImpl(null, null); } /** * ** Creates DTO from literal. */ static fromLiteral(literalDTO) { return RequestPageImpl.of(literalDTO.pageNumber, literalDTO.pageSize); } /** * @inheritDoc */ toLiteral() { var _a, _b; return { pageNumber: (_a = this.page) !== null && _a !== void 0 ? _a : 1, pageSize: (_b = this.size) !== null && _b !== void 0 ? _b : 25 }; } /** * @inheritDoc */ toLiteralCloneDeep() { return this.toLiteral(); } } /** * ** Request Order DTO. */ class RequestOrderImpl { constructor(...criteria) { // eslint-disable-next-line @typescript-eslint/unbound-method this.criteria = [...criteria.filter(CollectionsUtil.isDefined)]; } /** * ** Factory method. */ static of(...criteria) { return new RequestOrderImpl(...criteria); } /** * ** Factory method for empty RequestOrderDTO. */ static empty() { return new RequestOrderImpl(); } /** * ** Creates DTO from literal. */ static fromLiteral(literalCriteria) { return RequestOrderImpl.of(...literalCriteria); } /** * @inheritDoc */ toLiteral() { return [...this.criteria]; } /** * @inheritDoc */ toLiteralCloneDeep() { return this.criteria.map((c) => (Object.assign({}, c))); } } /** * ** Request Filter DTO. */ class RequestFilterImpl { constructor(...criteria) { // eslint-disable-next-line @typescript-eslint/unbound-method this.criteria = [...criteria.filter(CollectionsUtil.isDefined)]; } /** * ** Factory method. */ static of(...criteria) { return new RequestFilterImpl(...criteria); } /** * ** Factory method for empty RequestFilterDTO. */ static empty() { return new RequestFilterImpl(); } /** * ** Creates DTO from literal. */ static fromLiteral(literalCriteria) { return RequestFilterImpl.of(...literalCriteria); } /** * @inheritDoc */ toLiteral() { return [...this.criteria]; } /** * @inheritDoc */ toLiteralCloneDeep() { return this.criteria.map((c) => (Object.assign({}, c))); } } const ASC = 'ASC'; const DESC = 'DESC'; /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /** * ** Base Class for all Angular related Objects. * * - Cleans all rxjs subscriptions on object destroy. */ // eslint-disable-next-line @angular-eslint/directive-class-suffix class TaurusObject { /** * ** Constructor. */ constructor(className = null) { this.objectUUID = CollectionsUtil.generateObjectUUID(className !== null && className !== void 0 ? className : TaurusObject.CLASS_NAME); this.subscriptions = []; } /** * ** Methods that will dispose Object. * - Clean all Subscriptions. */ dispose() { this.cleanSubscriptions(); } /** * @inheritDoc */ ngOnDestroy() { this.dispose(); } /** * ** Clean all Subscriptions. */ cleanSubscriptions() { // unsubscribe all valid subscriptions this.subscriptions // eslint-disable-next-line @typescript-eslint/unbound-method .filter(CollectionsUtil.isDefined) // eslint-disable-next-line @typescript-eslint/unbound-method .forEach(TaurusObject._unsubscribeFromStream); } /** * ** Remove subscription reference from subscriptions queue providing reference itself. * * - Before remove it would be auto-unsubscribed from stream. * @protected */ removeSubscriptionRef(subscriptionRef) { const subscriptionIndex = this.subscriptions.findIndex((s) => s === subscriptionRef); if (subscriptionIndex === -1) { if (subscriptionRef instanceof Subscription) { TaurusObject._unsubscribeFromStream(subscriptionRef); return true; } return false; } const removedSubscription = this.subscriptions.splice(subscriptionIndex, 1); return TaurusObject._unsubscribeFromStream(removedSubscription[0]); } /** * ** Unsubscribe subscription from stream. * @private */ static _unsubscribeFromStream(s) { try { s.unsubscribe(); return true; } catch (e) { console.error(`Taurus Object failed to unsubscribe from rxjs stream!`, e); return false; } } } /** * ** Class name, identifier for Object class. * * - Format should be PascalCase. */ TaurusObject.CLASS_NAME = 'TaurusObject'; /** * ** Class PUBLIC_NAME, human-readable. * * - Format should be Kebab-Case. */ TaurusObject.PUBLIC_NAME = 'Taurus-Base-Object'; TaurusObject.ɵfac = function TaurusObject_Factory(t) { i0.ɵɵinvalidFactory(); }; TaurusObject.ɵdir = /*@__PURE__*/ i0.ɵɵdefineDirective({ type: TaurusObject }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(TaurusObject, [{ type: Directive }], function () { return [{ type: undefined }]; }, null); })(); /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /** * ** Comparable. */ class ComparableImpl { /** * ** Constructor. */ constructor(value) { this.value = value; } /** * ** Factory method. */ static of(value) { return new ComparableImpl(value); } /** * @inheritDoc */ compare(comparable) { if (comparable instanceof ComparableImpl) { const evaluateSecondStatement = () => (this.value > comparable.value ? 1 : -1); return this.value === comparable.value ? 0 : evaluateSecondStatement(); } else { return -1; } } /** * @inheritDoc */ isNil() { return CollectionsUtil.isNil(this.value); } /** * @inheritDoc */ notNil() { return CollectionsUtil.isDefined(this.value); } /** * @inheritDoc */ like(comparable) { return this.compare(comparable) === 0; } /** * @inheritDoc */ equal(comparable) { return this.compare(comparable) === 0; } /** * @inheritDoc */ notEqual(comparable) { return this.compare(comparable) !== 0; } /** * @inheritDoc */ lessThan(comparable) { return this.compare(comparable) < 0; } /** * @inheritDoc */ lessThanInclusive(comparable) { return this.compare(comparable) <= 0; } /** * @inheritDoc */ greaterThan(comparable) { return this.compare(comparable) > 0; } /** * @inheritDoc */ greaterThanInclusive(comparable) { return this.compare(comparable) >= 0; } } /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ class PredicatesComparable { /** * ** Constructor. */ constructor(...predicates) { this.value = predicates !== null && predicates !== void 0 ? predicates : []; } /** * ** Factory method. */ static of(...predicates) { return new PredicatesComparable(...predicates); } /** * @inheritDoc */ compare(_comparable) { console.warn('PredicatesComparable, unsupported comparison.'); return -1; } /** * @inheritDoc */ isNil() { return CollectionsUtil.isNil(this.value); } /** * @inheritDoc */ notNil() { return CollectionsUtil.isDefined(this.value); } /** * @inheritDoc */ like(comparable) { return this.value.some((predicate) => predicate.evaluate(comparable)); } /** * @inheritDoc */ equal(comparable) { return this.value.every((predicate) => predicate.evaluate(comparable)); } /** * @inheritDoc */ notEqual(comparable) { return !this.value.every((predicate) => predicate.evaluate(comparable)); } /** * @inheritDoc */ lessThan(_comparable) { return PredicatesComparable._defaultUnsupported(); } /** * @inheritDoc */ lessThanInclusive(_comparable) { return PredicatesComparable._defaultUnsupported(); } /** * @inheritDoc */ greaterThan(_comparable) { return PredicatesComparable._defaultUnsupported(); } /** * @inheritDoc */ greaterThanInclusive(_comparable) { return PredicatesComparable._defaultUnsupported(); } // eslint-disable-next-line @typescript-eslint/member-ordering static _defaultUnsupported() { console.warn('PredicatesComparable, unsupported comparison.'); return false; } } /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ class CompoundPredicate { constructor(...values) { if (values.length === 1) { if (values[0] instanceof PredicatesComparable) { this.comparable = values[0]; } else { this.comparable = PredicatesComparable.of(values[0]); } } else { this.comparable = PredicatesComparable.of(...values); } } /** * ** Factory method. */ static of(..._args) { throw new Error('Method have to be overridden in Subclasses.'); } } /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ class And extends CompoundPredicate { static of(...values) { if (values[0] instanceof PredicatesComparable) { return new And(values[0]); } else { return new And(...values); } } /** * @inheritDoc */ evaluate(comparable) { return this.comparable.equal(comparable); } } /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ class Or extends CompoundPredicate { static of(...values) { if (values[0] instanceof PredicatesComparable) { return new Or(values[0]); } else { return new Or(...values); } } /** * @inheritDoc */ evaluate(comparable) { return this.comparable.like(comparable); } } /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ class SimplePredicate { /** * ** Constructor. */ constructor(comparable) { this.comparable = comparable; } /** * ** Factory method. */ static of(..._args) { throw new Error('Method have to be overridden in Subclasses.'); } } /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /** * ** Equal Predicate that accepts Comparable and make equality evaluation. * * */ class Equal extends SimplePredicate { /** * ** Constructor. */ constructor(comparable) { super(comparable); } /** * ** Factory method. */ static of(comparable) { return new Equal(comparable); } /** * @inheritDoc */ evaluate(comparable) { return this.comparable.equal(comparable); } } /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /** * ** Base Class for Angular Service related classes. * * - Add abstraction for TaurusBaseApiService subclasses to auto-register their methods' error codes in relationship one method to many error codes for auto-supported scenarios. * - There could be added additional error codes from subclasses. */ class TaurusBaseApiService extends TaurusObject { /** * ** Constructor. */ constructor(className = null) { super(className !== null && className !== void 0 ? className : TaurusBaseApiService.CLASS_NAME); /** * ** Class error codes Mapping. * * - There are auto-generated error codes for every method name in runtime, where method name is the key, and the multiple values where each value is bound to unique error code. * - Subclasses could override in definition time or in runtime to add additional error codes. */ this.errorCodes = {}; } /** * ** Register error codes for service. * * - Exclude system methods. * - Exclude private methods which names start with underscore (e.g. _methodName(): void;) * @protected */ registerErrorCodes(service) { /* eslint-disable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */ try { Object.getOwnPropertyNames(service.prototype) .filter((method) => method !== 'constructor' && method !== 'dispose' && method !== 'ngOnDestroy' && method !== 'cleanSubscriptions' && method !== 'removeSubscriptionRef' && method !== 'registerErrorCodes' && !/^_/.test(method) && CollectionsUtil.isFunction(service.prototype[method])) .forEach((method) => { this.errorCodes[method] = generateSupportedHttpErrorCodes(service.CLASS_NAME, service.PUBLIC_NAME, method); }); } catch (e) { console.error(`Cannot register Service Error Codes!`); } /* eslint-enable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */ } } /** * @inheritDoc */ TaurusBaseApiService.CLASS_NAME = 'TaurusBaseApiService'; /** * @inheritDoc */ TaurusBaseApiService.PUBLIC_NAME = 'Taurus-Api-Service'; TaurusBaseApiService.ɵfac = function TaurusBaseApiService_Factory(t) { i0.ɵɵinvalidFactory(); }; TaurusBaseApiService.ɵdir = /*@__PURE__*/ i0.ɵɵdefineDirective({ type: TaurusBaseApiService, features: [i0.ɵɵInheritDefinitionFeature] }); (function () { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(TaurusBaseApiService, [{ type: Directive }], function () { return [{ type: undefined }]; }, null); })(); /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ const TASK_IDENTIFIER_SEPARATOR = ' __ '; const TASK_IDENTIFIER_TEMPLATE = `%s${TASK_IDENTIFIER_SEPARATOR}%s`; /** * ** Factory for Tasks identifiers. */ const createTaskIdentifier = (task) => { if (CollectionsUtil.isString(task)) { return CollectionsUtil.interpolateString(TASK_IDENTIFIER_TEMPLATE, task, CollectionsUtil.dateISO()); } return undefined; }; /** * ** Extract Task from Tasks identifiers. */ const extractTaskFromIdentifier = (taskIdentifier) => { if (CollectionsUtil.isString(taskIdentifier)) { return taskIdentifier.split(TASK_IDENTIFIER_SEPARATOR)[0]; } return null; }; /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /** * ** Process service HTTP request error and return ErrorRecord. * * @param {string} objectUUID - is objectUUID of the Object for which processing error is invoked * @param {Record<keyof ServiceHttpErrorCodes, string>} serviceHttpErrorCodes - is map of Service method supported error codes auto-handling * @param {unknown} error - is actual error object reference */ const processServiceRequestError = (objectUUID, serviceHttpErrorCodes, error) => { const _objectUUID = CollectionsUtil.isDefined(objectUUID) ? objectUUID : CollectionsUtil.generateObjectUUID('UnknownClassName'); if (!CollectionsUtil.isLiteralObject(serviceHttpErrorCodes)) { return { code: generateErrorCode('UnknownClassName', 'UnknownPublicName', 'UnknownMethodName', 'Generic'), objectUUID: _objectUUID, error: error instanceof Error ? error : null }; } if (error instanceof HttpErrorResponse) { let code; switch (error.status) { case 400 /* BadRequest */: code = serviceHttpErrorCodes.BadRequest; break; case 401 /* Unauthorized */: code = serviceHttpErrorCodes.Unauthorized; break; case 403 /* Forbidden */: code = serviceHttpErrorCodes.Forbidden; break; case 404 /* NotFound */: code = serviceHttpErrorCodes.NotFound; break; case 405 /* MethodNotAllowed */: code = serviceHttpErrorCodes.MethodNotAllowed; break; case 409 /* Conflict */: code = serviceHttpErrorCodes.Conflict; break; case 422 /* UnprocessableEntity */: code = serviceHttpErrorCodes.UnprocessableEntity; break; case 500 /* InternalServerError */: code = serviceHttpErrorCodes.InternalServerError; break; case 503 /* ServiceUnavailable */: code = serviceHttpErrorCodes.ServiceUnavailable; break; default: code = serviceHttpErrorCodes.Unknown; } return { code, objectUUID: _objectUUID, error, httpStatusCode: error.status }; } return { code: serviceHttpErrorCodes.Unknown, objectUUID: _objectUUID, error: error instanceof Error ? error : null }; }; /** * ** Get API formatted error message from provided Error. */ const getApiFormattedErrorMessage = (error) => { let statusCode = null; if (error instanceof HttpErrorResponse) { if (CollectionsUtil.isString(error.error)) { return { what: `${error.error}`, why: `${error.message}` }; } if (CollectionsUtil.isLiteralObject(error.error)) { return { what: `${error.error.what}`, why: `${error.error.why}`, consequences: `${error.error.consequences}`, countermeasures: `${error.error.countermeasures}` }; } statusCode = error.status; } return { what: 'Please contact Superollider and report the issue', why: getHumanReadableStatusText(statusCode) }; }; /** * ** Get Human readable text from HTTP error status code. */ const getHumanReadableStatusText = (httpErrorStatus) => { switch (httpErrorStatus) { case 400 /* BadRequest */: return 'Invalid param'; case 401 /* Unauthorized */: return 'Unauthorized'; case 403 /* Forbidden */: return 'Forbidden'; case 404 /* NotFound */: return 'Not Found'; case 405 /* MethodNotAllowed */: return 'Not Allowed'; case 409 /* Conflict */: return 'Conflict'; case 422 /* UnprocessableEntity */: return 'Invalid operation'; case 500 /* InternalServerError */: return 'Internal Server Error'; case 503 /* ServiceUnavailable */: return 'Service Unavailable'; default: return 'Unknown Error'; } }; /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /* * Copyright 2023-2025 Broadcom * SPDX-License-Identifier: Apache-2.0 */ /** * @inheritDoc * * ** ErrorStore implementation. */ class ErrorStoreImpl { /** * ** Constructor. */ constructor(errorRecords = []) { this.records = errorRecords !== null && errorRecords !== void 0 ? errorRecords : []; this.changeListeners = []; } /** * ** Factory method. */ static of(errorRecords) { return new ErrorStoreImpl(errorRecords); } /** * ** Factory method that returns empty store. */ static empty() { return ErrorStoreImpl.of(null); } /** * ** Creates ErrorStore from literal. */ static fromLiteral(errorRecords) { return ErrorStoreImpl.of(ErrorStoreImpl.cloneDeepErrorRecords(errorRecords)); } /** * ** Clone deep provided ErrorRecords. */ static cloneDeepErrorRecords(errorRecords) { return (errorRecords !== null && errorRecords !== void 0 ? errorRecords : []).map((r) => (Object.assign({}, r))); } /** * @inheritDoc */ hasErrors() { return this.records.length > 0; } /** * @inheritDoc */ hasCode(...errorCodes) { return errorCodes.some((code) => this.records.findIndex((r) => r.code === code) !== -1); } /** * @inheritDoc */ hasCodePattern(...errorCodesPatterns) { try { return errorCodesPatterns.some((errorPattern) => { if (!CollectionsUtil.isString(errorPattern)) { return false; } const errorPatternRegex = new RegExp(errorPattern); return this.records.findIndex((r) => errorPatternRegex.test(r.code)) !== -1; }); } catch (e) { console.error(e); return false; } } record(param, objectUUID, error, httpStatusCode) { const errorRecordsShallowCopy = [...this.records]; if (CollectionsUtil.isString(param) && CollectionsUtil.isString(objectUUID)) { const foundIndex = errorRecordsShallowCopy.findIndex((r) => r.code === param && r.objectUUID === objectUUID); const errorRecord = { code: param, objectUUID, time: CollectionsUtil.dateNow(), error: error !== null && error !== void 0 ? error : null, httpStatusCode: httpStatusCode !== null && httpStatusCode !== void 0 ? httpStatusCode : null }; if (foundIndex === -1) { errorRecordsShallowCopy.push(errorRecord); } else { errorRecordsShallowCopy.splice(foundIndex, 1, errorRecord); } } else if (CollectionsUtil.isLiteralObject(param) && CollectionsUtil.isNil(objectUUID)) { const foundIndex = errorRecordsShallowCopy.findIndex((r) => r.code === param.code && r.objectUUID === param.objectUUID); const errorRecord = Object.assign(Object.assign({}, param), { time: CollectionsUtil.dateNow() }); if (foundIndex === -1) { errorRecordsShallowCopy.push(errorRecord); } else { errorRecordsShallowCopy.splice(foundIndex, 1, errorRecord); } } this.records = errorRecordsShallowCopy; ErrorStoreImpl._executeChangeListeners(this, this.changeListeners); } /** * @inheritDoc */ removeCode(...errorCodes) { let errorRecordsShallowCopy = [...this.records]; try { errorRecordsShallowCopy = errorRecordsShallowCopy.filter((r) => !errorCodes.includes(r.code)); } catch (e) { console.error(e); } this.records = errorRecordsShallowCopy; ErrorStoreImpl._executeChangeListeners(this, this.changeListeners); } /** * @inheritDoc */ removeCodePattern(...errorCodePatterns) { let errorCodesShallowCopy = [...this.records]; for (const errorPattern of errorCodePatterns) { try { if (!CollectionsUtil.isString(errorPattern)) { continue; } const errorPatternRegex = new RegExp(errorPattern); errorCodesShallowCopy = errorCodesShallowCopy.filter((r) => !errorPatternRegex.test(r.code)); } catch (e) { console.error(e); } } this.records = errorCodesShallowCopy; ErrorStoreImpl._executeChangeListeners(this, this.changeListeners); } /** * @inheritDoc */ findRecords(...errorCodes) { return this.records.filter((r) => errorCodes.includes(r.code)); } /** * @inheritDoc */ findRecordsByPattern(...errorCodePatterns) { let foundRecords = []; for (const errorPattern of errorCodePatterns) { try { if (!CollectionsUtil.isString(errorPattern)) { continue; } const errorPatternRegex = new RegExp(errorPattern); const filteredRecords = this.records.filter((r) => errorPatternRegex.test(r.code)); foundRecords = foundRecords.concat(...filteredRecords); } catch (e) { console.error(e); } } return foundRecords; } /** * @inheritDoc */ distinctErrorRecords(errorRecords) { const _errorRecords = CollectionsUtil.isArray(errorRecords) ? errorRecords : []; return this.records.filter((r) => _errorRecords.findIndex((rInjected) => ErrorStoreImpl._checkErrorRecordsEquality(r, rInjected)) === -1); } /** * @inheritDoc */ purge(injectedStore) { if (!(injectedStore instanceof ErrorStoreImpl)) { return; } if (this.equals(injectedStore)) { return; } this.records = [...injectedStore.records]; ErrorStoreImpl._executeChangeListeners(this, this.changeListeners); } /** * @inheritDoc */ onChange(callback) { if (CollectionsUtil.isFunction(callback)) { this.changeListeners.push(callback); } } /** * @inheritDoc */ dispose() { this.clear(); this.changeListeners = []; } /** * @inheritDoc */ clear() { try { this.records.length = 0; this.records = []; } catch (e) { console.error(e); } } /** * @inheritDoc */ toLiteral() { return [...this.records]; } /**