Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@shapediver/viewer.shared.services

Package Overview
Dependencies
Maintainers
5
Versions
216
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@shapediver/viewer.shared.services - npm Package Compare versions

Comparing version 2.10.1-rc.0 to 2.11.0

22

dist/converter/Converter.d.ts

@@ -8,5 +8,5 @@ import { vec3 } from 'gl-matrix';

processSVG(blob: Blob): Promise<HTMLImageElement>;
responseToImage(response: HttpResponse<ArrayBuffer>): Promise<HTMLImageElement>;
toAlpha(color: any): number;
toColorArray(color: any): number[];
responseToImage(response: HttpResponse<ArrayBuffer | HTMLImageElement>): Promise<HTMLImageElement>;
toAlpha(color: unknown): number;
toColorArray(color: unknown): number[];
/**

@@ -16,3 +16,3 @@ * @param color

*/
toHex8Color(color: any, defColorString?: string): string;
toHex8Color(color: unknown, defColorString?: string): string;
/**

@@ -25,7 +25,15 @@ * This color converter is mostly left 'as-is' from viewer v2.

*/
toHexColor(color: any, defColorString?: string): string;
toThreeJsColorInput(color: any): string;
toVec3(point: any): vec3;
toHexColor(color: unknown, defColorString?: string): string;
toThreeJsColorInput(color: unknown): string;
toVec3(point: vec3 | {
x: number;
y: number;
z: number;
} | {
X: number;
Y: number;
Z: number;
}): vec3;
private tinyColorToString;
}
//# sourceMappingURL=Converter.d.ts.map

@@ -0,1 +1,2 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -10,9 +11,11 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
import { vec3 } from 'gl-matrix';
import { TinyColor } from '@ctrl/tinycolor';
import { HttpClient } from '../http-client/HttpClient';
export class Converter {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Converter = void 0;
const gl_matrix_1 = require("gl-matrix");
const tinycolor_1 = require("@ctrl/tinycolor");
const HttpClient_1 = require("../http-client/HttpClient");
class Converter {
constructor() {
// #region Properties (2)
this._httpClient = HttpClient.instance;
this._httpClient = HttpClient_1.HttpClient.instance;
// #endregion Private Methods (1)

@@ -37,8 +40,8 @@ }

data = atob(data);
let svgC = document.createElement('DIV');
const svgC = document.createElement('DIV');
svgC.id = 'svgc';
svgC.innerHTML = data;
// now we can access the svg element as a DOM object
let svgE = svgC.getElementsByTagName('svg');
let childImageURIs = [];
const svgE = svgC.getElementsByTagName('svg');
const childImageURIs = [];
let styleURIs = [];

@@ -48,3 +51,3 @@ // collect image urls

for (let j = 0; j < 2; ++j) {
let childImages = svgE[i].getElementsByTagName(['image', 'img'][j]);
const childImages = svgE[i].getElementsByTagName(['image', 'img'][j]);
for (let k = 0; k < childImages.length; ++k) {

@@ -59,5 +62,5 @@ if (childImages[k].href.baseVal.substring(0, 5) != 'data:') {

// @import url(CSS_URL);
let styleElements = svgE[i].getElementsByTagName('style');
const styleElements = svgE[i].getElementsByTagName('style');
for (let j = 0; j < styleElements.length; ++j) {
let regex = /@import\x20url\(\s*(.*?)\s*\);/g;
const regex = /@import\x20url\(\s*(.*?)\s*\);/g;
let m;

@@ -74,12 +77,13 @@ while ((m = regex.exec(styleElements[j].innerHTML)) !== null) {

// creating a promise for each image which needs to be converted to a data URI
let replacementPromises = [];
let createImagePromise = (uri) => __awaiter(this, void 0, void 0, function* () {
const replacementPromises = [];
const createImagePromise = (uri) => __awaiter(this, void 0, void 0, function* () {
if (uri.length > 0) {
const response = yield this._httpClient.loadTexture(uri);
let uInt8Array = new Uint8Array(response.data), i = uInt8Array.length;
let biStr = []; //new Array(i);
const response = yield this._httpClient.get(uri, undefined, true);
const uInt8Array = new Uint8Array(response.data);
let i = uInt8Array.length;
const biStr = []; //new Array(i);
while (i--)
biStr[i] = String.fromCharCode(uInt8Array[i]);
let base64Data = window.btoa(biStr.join(''));
let imgDataUrl = 'data:' + response.headers['content-type'] + ';base64,' + base64Data;
const base64Data = window.btoa(biStr.join(''));
const imgDataUrl = 'data:' + response.headers['content-type'] + ';base64,' + base64Data;
// replace url in SVG string

@@ -93,3 +97,3 @@ // CAUTION theoretically this could cause unwanted replacements

// now we create promises for the google fonts to be imported
let createStylePromise = (styleUrl) => __awaiter(this, void 0, void 0, function* () {
const createStylePromise = (styleUrl) => __awaiter(this, void 0, void 0, function* () {
const response = yield this._httpClient.get(styleUrl, { responseType: 'text' });

@@ -99,4 +103,4 @@ let cssString = response.data;

// url(FONT_URI);
let fontURLs = [];
let regex = /url\(\s*(.*?)\s*\)/g;
const fontURLs = [];
const regex = /url\(\s*(.*?)\s*\)/g;
let m;

@@ -106,11 +110,12 @@ while ((m = regex.exec(cssString)) !== null) {

}
let fontPromises = [];
let createFontPromise = (fUrl) => __awaiter(this, void 0, void 0, function* () {
const fontPromises = [];
const createFontPromise = (fUrl) => __awaiter(this, void 0, void 0, function* () {
const response = yield this._httpClient.get(fUrl, { responseType: 'arraybuffer' });
let uInt8Array = new Uint8Array(response.data), i = uInt8Array.length;
let biStr = []; //new Array(i);
const uInt8Array = new Uint8Array(response.data);
let i = uInt8Array.length;
const biStr = []; //new Array(i);
while (i--)
biStr[i] = String.fromCharCode(uInt8Array[i]);
let base64Data = window.btoa(biStr.join(''));
let fontDataUrl = 'data:' + response.headers['content-type'] + ';base64,' + base64Data;
const base64Data = window.btoa(biStr.join(''));
const fontDataUrl = 'data:' + response.headers['content-type'] + ';base64,' + base64Data;
if (fUrl.length > 0)

@@ -127,4 +132,4 @@ cssString = cssString.replace(fUrl, fontDataUrl);

yield Promise.all(replacementPromises);
let du = 'data:image/svg+xml,' + encodeURIComponent(data);
let img = new Image(); // same as document.createElement('img')
const du = 'data:image/svg+xml,' + encodeURIComponent(data);
const img = new Image(); // same as document.createElement('img')
img.crossOrigin = 'Anonymous';

@@ -142,2 +147,5 @@ const promise = new Promise((resolve, reject) => {

return __awaiter(this, void 0, void 0, function* () {
// if we already receive and image, this conversion already happened
if (response.data instanceof HTMLImageElement)
return response.data;
const arrayBufferView = new Uint8Array(response.data);

@@ -155,3 +163,3 @@ const blob = new Blob([arrayBufferView], { type: response.headers['content-type'] });

});
img.crossOrigin = "anonymous";
img.crossOrigin = 'anonymous';
img.src = URL.createObjectURL(blob);

@@ -171,5 +179,5 @@ yield promise;

toColorArray(color) {
if (typeof color !== 'string' || !color.startsWith("#"))
if (typeof color !== 'string' || !color.startsWith('#'))
color = this.toHexColor(color);
const tColor = new TinyColor(color);
const tColor = new tinycolor_1.TinyColor(color);
const rgb = tColor.toRgb();

@@ -184,3 +192,3 @@ return [rgb.r / 255.0, rgb.g / 255.0, rgb.b / 255.0];

const c = this.toHexColor(color, defColorString);
const tColor = new TinyColor(c);
const tColor = new tinycolor_1.TinyColor(c);
const cH8 = tColor.toHex8String();

@@ -201,4 +209,4 @@ return cH8.replace('#', '0x');

color = Array.from(color);
const tColor = new TinyColor(color);
if (color instanceof TinyColor)
const tColor = new tinycolor_1.TinyColor(color);
if (color instanceof tinycolor_1.TinyColor)
return this.tinyColorToString(tColor);

@@ -208,3 +216,3 @@ // check if we got a number

let cs = color.toString(16);
let cl = cs.length;
const cl = cs.length;
if (cl < 3)

@@ -216,3 +224,3 @@ cs = cs.padStart(3, '0');

cs = cs.padEnd(8, '0');
let tc = new TinyColor(cs);
const tc = new tinycolor_1.TinyColor(cs);
return tc.isValid ? this.tinyColorToString(tc) : defColorString;

@@ -222,3 +230,3 @@ }

if (color.isColor && typeof color.getHexString == 'function') {
let tc = new TinyColor(color.getHexString());
const tc = new tinycolor_1.TinyColor(color.getHexString());
return tc.isValid ? this.tinyColorToString(tc) : defColorString;

@@ -237,3 +245,3 @@ }

return defColorString;
let tc = new TinyColor({
const tc = new tinycolor_1.TinyColor({
r: Math.max(0, Math.min(color[0], 255)),

@@ -244,3 +252,3 @@ g: Math.max(0, Math.min(color[1], 255)),

if (color.length == 4) {
let a = parseFloat(color[3]);
const a = parseFloat(color[3]);
if (!isNaN(a)) {

@@ -255,10 +263,10 @@ tc.setAlpha(Math.max(0, Math.min(a, 255)) / 255);

if (typeof color !== 'string') {
let tc = new TinyColor(color);
const tc = new tinycolor_1.TinyColor(color);
return tc.isValid ? this.tinyColorToString(tc) : defColorString;
}
// tinycolor doesn't like 0x
let tmpColor = color.replace('0x', '#');
const tmpColor = color.replace('0x', '#');
// if we got no alpha value, add full opacity
if (tmpColor.match(/^#[a-f0-9]{6}$/i) !== null) {
let tc = new TinyColor(tmpColor + 'ff');
const tc = new tinycolor_1.TinyColor(tmpColor + 'ff');
return tc.isValid ? this.tinyColorToString(tc) : defColorString;

@@ -268,3 +276,3 @@ }

if (tmpColor.match(/^#[a-f0-9]{8}$/i) !== null) {
let tc = new TinyColor(tmpColor);
const tc = new tinycolor_1.TinyColor(tmpColor);
return tc.isValid ? this.tinyColorToString(tc) : defColorString;

@@ -274,7 +282,7 @@ }

if (tmpColor.match(/^#[a-f0-9]{7}$/i) !== null) {
let tc = new TinyColor(tmpColor.slice(0, 7) + '0' + tmpColor.slice(-1));
const tc = new tinycolor_1.TinyColor(tmpColor.slice(0, 7) + '0' + tmpColor.slice(-1));
return tc.isValid ? this.tinyColorToString(tc) : defColorString;
}
// check if tinycolor understands the string
let tc = new TinyColor(tmpColor);
const tc = new tinycolor_1.TinyColor(tmpColor);
return tc.isValid ? this.tinyColorToString(tc) : defColorString;

@@ -288,8 +296,10 @@ }

if (Array.isArray(point) && point.length >= 3 && typeof point[0] === 'number' && typeof point[1] === 'number' && typeof point[2] === 'number')
return vec3.fromValues(point[0], point[1], point[2]);
if (((point.x || point.x === 0) && typeof point.x === 'number') && ((point.y || point.y === 0) && typeof point.y === 'number') && ((point.z || point.z === 0) && typeof point.z === 'number'))
return vec3.fromValues(point.x, point.y, point.z);
if (((point.X || point.X === 0) && typeof point.X === 'number') && ((point.Y || point.Y === 0) && typeof point.Y === 'number') && ((point.Z || point.Z === 0) && typeof point.Z === 'number'))
return vec3.fromValues(point.X, point.Y, point.Z);
return vec3.create();
return gl_matrix_1.vec3.fromValues(point[0], point[1], point[2]);
const pointCast1 = point;
if (((pointCast1.x || pointCast1.x === 0) && typeof pointCast1.x === 'number') && ((pointCast1.y || pointCast1.y === 0) && typeof pointCast1.y === 'number') && ((pointCast1.z || pointCast1.z === 0) && typeof pointCast1.z === 'number'))
return gl_matrix_1.vec3.fromValues(pointCast1.x, pointCast1.y, pointCast1.z);
const pointCast2 = point;
if (((pointCast2.X || pointCast2.X === 0) && typeof pointCast2.X === 'number') && ((pointCast2.Y || pointCast2.Y === 0) && typeof pointCast2.Y === 'number') && ((pointCast2.Z || pointCast2.Z === 0) && typeof pointCast2.Z === 'number'))
return gl_matrix_1.vec3.fromValues(pointCast2.X, pointCast2.Y, pointCast2.Z);
return gl_matrix_1.vec3.create();
}

@@ -302,2 +312,3 @@ // #endregion Public Methods (8)

}
exports.Converter = Converter;
//# sourceMappingURL=Converter.js.map

@@ -1,4 +0,7 @@

import { SystemInfo } from '../system-info/SystemInfo';
import { UuidGenerator } from '../uuid-generator/UuidGenerator';
export class DomEventEngine {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DomEventEngine = void 0;
const SystemInfo_1 = require("../system-info/SystemInfo");
const UuidGenerator_1 = require("../uuid-generator/UuidGenerator");
class DomEventEngine {
// #endregion Properties (5)

@@ -9,4 +12,4 @@ // #region Constructors (1)

this._domEventListeners = {};
this._uuidGenerator = UuidGenerator.instance;
this._systemInfo = SystemInfo.instance;
this._uuidGenerator = UuidGenerator_1.UuidGenerator.instance;
this._systemInfo = SystemInfo_1.SystemInfo.instance;
this._allowListeners = {

@@ -292,2 +295,3 @@ mousewheel: true,

}
exports.DomEventEngine = DomEventEngine;
//# sourceMappingURL=DomEventEngine.js.map

@@ -1,2 +0,3 @@

export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IDomEventListener.js.map

@@ -1,13 +0,16 @@

import { EVENTTYPE } from './EventTypes';
import { UuidGenerator } from '../uuid-generator/UuidGenerator';
import { Logger } from '../logger/Logger';
export class EventEngine {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventEngine = void 0;
const EventTypes_1 = require("./EventTypes");
const UuidGenerator_1 = require("../uuid-generator/UuidGenerator");
const Logger_1 = require("../logger/Logger");
class EventEngine {
// #endregion Properties (4)
// #region Constructors (1)
constructor() {
this._logger = Logger.instance;
this._uuidGenerator = UuidGenerator.instance;
this._logger = Logger_1.Logger.instance;
this._uuidGenerator = UuidGenerator_1.UuidGenerator.instance;
this._eventListeners = {};
for (const type in EVENTTYPE) {
const subEventType = EVENTTYPE[type];
for (const type in EventTypes_1.EVENTTYPE) {
const subEventType = EventTypes_1.EVENTTYPE[type];
this._eventListeners[type.toLowerCase()] = [];

@@ -66,4 +69,4 @@ for (const subtype in subEventType) {

removeListener(token) {
for (const type in EVENTTYPE) {
const subEventType = EVENTTYPE[type];
for (const type in EventTypes_1.EVENTTYPE) {
const subEventType = EventTypes_1.EVENTTYPE[type];
const typeLowerCase = type.toLowerCase();

@@ -93,4 +96,4 @@ for (let i = 0; i < this._eventListeners[typeLowerCase].length; i++) {

typeString = type;
for (const mainType in EVENTTYPE)
if (type === EVENTTYPE[mainType])
for (const mainType in EventTypes_1.EVENTTYPE)
if (type === EventTypes_1.EVENTTYPE[mainType])
typeString = mainType.toLowerCase();

@@ -104,2 +107,3 @@ if (!typeString || !this._eventListeners[typeString]) {

}
exports.EventEngine = EventEngine;
//# sourceMappingURL=EventEngine.js.map

@@ -1,2 +0,5 @@

export var EVENTTYPE_CAMERA;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EVENTTYPE = exports.EVENTTYPE_INTERACTION = exports.EVENTTYPE_TASK = exports.EVENTTYPE_SESSION = exports.EVENTTYPE_VIEWPORT = exports.EVENTTYPE_SCENE = exports.EVENTTYPE_RENDERING = exports.EVENTTYPE_CAMERA = void 0;
var EVENTTYPE_CAMERA;
(function (EVENTTYPE_CAMERA) {

@@ -6,11 +9,11 @@ EVENTTYPE_CAMERA["CAMERA_START"] = "camera.start";

EVENTTYPE_CAMERA["CAMERA_END"] = "camera.end";
})(EVENTTYPE_CAMERA || (EVENTTYPE_CAMERA = {}));
export var EVENTTYPE_RENDERING;
})(EVENTTYPE_CAMERA = exports.EVENTTYPE_CAMERA || (exports.EVENTTYPE_CAMERA = {}));
var EVENTTYPE_RENDERING;
(function (EVENTTYPE_RENDERING) {
EVENTTYPE_RENDERING["BEAUTY_RENDERING_FINISHED"] = "rendering.beautyRenderingFinished";
})(EVENTTYPE_RENDERING || (EVENTTYPE_RENDERING = {}));
export var EVENTTYPE_SCENE;
})(EVENTTYPE_RENDERING = exports.EVENTTYPE_RENDERING || (exports.EVENTTYPE_RENDERING = {}));
var EVENTTYPE_SCENE;
(function (EVENTTYPE_SCENE) {
EVENTTYPE_SCENE["SCENE_BOUNDING_BOX_CHANGE"] = "scene.boundingBoxChange";
})(EVENTTYPE_SCENE || (EVENTTYPE_SCENE = {}));
})(EVENTTYPE_SCENE = exports.EVENTTYPE_SCENE || (exports.EVENTTYPE_SCENE = {}));
// VIEWPORT

@@ -24,3 +27,3 @@ // FRAMERATE

// VISIBILITY_OFF
export var EVENTTYPE_VIEWPORT;
var EVENTTYPE_VIEWPORT;
(function (EVENTTYPE_VIEWPORT) {

@@ -35,4 +38,4 @@ EVENTTYPE_VIEWPORT["BUSY_MODE_ON"] = "viewport.busy.on";

EVENTTYPE_VIEWPORT["VIEWPORT_HIDDEN"] = "viewport.hidden";
})(EVENTTYPE_VIEWPORT || (EVENTTYPE_VIEWPORT = {}));
export var EVENTTYPE_SESSION;
})(EVENTTYPE_VIEWPORT = exports.EVENTTYPE_VIEWPORT || (exports.EVENTTYPE_VIEWPORT = {}));
var EVENTTYPE_SESSION;
(function (EVENTTYPE_SESSION) {

@@ -43,4 +46,4 @@ EVENTTYPE_SESSION["SESSION_CREATED"] = "session.created";

EVENTTYPE_SESSION["SESSION_INITIAL_OUTPUTS_LOADED"] = "session.initialOutputsLoaded";
})(EVENTTYPE_SESSION || (EVENTTYPE_SESSION = {}));
export var EVENTTYPE_TASK;
})(EVENTTYPE_SESSION = exports.EVENTTYPE_SESSION || (exports.EVENTTYPE_SESSION = {}));
var EVENTTYPE_TASK;
(function (EVENTTYPE_TASK) {

@@ -51,4 +54,4 @@ EVENTTYPE_TASK["TASK_START"] = "task.start";

EVENTTYPE_TASK["TASK_CANCEL"] = "task.cancel";
})(EVENTTYPE_TASK || (EVENTTYPE_TASK = {}));
export var EVENTTYPE_INTERACTION;
})(EVENTTYPE_TASK = exports.EVENTTYPE_TASK || (exports.EVENTTYPE_TASK = {}));
var EVENTTYPE_INTERACTION;
(function (EVENTTYPE_INTERACTION) {

@@ -62,4 +65,4 @@ EVENTTYPE_INTERACTION["DRAG_START"] = "interaction.drag.start";

EVENTTYPE_INTERACTION["SELECT_OFF"] = "interaction.select.off";
})(EVENTTYPE_INTERACTION || (EVENTTYPE_INTERACTION = {}));
export const EVENTTYPE = {
})(EVENTTYPE_INTERACTION = exports.EVENTTYPE_INTERACTION || (exports.EVENTTYPE_INTERACTION = {}));
exports.EVENTTYPE = {
CAMERA: EVENTTYPE_CAMERA,

@@ -66,0 +69,0 @@ RENDERING: EVENTTYPE_RENDERING,

@@ -1,2 +0,3 @@

export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=ICallback.js.map

@@ -0,3 +1,4 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
;
export {};
//# sourceMappingURL=IEvent.js.map

@@ -1,2 +0,3 @@

export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IListener.js.map

@@ -6,5 +6,21 @@ import { AxiosRequestConfig } from 'axios';

private static _instance;
private _dataCache;
private _enableCaching;
private _excludedQueryParameters;
private _maxCacheSize;
private _sessionLoading;
private constructor();
static get instance(): HttpClient;
get enableCaching(): boolean;
set enableCaching(value: boolean);
get excludedQueryParameters(): string[];
set excludedQueryParameters(value: string[]);
get maxCacheSize(): number;
set maxCacheSize(value: number);
/**
* Add the data loading options from a session.
*
* @param sessionId
* @param callbacks
*/
addDataLoading(sessionId: string, callbacks: {

@@ -24,7 +40,64 @@ getAsset: (url: string) => Promise<[ArrayBuffer, string, string]>;

convertError(e: ShapeDiverBackendError | Error | unknown): void;
get(href: string, config?: AxiosRequestConfig, textureLoading?: boolean): Promise<HttpResponse<any>>;
loadTexture(href: string): Promise<HttpResponse<ArrayBuffer>>;
/**
* Get the requested resource either as a download or from the cache.
* If available, the registered session loading is used for download.
* Textures are downloaded via a specific endpoint and can be converted in this step as well.
* Depending on the provided caching options, the requested resource might already be cached.
*
* @param href
* @param config
* @param textureLoading
* @param textureConversion
* @returns
*/
get(href: string, config?: AxiosRequestConfig, textureLoading?: boolean, textureConversion?: boolean): Promise<HttpResponse<unknown>>;
/**
* Get the requested texture either as a download or from the cache.
*
* @param href
* @returns
*/
loadTexture(href: string): Promise<HttpResponse<HTMLImageElement>>;
/**
* Add the data loading options from a session.
*
* @param sessionId
*/
removeDataLoading(sessionId: string): void;
/**
* Add
*
* @param key
* @param value
*/
private addToCache;
/**
* Calculate the current cache size from all resolved promises.
*
* @returns
*/
private calculateCacheSize;
/**
* Get the value of an object from the cache.
*
* @param key
* @returns
*/
private getFromCache;
/**
* Get the session id of the provided href.
*
* @param href
* @returns
*/
private getSessionId;
/**
* Convert the provided href to a data cache key.
* In this conversion the excludedQueryParameters are removed from the href.
*
* @param href
* @returns
*/
private hrefToDataKey;
}
//# sourceMappingURL=HttpClient.d.ts.map

@@ -0,1 +1,2 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -10,9 +11,20 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
import axios from 'axios';
import { isGBResponseError, isGBRequestError, isGBError } from '@shapediver/sdk.geometry-api-sdk-v2';
import { ShapeDiverGeometryBackendError, ShapeDiverGeometryBackendRequestError, ShapeDiverGeometryBackendResponseError } from '../logger/ShapeDiverBackendErrors';
export class HttpClient {
// #endregion Properties (2)
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpClient = void 0;
const axios_1 = __importDefault(require("axios"));
const sdk_geometry_api_sdk_v2_1 = require("@shapediver/sdk.geometry-api-sdk-v2");
const ShapeDiverBackendErrors_1 = require("../logger/ShapeDiverBackendErrors");
const Converter_1 = require("../converter/Converter");
class HttpClient {
// #endregion Properties (7)
// #region Constructors (1)
// eslint-disable-next-line @typescript-eslint/no-empty-function
constructor() {
this._dataCache = new Map();
this._enableCaching = true;
this._excludedQueryParameters = ['Expires', 'Signature', 'Key-Pair-Id'];
this._maxCacheSize = 1024 * 1024 * 32;
this._sessionLoading = {};

@@ -26,3 +38,31 @@ }

// #endregion Public Static Accessors (1)
// #region Public Accessors (6)
get enableCaching() {
return this._enableCaching;
}
set enableCaching(value) {
this._enableCaching = value;
if (this._enableCaching === false)
this._dataCache.clear();
}
get excludedQueryParameters() {
return this._excludedQueryParameters;
}
set excludedQueryParameters(value) {
this._excludedQueryParameters = value;
}
get maxCacheSize() {
return this._maxCacheSize;
}
set maxCacheSize(value) {
this._maxCacheSize = value;
}
// #endregion Public Accessors (6)
// #region Public Methods (5)
/**
* Add the data loading options from a session.
*
* @param sessionId
* @param callbacks
*/
addDataLoading(sessionId, callbacks) {

@@ -41,14 +81,30 @@ this._sessionLoading[sessionId] = callbacks;

convertError(e) {
if (isGBResponseError(e)) {
throw new ShapeDiverGeometryBackendResponseError(e.message, e.status, e.error, e.desc);
if ((0, sdk_geometry_api_sdk_v2_1.isGBResponseError)(e)) {
throw new ShapeDiverBackendErrors_1.ShapeDiverGeometryBackendResponseError(e.message, e.status, e.error, e.desc);
}
else if (isGBRequestError(e)) {
throw new ShapeDiverGeometryBackendRequestError(e.message, e.desc);
else if ((0, sdk_geometry_api_sdk_v2_1.isGBRequestError)(e)) {
throw new ShapeDiverBackendErrors_1.ShapeDiverGeometryBackendRequestError(e.message, e.desc);
}
else if (isGBError(e)) {
throw new ShapeDiverGeometryBackendError(e.message);
else if ((0, sdk_geometry_api_sdk_v2_1.isGBError)(e)) {
throw new ShapeDiverBackendErrors_1.ShapeDiverGeometryBackendError(e.message);
}
}
get(href, config = { responseType: 'arraybuffer' }, textureLoading = false) {
/**
* Get the requested resource either as a download or from the cache.
* If available, the registered session loading is used for download.
* Textures are downloaded via a specific endpoint and can be converted in this step as well.
* Depending on the provided caching options, the requested resource might already be cached.
*
* @param href
* @param config
* @param textureLoading
* @param textureConversion
* @returns
*/
get(href, config = { responseType: 'arraybuffer' }, textureLoading = false, textureConversion = false) {
return __awaiter(this, void 0, void 0, function* () {
const dataKey = this.hrefToDataKey(href);
// return element if it exists in cache
if (this._dataCache.has(dataKey))
return this.getFromCache(dataKey);
// try to get sessionId from href

@@ -63,2 +119,3 @@ let sessionId = this.getSessionId(href);

sessionLoading = this._sessionLoading[sessionId];
let loadingPromise;
// separation texture vs everything else

@@ -69,11 +126,28 @@ if (textureLoading) {

// take first session to load a texture that is not session related
return new Promise((resolve, reject) => {
sessionLoading.downloadTexture(sessionId, href).then((result) => {
resolve({
data: result[0],
headers: {
'content-type': result[1]
}
});
}).catch(e => reject(e));
loadingPromise = new Promise((resolve, reject) => {
sessionLoading.downloadTexture(sessionId, href).then((result) => __awaiter(this, void 0, void 0, function* () {
if (textureConversion) {
const image = yield Converter_1.Converter.instance.responseToImage({
data: result[0],
headers: {
'content-type': result[1]
}
});
resolve({
data: image,
size: result[0].byteLength,
headers: {
'content-type': result[1]
}
});
}
else {
resolve({
data: result[0],
headers: {
'content-type': result[1]
}
});
}
})).catch(e => reject(e));
}).catch(e => { throw this.convertError(e); });

@@ -84,3 +158,16 @@ }

// or load it directly if we don't have a session
return axios(href, Object.assign({ method: 'get' }, config))
loadingPromise = (0, axios_1.default)(href, Object.assign({ method: 'get' }, config))
.then((result) => __awaiter(this, void 0, void 0, function* () {
if (textureConversion) {
const image = yield Converter_1.Converter.instance.responseToImage(result);
return {
data: image,
size: result.data.byteLength,
headers: result.headers
};
}
else {
return result;
}
}))
.catch(e => { throw this.convertError(e); });

@@ -92,3 +179,3 @@ }

// if there is no session to load from, we use the fallback option
return axios(href, Object.assign({ method: 'get' }, config))
loadingPromise = (0, axios_1.default)(href, Object.assign({ method: 'get' }, config))
.catch(e => { throw this.convertError(e); });

@@ -98,3 +185,3 @@ }

// all data links where we could somehow find a session to load it with
return new Promise((resolve, reject) => {
loadingPromise = new Promise((resolve, reject) => {
sessionLoading.getAsset(href)

@@ -111,3 +198,3 @@ .then((result) => {

// if this fails, we just load it directly
const axiosPromise = axios(href, Object.assign({ method: 'get' }, config));
const axiosPromise = (0, axios_1.default)(href, Object.assign({ method: 'get' }, config));
axiosPromise.catch(e => reject(e));

@@ -119,9 +206,23 @@ resolve(axiosPromise);

}
if (this.enableCaching)
this.addToCache(dataKey, loadingPromise);
return loadingPromise;
});
}
/**
* Get the requested texture either as a download or from the cache.
*
* @param href
* @returns
*/
loadTexture(href) {
return __awaiter(this, void 0, void 0, function* () {
return this.get(href, undefined, true);
return this.get(href, undefined, true, true);
});
}
/**
* Add the data loading options from a session.
*
* @param sessionId
*/
removeDataLoading(sessionId) {

@@ -131,3 +232,55 @@ delete this._sessionLoading[sessionId];

// #endregion Public Methods (5)
// #region Private Methods (1)
// #region Private Methods (5)
/**
* Add
*
* @param key
* @param value
*/
addToCache(key, value) {
// Remove items from the cache until the cache size is smaller than the maximum cache size.
// Only resolved promises are evaluated, as unresolved promises don't add any size.
while (this.calculateCacheSize() >= this._maxCacheSize) {
// Remove the oldest entry if the cache is full
const oldestKey = this._dataCache.keys().next().value;
this._dataCache.delete(oldestKey);
}
const timestamp = Date.now();
this._dataCache.set(key, { value, timestamp, resolved: false });
// once the promise resolves, set resolved and size properties
value.then((promiseResult) => {
const size = promiseResult.size ? promiseResult.size : promiseResult.data.byteLength;
this._dataCache.set(key, { value, timestamp, resolved: true, size });
}).catch(e => { throw this.convertError(e); });
}
/**
* Calculate the current cache size from all resolved promises.
*
* @returns
*/
calculateCacheSize() {
let size = 0;
this._dataCache.forEach(value => {
if (value.resolved === true)
size += value.size;
});
return size;
}
/**
* Get the value of an object from the cache.
*
* @param key
* @returns
*/
getFromCache(key) {
const cachedObject = this._dataCache.get(key);
this._dataCache.set(key, { value: cachedObject.value, timestamp: Date.now(), resolved: cachedObject.resolved, size: cachedObject.size });
return cachedObject.value;
}
/**
* Get the session id of the provided href.
*
* @param href
* @returns
*/
getSessionId(href) {

@@ -147,3 +300,23 @@ // searching for "/session/SESSION_ID/{'output' | 'export' | 'texture'}/ASSET_DATA"

}
/**
* Convert the provided href to a data cache key.
* In this conversion the excludedQueryParameters are removed from the href.
*
* @param href
* @returns
*/
hrefToDataKey(href) {
const url = new URL(href);
// Create a URLSearchParams object from the existing query parameters
const params = new URLSearchParams(url.search);
for (let i = 0; i < this._excludedQueryParameters.length; i++)
// Remove specific query parameters
params.delete(this._excludedQueryParameters[i]);
// Reconstruct the URL with the modified query parameters
url.search = params.toString();
const hrefAsKey = url.toString();
return window.btoa(hrefAsKey);
}
}
exports.HttpClient = HttpClient;
//# sourceMappingURL=HttpClient.js.map
export interface HttpResponse<T = any> {
data: T;
headers: any;
size?: number;
}
//# sourceMappingURL=HttpResponse.d.ts.map

@@ -1,2 +0,3 @@

export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=HttpResponse.js.map

@@ -1,33 +0,81 @@

import { EventEngine } from './event-engine/EventEngine';
import { EVENTTYPE, EVENTTYPE_CAMERA, EVENTTYPE_INTERACTION, EVENTTYPE_RENDERING, EVENTTYPE_SCENE, EVENTTYPE_SESSION, EVENTTYPE_TASK, EVENTTYPE_VIEWPORT } from './event-engine/EventTypes';
import { SettingsEngine } from './settings-engine/SettingsEngine';
import { StateEngine } from './state-engine/StateEngine';
import { SystemInfo } from './system-info/SystemInfo';
import { DomEventEngine } from './dom-event-engine/DomEventEngine';
import { Converter } from './converter/Converter';
import { HttpClient } from './http-client/HttpClient';
import { InputValidator } from './input-validator/InputValidator';
import { TypeChecker } from './type-check/TypeChecker';
import { UuidGenerator } from './uuid-generator/UuidGenerator';
import { PerformanceEvaluator } from './performance-evaluator/PerformanceEvaluator';
import { Logger, LOGGING_LEVEL } from './logger/Logger';
import { StatePromise } from './state-engine/StatePromise';
import { ShapeDiverViewerArError, ShapeDiverViewerCameraError, ShapeDiverViewerDataProcessingError, ShapeDiverViewerEnvironmentMapError, ShapeDiverViewerLightError, ShapeDiverViewerSessionError, ShapeDiverViewerSettingsError, ShapeDiverViewerUnknownError, ShapeDiverViewerValidationError, ShapeDiverViewerWebGLError, ShapeDiverViewerInteractionError, ShapeDiverViewerViewportError } from './logger/ShapeDiverViewerErrors';
import { ShapeDiverViewerError, ShapeDiverViewerErrorType } from './logger/ShapeDiverError';
import { ShapeDiverGeometryBackendError, ShapeDiverGeometryBackendRequestError, ShapeDiverGeometryBackendResponseError } from './logger/ShapeDiverBackendErrors';
import { ShapeDiverResponseErrorType as ShapeDiverGeometryBackendResponseErrorType } from "@shapediver/sdk.geometry-api-sdk-v2";
import { isViewerError, isViewerUnknownError, isViewerDataProcessingError, isViewerEnvironmentMapError, isViewerWebGLError, isViewerSettingsError, isViewerSessionError, isViewerViewportError, isViewerLightError, isViewerCameraError, isARError, isViewerValidationError, isViewerInteractionError, isViewerGeometryBackendError, isViewerGeometryBackendGenericError, isViewerGeometryBackendRequestError, isViewerGeometryBackendResponseError } from './logger/ErrorTypeGuards';
export { EventEngine, EVENTTYPE, EVENTTYPE_CAMERA, EVENTTYPE_RENDERING, EVENTTYPE_SCENE, EVENTTYPE_SESSION, EVENTTYPE_VIEWPORT, EVENTTYPE_INTERACTION, EVENTTYPE_TASK };
export { SettingsEngine };
export { StateEngine, StatePromise };
export { SystemInfo };
export { DomEventEngine };
export { HttpClient };
export { UuidGenerator };
export { Converter };
export { TypeChecker };
export { InputValidator };
export { Logger, LOGGING_LEVEL, ShapeDiverViewerErrorType, ShapeDiverViewerError, ShapeDiverViewerDataProcessingError, ShapeDiverViewerEnvironmentMapError, ShapeDiverViewerWebGLError, ShapeDiverViewerSettingsError, ShapeDiverViewerSessionError, ShapeDiverViewerViewportError, ShapeDiverViewerUnknownError, ShapeDiverViewerArError, ShapeDiverViewerLightError, ShapeDiverViewerCameraError, ShapeDiverViewerValidationError, ShapeDiverViewerInteractionError, ShapeDiverGeometryBackendError, ShapeDiverGeometryBackendRequestError, ShapeDiverGeometryBackendResponseError, ShapeDiverGeometryBackendResponseErrorType };
export { isViewerError, isViewerUnknownError, isViewerDataProcessingError, isViewerEnvironmentMapError, isViewerWebGLError, isViewerSettingsError, isViewerSessionError, isViewerViewportError, isViewerLightError, isViewerCameraError, isARError, isViewerValidationError, isViewerInteractionError, isViewerGeometryBackendError, isViewerGeometryBackendGenericError, isViewerGeometryBackendRequestError, isViewerGeometryBackendResponseError };
export { PerformanceEvaluator };
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isARError = exports.isViewerCameraError = exports.isViewerLightError = exports.isViewerViewportError = exports.isViewerSessionError = exports.isViewerSettingsError = exports.isViewerWebGLError = exports.isViewerEnvironmentMapError = exports.isViewerDataProcessingError = exports.isViewerUnknownError = exports.isViewerError = exports.ShapeDiverGeometryBackendResponseErrorType = exports.ShapeDiverGeometryBackendResponseError = exports.ShapeDiverGeometryBackendRequestError = exports.ShapeDiverGeometryBackendError = exports.ShapeDiverViewerInteractionError = exports.ShapeDiverViewerValidationError = exports.ShapeDiverViewerCameraError = exports.ShapeDiverViewerLightError = exports.ShapeDiverViewerArError = exports.ShapeDiverViewerUnknownError = exports.ShapeDiverViewerViewportError = exports.ShapeDiverViewerSessionError = exports.ShapeDiverViewerSettingsError = exports.ShapeDiverViewerWebGLError = exports.ShapeDiverViewerEnvironmentMapError = exports.ShapeDiverViewerDataProcessingError = exports.ShapeDiverViewerError = exports.ShapeDiverViewerErrorType = exports.LOGGING_LEVEL = exports.Logger = exports.InputValidator = exports.TypeChecker = exports.Converter = exports.UuidGenerator = exports.HttpClient = exports.DomEventEngine = exports.SystemInfo = exports.StatePromise = exports.StateEngine = exports.SettingsEngine = exports.EVENTTYPE_TASK = exports.EVENTTYPE_INTERACTION = exports.EVENTTYPE_VIEWPORT = exports.EVENTTYPE_SESSION = exports.EVENTTYPE_SCENE = exports.EVENTTYPE_RENDERING = exports.EVENTTYPE_CAMERA = exports.EVENTTYPE = exports.EventEngine = void 0;
exports.PerformanceEvaluator = exports.isViewerGeometryBackendResponseError = exports.isViewerGeometryBackendRequestError = exports.isViewerGeometryBackendGenericError = exports.isViewerGeometryBackendError = exports.isViewerInteractionError = exports.isViewerValidationError = void 0;
const EventEngine_1 = require("./event-engine/EventEngine");
Object.defineProperty(exports, "EventEngine", { enumerable: true, get: function () { return EventEngine_1.EventEngine; } });
const EventTypes_1 = require("./event-engine/EventTypes");
Object.defineProperty(exports, "EVENTTYPE", { enumerable: true, get: function () { return EventTypes_1.EVENTTYPE; } });
Object.defineProperty(exports, "EVENTTYPE_CAMERA", { enumerable: true, get: function () { return EventTypes_1.EVENTTYPE_CAMERA; } });
Object.defineProperty(exports, "EVENTTYPE_INTERACTION", { enumerable: true, get: function () { return EventTypes_1.EVENTTYPE_INTERACTION; } });
Object.defineProperty(exports, "EVENTTYPE_RENDERING", { enumerable: true, get: function () { return EventTypes_1.EVENTTYPE_RENDERING; } });
Object.defineProperty(exports, "EVENTTYPE_SCENE", { enumerable: true, get: function () { return EventTypes_1.EVENTTYPE_SCENE; } });
Object.defineProperty(exports, "EVENTTYPE_SESSION", { enumerable: true, get: function () { return EventTypes_1.EVENTTYPE_SESSION; } });
Object.defineProperty(exports, "EVENTTYPE_TASK", { enumerable: true, get: function () { return EventTypes_1.EVENTTYPE_TASK; } });
Object.defineProperty(exports, "EVENTTYPE_VIEWPORT", { enumerable: true, get: function () { return EventTypes_1.EVENTTYPE_VIEWPORT; } });
const SettingsEngine_1 = require("./settings-engine/SettingsEngine");
Object.defineProperty(exports, "SettingsEngine", { enumerable: true, get: function () { return SettingsEngine_1.SettingsEngine; } });
const StateEngine_1 = require("./state-engine/StateEngine");
Object.defineProperty(exports, "StateEngine", { enumerable: true, get: function () { return StateEngine_1.StateEngine; } });
const SystemInfo_1 = require("./system-info/SystemInfo");
Object.defineProperty(exports, "SystemInfo", { enumerable: true, get: function () { return SystemInfo_1.SystemInfo; } });
const DomEventEngine_1 = require("./dom-event-engine/DomEventEngine");
Object.defineProperty(exports, "DomEventEngine", { enumerable: true, get: function () { return DomEventEngine_1.DomEventEngine; } });
const Converter_1 = require("./converter/Converter");
Object.defineProperty(exports, "Converter", { enumerable: true, get: function () { return Converter_1.Converter; } });
const HttpClient_1 = require("./http-client/HttpClient");
Object.defineProperty(exports, "HttpClient", { enumerable: true, get: function () { return HttpClient_1.HttpClient; } });
const InputValidator_1 = require("./input-validator/InputValidator");
Object.defineProperty(exports, "InputValidator", { enumerable: true, get: function () { return InputValidator_1.InputValidator; } });
const TypeChecker_1 = require("./type-check/TypeChecker");
Object.defineProperty(exports, "TypeChecker", { enumerable: true, get: function () { return TypeChecker_1.TypeChecker; } });
const UuidGenerator_1 = require("./uuid-generator/UuidGenerator");
Object.defineProperty(exports, "UuidGenerator", { enumerable: true, get: function () { return UuidGenerator_1.UuidGenerator; } });
const PerformanceEvaluator_1 = require("./performance-evaluator/PerformanceEvaluator");
Object.defineProperty(exports, "PerformanceEvaluator", { enumerable: true, get: function () { return PerformanceEvaluator_1.PerformanceEvaluator; } });
const Logger_1 = require("./logger/Logger");
Object.defineProperty(exports, "Logger", { enumerable: true, get: function () { return Logger_1.Logger; } });
Object.defineProperty(exports, "LOGGING_LEVEL", { enumerable: true, get: function () { return Logger_1.LOGGING_LEVEL; } });
const StatePromise_1 = require("./state-engine/StatePromise");
Object.defineProperty(exports, "StatePromise", { enumerable: true, get: function () { return StatePromise_1.StatePromise; } });
const ShapeDiverViewerErrors_1 = require("./logger/ShapeDiverViewerErrors");
Object.defineProperty(exports, "ShapeDiverViewerArError", { enumerable: true, get: function () { return ShapeDiverViewerErrors_1.ShapeDiverViewerArError; } });
Object.defineProperty(exports, "ShapeDiverViewerCameraError", { enumerable: true, get: function () { return ShapeDiverViewerErrors_1.ShapeDiverViewerCameraError; } });
Object.defineProperty(exports, "ShapeDiverViewerDataProcessingError", { enumerable: true, get: function () { return ShapeDiverViewerErrors_1.ShapeDiverViewerDataProcessingError; } });
Object.defineProperty(exports, "ShapeDiverViewerEnvironmentMapError", { enumerable: true, get: function () { return ShapeDiverViewerErrors_1.ShapeDiverViewerEnvironmentMapError; } });
Object.defineProperty(exports, "ShapeDiverViewerLightError", { enumerable: true, get: function () { return ShapeDiverViewerErrors_1.ShapeDiverViewerLightError; } });
Object.defineProperty(exports, "ShapeDiverViewerSessionError", { enumerable: true, get: function () { return ShapeDiverViewerErrors_1.ShapeDiverViewerSessionError; } });
Object.defineProperty(exports, "ShapeDiverViewerSettingsError", { enumerable: true, get: function () { return ShapeDiverViewerErrors_1.ShapeDiverViewerSettingsError; } });
Object.defineProperty(exports, "ShapeDiverViewerUnknownError", { enumerable: true, get: function () { return ShapeDiverViewerErrors_1.ShapeDiverViewerUnknownError; } });
Object.defineProperty(exports, "ShapeDiverViewerValidationError", { enumerable: true, get: function () { return ShapeDiverViewerErrors_1.ShapeDiverViewerValidationError; } });
Object.defineProperty(exports, "ShapeDiverViewerWebGLError", { enumerable: true, get: function () { return ShapeDiverViewerErrors_1.ShapeDiverViewerWebGLError; } });
Object.defineProperty(exports, "ShapeDiverViewerInteractionError", { enumerable: true, get: function () { return ShapeDiverViewerErrors_1.ShapeDiverViewerInteractionError; } });
Object.defineProperty(exports, "ShapeDiverViewerViewportError", { enumerable: true, get: function () { return ShapeDiverViewerErrors_1.ShapeDiverViewerViewportError; } });
const ShapeDiverError_1 = require("./logger/ShapeDiverError");
Object.defineProperty(exports, "ShapeDiverViewerError", { enumerable: true, get: function () { return ShapeDiverError_1.ShapeDiverViewerError; } });
Object.defineProperty(exports, "ShapeDiverViewerErrorType", { enumerable: true, get: function () { return ShapeDiverError_1.ShapeDiverViewerErrorType; } });
const ShapeDiverBackendErrors_1 = require("./logger/ShapeDiverBackendErrors");
Object.defineProperty(exports, "ShapeDiverGeometryBackendError", { enumerable: true, get: function () { return ShapeDiverBackendErrors_1.ShapeDiverGeometryBackendError; } });
Object.defineProperty(exports, "ShapeDiverGeometryBackendRequestError", { enumerable: true, get: function () { return ShapeDiverBackendErrors_1.ShapeDiverGeometryBackendRequestError; } });
Object.defineProperty(exports, "ShapeDiverGeometryBackendResponseError", { enumerable: true, get: function () { return ShapeDiverBackendErrors_1.ShapeDiverGeometryBackendResponseError; } });
const sdk_geometry_api_sdk_v2_1 = require("@shapediver/sdk.geometry-api-sdk-v2");
Object.defineProperty(exports, "ShapeDiverGeometryBackendResponseErrorType", { enumerable: true, get: function () { return sdk_geometry_api_sdk_v2_1.ShapeDiverResponseErrorType; } });
const ErrorTypeGuards_1 = require("./logger/ErrorTypeGuards");
Object.defineProperty(exports, "isViewerError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerError; } });
Object.defineProperty(exports, "isViewerUnknownError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerUnknownError; } });
Object.defineProperty(exports, "isViewerDataProcessingError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerDataProcessingError; } });
Object.defineProperty(exports, "isViewerEnvironmentMapError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerEnvironmentMapError; } });
Object.defineProperty(exports, "isViewerWebGLError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerWebGLError; } });
Object.defineProperty(exports, "isViewerSettingsError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerSettingsError; } });
Object.defineProperty(exports, "isViewerSessionError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerSessionError; } });
Object.defineProperty(exports, "isViewerViewportError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerViewportError; } });
Object.defineProperty(exports, "isViewerLightError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerLightError; } });
Object.defineProperty(exports, "isViewerCameraError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerCameraError; } });
Object.defineProperty(exports, "isARError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isARError; } });
Object.defineProperty(exports, "isViewerValidationError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerValidationError; } });
Object.defineProperty(exports, "isViewerInteractionError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerInteractionError; } });
Object.defineProperty(exports, "isViewerGeometryBackendError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerGeometryBackendError; } });
Object.defineProperty(exports, "isViewerGeometryBackendGenericError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerGeometryBackendGenericError; } });
Object.defineProperty(exports, "isViewerGeometryBackendRequestError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerGeometryBackendRequestError; } });
Object.defineProperty(exports, "isViewerGeometryBackendResponseError", { enumerable: true, get: function () { return ErrorTypeGuards_1.isViewerGeometryBackendResponseError; } });
//# sourceMappingURL=index.js.map

@@ -1,10 +0,16 @@

import DOMPurify from 'dompurify';
import { Logger } from '../logger/Logger';
import { ShapeDiverViewerValidationError } from '../logger/ShapeDiverViewerErrors';
import { TypeChecker } from '../type-check/TypeChecker';
export class InputValidator {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InputValidator = void 0;
const dompurify_1 = __importDefault(require("dompurify"));
const Logger_1 = require("../logger/Logger");
const ShapeDiverViewerErrors_1 = require("../logger/ShapeDiverViewerErrors");
const TypeChecker_1 = require("../type-check/TypeChecker");
class InputValidator {
constructor() {
// #region Properties (3)
this._logger = Logger.instance;
this._typeChecker = TypeChecker.instance;
this._logger = Logger_1.Logger.instance;
this._typeChecker = TypeChecker_1.TypeChecker.instance;
// #endregion Private Methods (1)

@@ -20,3 +26,3 @@ }

sanitize(input) {
return DOMPurify.sanitize(input);
return dompurify_1.default.sanitize(input);
}

@@ -27,3 +33,3 @@ validateAndError(scope, value, type, defined = true, enumValues = []) {

return;
throw new ShapeDiverViewerValidationError(`${scope}: Input could not be validated. ${value} is not of type ${type}.${defined === false ? ' (Can also be undefined)' : ''}`, value, type);
throw new ShapeDiverViewerErrors_1.ShapeDiverViewerValidationError(`${scope}: Input could not be validated. ${value} is not of type ${type}.${defined === false ? ' (Can also be undefined)' : ''}`, value, type);
}

@@ -127,2 +133,3 @@ // #endregion Public Methods (2)

}
exports.InputValidator = InputValidator;
//# sourceMappingURL=InputValidator.js.map

@@ -1,104 +0,124 @@

import { ShapeDiverViewerErrorType } from "./ShapeDiverError";
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isViewerGeometryBackendResponseError = exports.isViewerGeometryBackendRequestError = exports.isViewerGeometryBackendGenericError = exports.isViewerGeometryBackendError = exports.isViewerInteractionError = exports.isViewerValidationError = exports.isARError = exports.isViewerCameraError = exports.isViewerLightError = exports.isViewerViewportError = exports.isViewerSessionError = exports.isViewerSettingsError = exports.isViewerWebGLError = exports.isViewerEnvironmentMapError = exports.isViewerDataProcessingError = exports.isViewerUnknownError = exports.isViewerError = void 0;
const ShapeDiverError_1 = require("./ShapeDiverError");
/** Type guard for all error types of the viewer package. */
export function isViewerError(e) {
function isViewerError(e) {
return e instanceof Error &&
"errorType" in e &&
Object.values(ShapeDiverViewerErrorType).includes(e.errorType);
Object.values(ShapeDiverError_1.ShapeDiverViewerErrorType).includes(e.errorType);
}
exports.isViewerError = isViewerError;
/** Type guard for an unknown viewer error. */
export function isViewerUnknownError(e) {
function isViewerUnknownError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.UNKNOWN;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.UNKNOWN;
}
exports.isViewerUnknownError = isViewerUnknownError;
/** Type guard for a data processing viewer error. */
export function isViewerDataProcessingError(e) {
function isViewerDataProcessingError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.DATA_PROCESSING_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.DATA_PROCESSING_ERROR;
}
exports.isViewerDataProcessingError = isViewerDataProcessingError;
/** Type guard for a environment map viewer error. */
export function isViewerEnvironmentMapError(e) {
function isViewerEnvironmentMapError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.ENVIRONMENT_MAP_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.ENVIRONMENT_MAP_ERROR;
}
exports.isViewerEnvironmentMapError = isViewerEnvironmentMapError;
/** Type guard for a webGL viewer error. */
export function isViewerWebGLError(e) {
function isViewerWebGLError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.WEBGL_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.WEBGL_ERROR;
}
exports.isViewerWebGLError = isViewerWebGLError;
/** Type guard for a settings viewer error. */
export function isViewerSettingsError(e) {
function isViewerSettingsError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.SETTINGS_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.SETTINGS_ERROR;
}
exports.isViewerSettingsError = isViewerSettingsError;
/** Type guard for a session viewer error. */
export function isViewerSessionError(e) {
function isViewerSessionError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.SESSION_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.SESSION_ERROR;
}
exports.isViewerSessionError = isViewerSessionError;
/** Type guard for a viewport viewer error. */
export function isViewerViewportError(e) {
function isViewerViewportError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.VIEWPORT_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.VIEWPORT_ERROR;
}
exports.isViewerViewportError = isViewerViewportError;
/** Type guard for a light viewer error. */
export function isViewerLightError(e) {
function isViewerLightError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.LIGHT_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.LIGHT_ERROR;
}
exports.isViewerLightError = isViewerLightError;
/** Type guard for a camera viewer error. */
export function isViewerCameraError(e) {
function isViewerCameraError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.CAMERA_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.CAMERA_ERROR;
}
exports.isViewerCameraError = isViewerCameraError;
/** Type guard for an AR viewer error. */
export function isARError(e) {
function isARError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.AR_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.AR_ERROR;
}
exports.isARError = isARError;
/** Type guard for a validation viewer error. */
export function isViewerValidationError(e) {
function isViewerValidationError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.VALIDATION_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.VALIDATION_ERROR;
}
exports.isViewerValidationError = isViewerValidationError;
/** Type guard for a interaction viewer error. */
export function isViewerInteractionError(e) {
function isViewerInteractionError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.INTERACTION_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.INTERACTION_ERROR;
}
exports.isViewerInteractionError = isViewerInteractionError;
/** Type guard for all error types of the Geometry Backend SDK package that are mapped to viewer errors. */
export function isViewerGeometryBackendError(e) {
function isViewerGeometryBackendError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.GEOMETRY_BACKEND_ERROR || e.errorType === ShapeDiverViewerErrorType.GEOMETRY_BACKEND_REQUEST_ERROR || e.errorType === ShapeDiverViewerErrorType.GEOMETRY_BACKEND_REQUEST_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.GEOMETRY_BACKEND_ERROR || e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.GEOMETRY_BACKEND_REQUEST_ERROR || e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.GEOMETRY_BACKEND_REQUEST_ERROR;
}
exports.isViewerGeometryBackendError = isViewerGeometryBackendError;
/** Type guard for a Geometry Backend SDK generic error that is mapped to a viewer error. */
export function isViewerGeometryBackendGenericError(e) {
function isViewerGeometryBackendGenericError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.GEOMETRY_BACKEND_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.GEOMETRY_BACKEND_ERROR;
}
exports.isViewerGeometryBackendGenericError = isViewerGeometryBackendGenericError;
/** Type guard for a Geometry Backend SDK request error that is mapped to a viewer error. */
export function isViewerGeometryBackendRequestError(e) {
function isViewerGeometryBackendRequestError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.GEOMETRY_BACKEND_REQUEST_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.GEOMETRY_BACKEND_REQUEST_ERROR;
}
exports.isViewerGeometryBackendRequestError = isViewerGeometryBackendRequestError;
/** Type guard for a Geometry Backend SDK response error that is mapped to a viewer error. */
export function isViewerGeometryBackendResponseError(e) {
function isViewerGeometryBackendResponseError(e) {
return e instanceof Error &&
"errorType" in e &&
e.errorType === ShapeDiverViewerErrorType.GEOMETRY_BACKEND_RESPONSE_ERROR;
e.errorType === ShapeDiverError_1.ShapeDiverViewerErrorType.GEOMETRY_BACKEND_RESPONSE_ERROR;
}
exports.isViewerGeometryBackendResponseError = isViewerGeometryBackendResponseError;
//# sourceMappingURL=ErrorTypeGuards.js.map

@@ -1,2 +0,5 @@

export var LOGGING_LEVEL;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Logger = exports.LOGGING_LEVEL = void 0;
var LOGGING_LEVEL;
(function (LOGGING_LEVEL) {

@@ -12,4 +15,4 @@ LOGGING_LEVEL["NONE"] = "none";

LOGGING_LEVEL["DEBUG_LOW"] = "debug_low";
})(LOGGING_LEVEL || (LOGGING_LEVEL = {}));
export class Logger {
})(LOGGING_LEVEL = exports.LOGGING_LEVEL || (exports.LOGGING_LEVEL = {}));
class Logger {
constructor() {

@@ -176,2 +179,3 @@ // #region Properties (8)

}
exports.Logger = Logger;
//# sourceMappingURL=Logger.js.map

@@ -1,13 +0,17 @@

import { ShapeDiverViewerError, ShapeDiverViewerErrorType } from "./ShapeDiverError";
export class ShapeDiverGeometryBackendRequestError extends ShapeDiverViewerError {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ShapeDiverGeometryBackendError = exports.ShapeDiverGeometryBackendResponseError = exports.ShapeDiverGeometryBackendRequestError = void 0;
const ShapeDiverError_1 = require("./ShapeDiverError");
class ShapeDiverGeometryBackendRequestError extends ShapeDiverError_1.ShapeDiverViewerError {
// #region Constructors (1)
constructor(message, desc) {
super(ShapeDiverViewerErrorType.GEOMETRY_BACKEND_REQUEST_ERROR, desc, message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.GEOMETRY_BACKEND_REQUEST_ERROR, desc, message);
this.desc = desc;
}
}
export class ShapeDiverGeometryBackendResponseError extends ShapeDiverViewerError {
exports.ShapeDiverGeometryBackendRequestError = ShapeDiverGeometryBackendRequestError;
class ShapeDiverGeometryBackendResponseError extends ShapeDiverError_1.ShapeDiverViewerError {
// #region Constructors (1)
constructor(message, status, geometryBackendErrorType, desc) {
super(ShapeDiverViewerErrorType.GEOMETRY_BACKEND_RESPONSE_ERROR, desc, message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.GEOMETRY_BACKEND_RESPONSE_ERROR, desc, message);
this.status = status;

@@ -18,8 +22,10 @@ this.geometryBackendErrorType = geometryBackendErrorType;

}
export class ShapeDiverGeometryBackendError extends ShapeDiverViewerError {
exports.ShapeDiverGeometryBackendResponseError = ShapeDiverGeometryBackendResponseError;
class ShapeDiverGeometryBackendError extends ShapeDiverError_1.ShapeDiverViewerError {
// #region Constructors (1)
constructor(message) {
super(ShapeDiverViewerErrorType.GEOMETRY_BACKEND_ERROR, "A generic geometry backend error occurred.", message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.GEOMETRY_BACKEND_ERROR, "A generic geometry backend error occurred.", message);
}
}
exports.ShapeDiverGeometryBackendError = ShapeDiverGeometryBackendError;
//# sourceMappingURL=ShapeDiverBackendErrors.js.map

@@ -1,2 +0,5 @@

export var ShapeDiverViewerErrorType;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ShapeDiverViewerError = exports.ShapeDiverError = exports.ShapeDiverViewerErrorType = void 0;
var ShapeDiverViewerErrorType;
(function (ShapeDiverViewerErrorType) {

@@ -19,4 +22,4 @@ ShapeDiverViewerErrorType["AR_ERROR"] = "SdARError";

ShapeDiverViewerErrorType["UNKNOWN"] = "";
})(ShapeDiverViewerErrorType || (ShapeDiverViewerErrorType = {}));
export class ShapeDiverError extends Error {
})(ShapeDiverViewerErrorType = exports.ShapeDiverViewerErrorType || (exports.ShapeDiverViewerErrorType = {}));
class ShapeDiverError extends Error {
// #region Constructors (1)

@@ -27,3 +30,4 @@ constructor(message) {

}
export class ShapeDiverViewerError extends ShapeDiverError {
exports.ShapeDiverError = ShapeDiverError;
class ShapeDiverViewerError extends ShapeDiverError {
constructor(errorType, desc, message) {

@@ -39,2 +43,3 @@ super(message);

}
exports.ShapeDiverViewerError = ShapeDiverViewerError;
//# sourceMappingURL=ShapeDiverError.js.map

@@ -1,5 +0,8 @@

import { ShapeDiverViewerError, ShapeDiverViewerErrorType } from "./ShapeDiverError";
export class ShapeDiverViewerUnknownError extends ShapeDiverViewerError {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ShapeDiverViewerInteractionError = exports.ShapeDiverViewerValidationError = exports.ShapeDiverViewerArError = exports.ShapeDiverViewerCameraError = exports.ShapeDiverViewerLightError = exports.ShapeDiverViewerViewportError = exports.ShapeDiverViewerSessionError = exports.ShapeDiverViewerSettingsError = exports.ShapeDiverViewerWebGLError = exports.ShapeDiverViewerEnvironmentMapError = exports.ShapeDiverViewerDataProcessingError = exports.ShapeDiverViewerUnknownError = void 0;
const ShapeDiverError_1 = require("./ShapeDiverError");
class ShapeDiverViewerUnknownError extends ShapeDiverError_1.ShapeDiverViewerError {
constructor(message, errorObject) {
super(ShapeDiverViewerErrorType.UNKNOWN, 'An unknown error occurred.', message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.UNKNOWN, 'An unknown error occurred.', message);
this.message = message;

@@ -11,5 +14,6 @@ this.errorObject = errorObject;

}
export class ShapeDiverViewerDataProcessingError extends ShapeDiverViewerError {
exports.ShapeDiverViewerUnknownError = ShapeDiverViewerUnknownError;
class ShapeDiverViewerDataProcessingError extends ShapeDiverError_1.ShapeDiverViewerError {
constructor(message, errorObject) {
super(ShapeDiverViewerErrorType.DATA_PROCESSING_ERROR, 'An error occurred while processing data.', message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.DATA_PROCESSING_ERROR, 'An error occurred while processing data.', message);
this.message = message;

@@ -19,5 +23,6 @@ this.errorObject = errorObject;

}
export class ShapeDiverViewerEnvironmentMapError extends ShapeDiverViewerError {
exports.ShapeDiverViewerDataProcessingError = ShapeDiverViewerDataProcessingError;
class ShapeDiverViewerEnvironmentMapError extends ShapeDiverError_1.ShapeDiverViewerError {
constructor(message, url, errorObject) {
super(ShapeDiverViewerErrorType.ENVIRONMENT_MAP_ERROR, 'An error occurred while loading the environment map.', message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.ENVIRONMENT_MAP_ERROR, 'An error occurred while loading the environment map.', message);
this.message = message;

@@ -28,5 +33,6 @@ this.url = url;

}
export class ShapeDiverViewerWebGLError extends ShapeDiverViewerError {
exports.ShapeDiverViewerEnvironmentMapError = ShapeDiverViewerEnvironmentMapError;
class ShapeDiverViewerWebGLError extends ShapeDiverError_1.ShapeDiverViewerError {
constructor(message, errorObject) {
super(ShapeDiverViewerErrorType.WEBGL_ERROR, 'An error occurred regarding to the WebGL context.', message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.WEBGL_ERROR, 'An error occurred regarding to the WebGL context.', message);
this.message = message;

@@ -36,5 +42,6 @@ this.errorObject = errorObject;

}
export class ShapeDiverViewerSettingsError extends ShapeDiverViewerError {
exports.ShapeDiverViewerWebGLError = ShapeDiverViewerWebGLError;
class ShapeDiverViewerSettingsError extends ShapeDiverError_1.ShapeDiverViewerError {
constructor(message, errorObject) {
super(ShapeDiverViewerErrorType.SETTINGS_ERROR, 'An error occurred while loading the settings.', message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.SETTINGS_ERROR, 'An error occurred while loading the settings.', message);
this.message = message;

@@ -44,5 +51,6 @@ this.errorObject = errorObject;

}
export class ShapeDiverViewerSessionError extends ShapeDiverViewerError {
exports.ShapeDiverViewerSettingsError = ShapeDiverViewerSettingsError;
class ShapeDiverViewerSessionError extends ShapeDiverError_1.ShapeDiverViewerError {
constructor(message, errorObject) {
super(ShapeDiverViewerErrorType.SESSION_ERROR, 'An error occurred while working with the session.', message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.SESSION_ERROR, 'An error occurred while working with the session.', message);
this.message = message;

@@ -52,5 +60,6 @@ this.errorObject = errorObject;

}
export class ShapeDiverViewerViewportError extends ShapeDiverViewerError {
exports.ShapeDiverViewerSessionError = ShapeDiverViewerSessionError;
class ShapeDiverViewerViewportError extends ShapeDiverError_1.ShapeDiverViewerError {
constructor(message, errorObject) {
super(ShapeDiverViewerErrorType.VIEWPORT_ERROR, 'An error occurred while working with the viewport.', message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.VIEWPORT_ERROR, 'An error occurred while working with the viewport.', message);
this.message = message;

@@ -60,5 +69,6 @@ this.errorObject = errorObject;

}
export class ShapeDiverViewerLightError extends ShapeDiverViewerError {
exports.ShapeDiverViewerViewportError = ShapeDiverViewerViewportError;
class ShapeDiverViewerLightError extends ShapeDiverError_1.ShapeDiverViewerError {
constructor(message, errorObject) {
super(ShapeDiverViewerErrorType.LIGHT_ERROR, 'An error occurred while working with the lights.', message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.LIGHT_ERROR, 'An error occurred while working with the lights.', message);
this.message = message;

@@ -68,5 +78,6 @@ this.errorObject = errorObject;

}
export class ShapeDiverViewerCameraError extends ShapeDiverViewerError {
exports.ShapeDiverViewerLightError = ShapeDiverViewerLightError;
class ShapeDiverViewerCameraError extends ShapeDiverError_1.ShapeDiverViewerError {
constructor(message, errorObject) {
super(ShapeDiverViewerErrorType.CAMERA_ERROR, 'An error occurred while working with the cameras.', message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.CAMERA_ERROR, 'An error occurred while working with the cameras.', message);
this.message = message;

@@ -76,5 +87,6 @@ this.errorObject = errorObject;

}
export class ShapeDiverViewerArError extends ShapeDiverViewerError {
exports.ShapeDiverViewerCameraError = ShapeDiverViewerCameraError;
class ShapeDiverViewerArError extends ShapeDiverError_1.ShapeDiverViewerError {
constructor(message, errorObject) {
super(ShapeDiverViewerErrorType.AR_ERROR, 'An error occurred while working with AR.', message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.AR_ERROR, 'An error occurred while working with AR.', message);
this.message = message;

@@ -84,5 +96,6 @@ this.errorObject = errorObject;

}
export class ShapeDiverViewerValidationError extends ShapeDiverViewerError {
exports.ShapeDiverViewerArError = ShapeDiverViewerArError;
class ShapeDiverViewerValidationError extends ShapeDiverError_1.ShapeDiverViewerError {
constructor(message, value, requestedType, errorObject) {
super(ShapeDiverViewerErrorType.VALIDATION_ERROR, 'An error occurred while validating the value.', message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.VALIDATION_ERROR, 'An error occurred while validating the value.', message);
this.message = message;

@@ -94,8 +107,10 @@ this.value = value;

}
export class ShapeDiverViewerInteractionError extends ShapeDiverViewerError {
exports.ShapeDiverViewerValidationError = ShapeDiverViewerValidationError;
class ShapeDiverViewerInteractionError extends ShapeDiverError_1.ShapeDiverViewerError {
constructor(message) {
super(ShapeDiverViewerErrorType.INTERACTION_ERROR, 'An error occurred with interactions.', message);
super(ShapeDiverError_1.ShapeDiverViewerErrorType.INTERACTION_ERROR, 'An error occurred with interactions.', message);
this.message = message;
}
}
exports.ShapeDiverViewerInteractionError = ShapeDiverViewerInteractionError;
//# sourceMappingURL=ShapeDiverViewerErrors.js.map

@@ -6,2 +6,8 @@ export declare class PerformanceEvaluator {

/**
* Continue the performance evaluation.
*
* @param id
*/
continueSection(sectionId: string): void;
/**
* End the performance evaluation and calculate the duration.

@@ -28,2 +34,3 @@ *

start: number;
continued?: number;
end?: number;

@@ -43,2 +50,8 @@ duration?: number;

/**
* Pause the performance evaluation.
*
* @param id
*/
pauseSection(sectionId: string): void;
/**
* Start the evaluation with a specific id.

@@ -45,0 +58,0 @@ *

@@ -1,2 +0,5 @@

export class PerformanceEvaluator {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PerformanceEvaluator = void 0;
class PerformanceEvaluator {
// #endregion Properties (2)

@@ -8,4 +11,20 @@ // #region Public Static Accessors (1)

// #endregion Public Static Accessors (1)
// #region Public Methods (6)
// #region Public Methods (8)
/**
* Continue the performance evaluation.
*
* @param id
*/
continueSection(sectionId) {
if (!this._eval)
return;
if (this._eval.end)
return;
if (!this._eval.section[sectionId])
return;
if (this._eval.section[sectionId].end)
return;
this._eval.section[sectionId].continued = performance.now();
}
/**
* End the performance evaluation and calculate the duration.

@@ -38,3 +57,3 @@ *

this._eval.section[sectionId].end = performance.now();
this._eval.section[sectionId].duration = this._eval.section[sectionId].end - this._eval.section[sectionId].start;
this._eval.section[sectionId].duration = (this._eval.section[sectionId].duration || 0) + (this._eval.section[sectionId].end - (this._eval.section[sectionId].continued || this._eval.section[sectionId].start));
}

@@ -59,2 +78,18 @@ /**

/**
* Pause the performance evaluation.
*
* @param id
*/
pauseSection(sectionId) {
if (!this._eval)
return;
if (this._eval.end)
return;
if (!this._eval.section[sectionId])
return;
if (this._eval.section[sectionId].end)
return;
this._eval.section[sectionId].duration = (this._eval.section[sectionId].duration || 0) + performance.now() - (this._eval.section[sectionId].continued || this._eval.section[sectionId].start);
}
/**
* Start the evaluation with a specific id.

@@ -85,2 +120,3 @@ *

}
exports.PerformanceEvaluator = PerformanceEvaluator;
//# sourceMappingURL=PerformanceEvaluator.js.map

@@ -1,11 +0,14 @@

import { convert, validate, Defaults, latestVersion } from '@shapediver/viewer.settings';
import { EventEngine } from '../event-engine/EventEngine';
import { Logger } from '../logger/Logger';
import { ShapeDiverViewerSettingsError } from '../logger/ShapeDiverViewerErrors';
export class SettingsEngine {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SettingsEngine = void 0;
const viewer_settings_1 = require("@shapediver/viewer.settings");
const EventEngine_1 = require("../event-engine/EventEngine");
const Logger_1 = require("../logger/Logger");
const ShapeDiverViewerErrors_1 = require("../logger/ShapeDiverViewerErrors");
class SettingsEngine {
constructor() {
// #region Properties (8)
this._eventEngine = EventEngine.instance;
this._logger = Logger.instance;
this._settings = Defaults();
this._eventEngine = EventEngine_1.EventEngine.instance;
this._logger = Logger_1.Logger.instance;
this._settings = (0, viewer_settings_1.Defaults)();
// #endregion Private Methods (1)

@@ -75,8 +78,8 @@ }

if (JSON.stringify(json) !== JSON.stringify({})) {
const prevVersions = ['1.0', '2.0', '3.0', '3.1', '3.2', '3.3', '3.4'];
const prevVersions = ['1.0', '2.0', '3.0', '3.1', '3.2', '3.3', '3.4', '4.0'];
for (let i = 0; i < prevVersions.length; i++) {
const v = prevVersions[i];
try {
validate(json, v);
this._settings = convert(json, latestVersion);
(0, viewer_settings_1.validate)(json, v);
this._settings = (0, viewer_settings_1.convert)(json, viewer_settings_1.latestVersion);
this.cleanSettings(this._settings);

@@ -88,4 +91,4 @@ return;

try {
validate(json, latestVersion);
this._settings = convert(json, latestVersion);
(0, viewer_settings_1.validate)(json, viewer_settings_1.latestVersion);
this._settings = (0, viewer_settings_1.convert)(json, viewer_settings_1.latestVersion);
this.cleanSettings(this._settings);

@@ -95,7 +98,7 @@ return;

catch (e) {
throw new ShapeDiverViewerSettingsError('SettingsEngine.loadSettings: Settings could not be validated. ' + e.message, e);
throw new ShapeDiverViewerErrors_1.ShapeDiverViewerSettingsError('SettingsEngine.loadSettings: Settings could not be validated. ' + e.message, e);
}
}
else {
this._settings = Defaults();
this._settings = (0, viewer_settings_1.Defaults)();
return;

@@ -105,3 +108,3 @@ }

reset() {
this._settings = Defaults();
this._settings = (0, viewer_settings_1.Defaults)();
}

@@ -153,2 +156,3 @@ // #endregion Public Methods (4)

}
exports.SettingsEngine = SettingsEngine;
//# sourceMappingURL=SettingsEngine.js.map

@@ -1,3 +0,6 @@

import { StatePromise } from './StatePromise';
export class StateEngine {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StateEngine = void 0;
const StatePromise_1 = require("./StatePromise");
class StateEngine {
// #endregion Properties (6)

@@ -7,6 +10,6 @@ // #region Constructors (1)

// #region Properties (6)
this._fontLoaded = new StatePromise();
this._fontLoaded = new StatePromise_1.StatePromise();
this._renderingEngines = {};
this._sessionEngines = {};
this._fontLoaded = new StatePromise();
this._fontLoaded = new StatePromise_1.StatePromise();
}

@@ -30,2 +33,3 @@ // #endregion Constructors (1)

}
exports.StateEngine = StateEngine;
//# sourceMappingURL=StateEngine.js.map

@@ -0,1 +1,2 @@

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -10,3 +11,5 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
export class StatePromise {
Object.defineProperty(exports, "__esModule", { value: true });
exports.StatePromise = void 0;
class StatePromise {
constructor() {

@@ -53,2 +56,3 @@ this._resolved = false;

}
exports.StatePromise = StatePromise;
//# sourceMappingURL=StatePromise.js.map

@@ -1,7 +0,13 @@

import UAParser from 'ua-parser-js';
export class SystemInfo {
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SystemInfo = void 0;
const ua_parser_js_1 = __importDefault(require("ua-parser-js"));
class SystemInfo {
// #endregion Properties (5)
// #region Constructors (1)
constructor() {
this._parser = new UAParser();
this._parser = new ua_parser_js_1.default();
const isInternetExplorer = typeof window !== 'undefined' && window.navigator && window.navigator.userAgent.indexOf('Trident') > -1;

@@ -113,2 +119,3 @@ this._isBrowser = isInternetExplorer ||

}
exports.SystemInfo = SystemInfo;
//# sourceMappingURL=SystemInfo.js.map

@@ -1,2 +0,5 @@

export class TypeChecker {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeChecker = void 0;
class TypeChecker {
// #endregion Properties (1)

@@ -16,2 +19,3 @@ // #region Public Static Accessors (1)

}
exports.TypeChecker = TypeChecker;
//# sourceMappingURL=TypeChecker.js.map

@@ -1,3 +0,6 @@

import { parse as parseUUID, stringify as stringifyUUID, v4, validate as validateUUID } from 'uuid';
export class UuidGenerator {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UuidGenerator = void 0;
const uuid_1 = require("uuid");
class UuidGenerator {
// #endregion Properties (1)

@@ -14,3 +17,3 @@ // #region Public Static Accessors (1)

create() {
return v4();
return (0, uuid_1.v4)();
}

@@ -24,3 +27,3 @@ /**

parse(uuid) {
return parseUUID(uuid);
return (0, uuid_1.parse)(uuid);
}

@@ -34,3 +37,3 @@ /**

stringify(uuid) {
return stringifyUUID(uuid);
return (0, uuid_1.stringify)(uuid);
}

@@ -43,5 +46,6 @@ /**

validate(uuid) {
return validateUUID(uuid);
return (0, uuid_1.validate)(uuid);
}
}
exports.UuidGenerator = UuidGenerator;
//# sourceMappingURL=UuidGenerator.js.map
{
"name": "@shapediver/viewer.shared.services",
"version": "2.10.1-rc.0",
"version": "2.11.0",
"description": "",

@@ -44,4 +44,4 @@ "keywords": [],

"@shapediver/sdk.geometry-api-sdk-v2": "1.6.0",
"@shapediver/viewer.settings": "0.5.5",
"@shapediver/viewer.shared.build-data": "2.10.1-rc.0",
"@shapediver/viewer.settings": "0.5.7",
"@shapediver/viewer.shared.build-data": "2.11.0",
"@types/dompurify": "^2.3.1",

@@ -56,3 +56,3 @@ "@types/ua-parser-js": "^0.7.36",

},
"gitHead": "7d6e75b740536d82351b9f4d1c2b0722bbde5a87"
"gitHead": "abc828ee5f772bc79b737c994716b8ec372503ef"
}

@@ -1,3 +0,3 @@

import { vec3, vec4 } from 'gl-matrix'
import { TinyColor } from '@ctrl/tinycolor'
import { vec3 } from 'gl-matrix';
import { ColorInput, TinyColor } from '@ctrl/tinycolor';
import { HttpClient } from '../http-client/HttpClient';

@@ -32,6 +32,6 @@ import { HttpResponse } from '../http-client/HttpResponse';

});
data = data.replace('data:image/svg+xml;base64,', '')
data = data.replace('data:image/svg+xml;base64,', '');
data = atob(data);
let svgC = document.createElement('DIV');
const svgC = document.createElement('DIV');
svgC.id = 'svgc';

@@ -41,4 +41,4 @@ svgC.innerHTML = <string>data;

// now we can access the svg element as a DOM object
let svgE = svgC.getElementsByTagName('svg');
let childImageURIs: string[] = [];
const svgE = svgC.getElementsByTagName('svg');
const childImageURIs: string[] = [];
let styleURIs: string[] = [];

@@ -49,3 +49,3 @@

for (let j = 0; j < 2; ++j) {
let childImages = <HTMLCollectionOf<SVGImageElement>>svgE[i].getElementsByTagName(['image', 'img'][j]);
const childImages = <HTMLCollectionOf<SVGImageElement>>svgE[i].getElementsByTagName(['image', 'img'][j]);
for (let k = 0; k < childImages.length; ++k) {

@@ -60,5 +60,5 @@ if (childImages[k].href.baseVal.substring(0, 5) != 'data:') {

// @import url(CSS_URL);
let styleElements = <HTMLCollectionOf<HTMLStyleElement>>svgE[i].getElementsByTagName('style');
const styleElements = <HTMLCollectionOf<HTMLStyleElement>>svgE[i].getElementsByTagName('style');
for (let j = 0; j < styleElements.length; ++j) {
let regex = /@import\x20url\(\s*(.*?)\s*\);/g;
const regex = /@import\x20url\(\s*(.*?)\s*\);/g;
let m;

@@ -78,13 +78,14 @@ while ((m = regex.exec(styleElements[j].innerHTML)) !== null) {

// creating a promise for each image which needs to be converted to a data URI
let replacementPromises = [];
let createImagePromise = async (uri: string) => {
const replacementPromises = [];
const createImagePromise = async (uri: string) => {
if (uri.length > 0) {
const response = await this._httpClient.loadTexture(uri);
let uInt8Array = new Uint8Array(response.data), i = uInt8Array.length;
let biStr = []; //new Array(i);
const response = await this._httpClient.get(uri, undefined, true) as HttpResponse<ArrayBuffer>;
const uInt8Array = new Uint8Array(response.data as ArrayBuffer);
let i = uInt8Array.length;
const biStr = []; //new Array(i);
while (i--)
biStr[i] = String.fromCharCode(uInt8Array[i]);
let base64Data = window.btoa(biStr.join(''));
let imgDataUrl = 'data:' + response.headers['content-type'] + ';base64,' + base64Data;
const base64Data = window.btoa(biStr.join(''));
const imgDataUrl = 'data:' + response.headers['content-type'] + ';base64,' + base64Data;

@@ -101,12 +102,12 @@ // replace url in SVG string

// now we create promises for the google fonts to be imported
let createStylePromise = async (styleUrl: string) => {
const createStylePromise = async (styleUrl: string) => {
const response = await this._httpClient.get(
styleUrl,
{ responseType: 'text' }
);
let cssString = response.data;
) as HttpResponse<ArrayBuffer>;
let cssString = response.data as unknown as string;
// we assume that fonts are imported using the following syntax:
// url(FONT_URI);
let fontURLs = [];
let regex = /url\(\s*(.*?)\s*\)/g;
const fontURLs = [];
const regex = /url\(\s*(.*?)\s*\)/g;
let m;

@@ -117,15 +118,16 @@ while ((m = regex.exec(cssString)) !== null) {

let fontPromises = [];
let createFontPromise = async (fUrl: string) => {
const fontPromises = [];
const createFontPromise = async (fUrl: string) => {
const response = await this._httpClient.get(
fUrl,
{ responseType: 'arraybuffer' }
);
let uInt8Array = new Uint8Array(response.data), i = uInt8Array.length;
let biStr = []; //new Array(i);
) as HttpResponse<ArrayBuffer>;
const uInt8Array = new Uint8Array(response.data as ArrayBuffer);
let i = uInt8Array.length;
const biStr = []; //new Array(i);
while (i--)
biStr[i] = String.fromCharCode(uInt8Array[i]);
let base64Data = window.btoa(biStr.join(''));
let fontDataUrl = 'data:' + response.headers['content-type'] + ';base64,' + base64Data;
const base64Data = window.btoa(biStr.join(''));
const fontDataUrl = 'data:' + response.headers['content-type'] + ';base64,' + base64Data;
if (fUrl.length > 0)

@@ -147,4 +149,4 @@ cssString = cssString.replace(fUrl, fontDataUrl);

let du = 'data:image/svg+xml,' + encodeURIComponent(data);
let img = new Image(); // same as document.createElement('img')
const du = 'data:image/svg+xml,' + encodeURIComponent(data);
const img = new Image(); // same as document.createElement('img')
img.crossOrigin = 'Anonymous';

@@ -154,3 +156,3 @@ const promise = new Promise<void>((resolve, reject) => {

img.onerror = reject;
})
});
img.src = du;

@@ -161,3 +163,6 @@ await promise;

public async responseToImage(response: HttpResponse<ArrayBuffer>): Promise<HTMLImageElement> {
public async responseToImage(response: HttpResponse<ArrayBuffer | HTMLImageElement>): Promise<HTMLImageElement> {
// if we already receive and image, this conversion already happened
if(response.data instanceof HTMLImageElement) return response.data;
const arrayBufferView = new Uint8Array( response.data );

@@ -173,4 +178,4 @@ const blob = new Blob([ arrayBufferView ], { type: response.headers['content-type'] } );

img.onerror = reject;
})
img.crossOrigin = "anonymous";
});
img.crossOrigin = 'anonymous';
img.src = URL.createObjectURL(blob);

@@ -183,3 +188,3 @@ await promise;

public toAlpha(color: any): number {
public toAlpha(color: unknown): number {
const c = this.toHexColor(color);

@@ -190,7 +195,7 @@ if (c.length <= 8) return 1;

public toColorArray(color: any): number[] {
if(typeof color !== 'string' || !color.startsWith("#"))
public toColorArray(color: unknown): number[] {
if(typeof color !== 'string' || !color.startsWith('#'))
color = this.toHexColor(color);
const tColor = new TinyColor(color);
const rgb = tColor.toRgb()
const tColor = new TinyColor(color as ColorInput | undefined);
const rgb = tColor.toRgb();
return [rgb.r / 255.0, rgb.g / 255.0, rgb.b / 255.0];

@@ -203,3 +208,3 @@ }

*/
public toHex8Color(color: any, defColorString: string = '#000'): string {
public toHex8Color(color: unknown, defColorString: string = '#000'): string {
const c = this.toHexColor(color, defColorString);

@@ -218,9 +223,9 @@ const tColor = new TinyColor(c);

*/
public toHexColor(color: any, defColorString: string = '#000'): string {
public toHexColor(color: unknown, defColorString: string = '#000'): string {
if (!color || color === 'default') return defColorString;
if (color.constructor === Float32Array)
color = Array.from(color);
if ((color as Float32Array).constructor === Float32Array)
color = Array.from(color as Float32Array);
const tColor = new TinyColor(color);
const tColor = new TinyColor(color as TinyColor | undefined);

@@ -233,7 +238,7 @@ if (color instanceof TinyColor)

let cs = color.toString(16);
let cl = cs.length;
const cl = cs.length;
if (cl < 3) cs = cs.padStart(3, '0');
else if (cl < 6) cs = cs.padStart(6, '0');
else if (cl < 8) cs = cs.padEnd(8, '0');
let tc = new TinyColor(cs);
const tc = new TinyColor(cs);
return tc.isValid ? this.tinyColorToString(tc) : defColorString;

@@ -243,4 +248,4 @@ }

// check if the input is a THREE.Color
if (color.isColor && typeof color.getHexString == 'function') {
let tc = new TinyColor(color.getHexString());
if ((color as THREE.Color).isColor && typeof (color as THREE.Color).getHexString == 'function') {
const tc = new TinyColor((color as THREE.Color).getHexString());
return tc.isValid ? this.tinyColorToString(tc) : defColorString;

@@ -261,3 +266,3 @@ }

let tc = new TinyColor({
const tc = new TinyColor({
r: Math.max(0, Math.min(color[0], 255)),

@@ -268,3 +273,3 @@ g: Math.max(0, Math.min(color[1], 255)),

if (color.length == 4) {
let a = parseFloat(color[3]);
const a = parseFloat(color[3]);
if (!isNaN(a)) {

@@ -280,3 +285,3 @@ tc.setAlpha(Math.max(0, Math.min(a, 255)) / 255);

if (typeof color !== 'string') {
let tc = new TinyColor(color);
const tc = new TinyColor(color as string);
return tc.isValid ? this.tinyColorToString(tc) : defColorString;

@@ -286,7 +291,7 @@ }

// tinycolor doesn't like 0x
let tmpColor = color.replace('0x', '#');
const tmpColor = color.replace('0x', '#');
// if we got no alpha value, add full opacity
if (tmpColor.match(/^#[a-f0-9]{6}$/i) !== null) {
let tc = new TinyColor(tmpColor + 'ff');
const tc = new TinyColor(tmpColor + 'ff');
return tc.isValid ? this.tinyColorToString(tc) : defColorString;

@@ -297,3 +302,3 @@ }

if (tmpColor.match(/^#[a-f0-9]{8}$/i) !== null) {
let tc = new TinyColor(tmpColor);
const tc = new TinyColor(tmpColor);
return tc.isValid ? this.tinyColorToString(tc) : defColorString;

@@ -304,3 +309,3 @@ }

if (tmpColor.match(/^#[a-f0-9]{7}$/i) !== null) {
let tc = new TinyColor(tmpColor.slice(0, 7) + '0' + tmpColor.slice(-1));
const tc = new TinyColor(tmpColor.slice(0, 7) + '0' + tmpColor.slice(-1));
return tc.isValid ? this.tinyColorToString(tc) : defColorString;

@@ -310,7 +315,7 @@ }

// check if tinycolor understands the string
let tc = new TinyColor(tmpColor);
const tc = new TinyColor(tmpColor);
return tc.isValid ? this.tinyColorToString(tc) : defColorString;
}
public toThreeJsColorInput(color: any): string {
public toThreeJsColorInput(color: unknown): string {
const c = this.toHexColor(color);

@@ -320,11 +325,13 @@ return c.slice(0, c.length - 2);

public toVec3(point: any): vec3 {
public toVec3(point: vec3 | { x: number, y: number, z: number} | { X: number, Y: number, Z: number}): vec3 {
if (Array.isArray(point) && point.length >= 3 && typeof point[0] === 'number' && typeof point[1] === 'number' && typeof point[2] === 'number')
return vec3.fromValues(point[0], point[1], point[2]);
if (((point.x || point.x === 0) && typeof point.x === 'number') && ((point.y || point.y === 0) && typeof point.y === 'number') && ((point.z || point.z === 0) && typeof point.z === 'number'))
return vec3.fromValues(point.x, point.y, point.z);
const pointCast1 = point as { x: number, y: number, z: number};
if (((pointCast1.x || pointCast1.x === 0) && typeof pointCast1.x === 'number') && ((pointCast1.y || pointCast1.y === 0) && typeof pointCast1.y === 'number') && ((pointCast1.z || pointCast1.z === 0) && typeof pointCast1.z === 'number'))
return vec3.fromValues(pointCast1.x, pointCast1.y, pointCast1.z);
if (((point.X || point.X === 0) && typeof point.X === 'number') && ((point.Y || point.Y === 0) && typeof point.Y === 'number') && ((point.Z || point.Z === 0) && typeof point.Z === 'number'))
return vec3.fromValues(point.X, point.Y, point.Z);
const pointCast2 = point as { X: number, Y: number, Z: number};
if (((pointCast2.X || pointCast2.X === 0) && typeof pointCast2.X === 'number') && ((pointCast2.Y || pointCast2.Y === 0) && typeof pointCast2.Y === 'number') && ((pointCast2.Z || pointCast2.Z === 0) && typeof pointCast2.Z === 'number'))
return vec3.fromValues(pointCast2.X, pointCast2.Y, pointCast2.Z);

@@ -331,0 +338,0 @@ return vec3.create();

@@ -1,11 +0,22 @@

import axios, { AxiosRequestConfig } from 'axios'
import { ShapeDiverError as ShapeDiverBackendError, isGBResponseError, isGBRequestError, isGBError } from '@shapediver/sdk.geometry-api-sdk-v2'
import axios, { AxiosRequestConfig } from 'axios';
import { ShapeDiverError as ShapeDiverBackendError, isGBResponseError, isGBRequestError, isGBError } from '@shapediver/sdk.geometry-api-sdk-v2';
import { ShapeDiverGeometryBackendError, ShapeDiverGeometryBackendRequestError, ShapeDiverGeometryBackendResponseError } from '../logger/ShapeDiverBackendErrors';
import { HttpResponse } from './HttpResponse';
import { Converter } from '../converter/Converter';
export class HttpClient {
// #region Properties (2)
// #region Properties (7)
private static _instance: HttpClient;
private _dataCache: Map<
string,
{
value: Promise<HttpResponse<unknown>>,
timestamp: number,
resolved: boolean,
size?: number
}> = new Map();
private _enableCaching: boolean = true;
private _excludedQueryParameters: string[] = ['Expires', 'Signature', 'Key-Pair-Id'];
private _maxCacheSize: number = 1024 * 1024 * 32;
private _sessionLoading: {

@@ -18,6 +29,7 @@ [key: string]: {

// #endregion Properties (2)
// #endregion Properties (7)
// #region Constructors (1)
// eslint-disable-next-line @typescript-eslint/no-empty-function
private constructor() { }

@@ -35,4 +47,40 @@

// #region Public Accessors (6)
public get enableCaching(): boolean {
return this._enableCaching;
}
public set enableCaching(value: boolean) {
this._enableCaching = value;
if (this._enableCaching === false)
this._dataCache.clear();
}
public get excludedQueryParameters(): string[] {
return this._excludedQueryParameters;
}
public set excludedQueryParameters(value: string[]) {
this._excludedQueryParameters = value;
}
public get maxCacheSize(): number {
return this._maxCacheSize;
}
public set maxCacheSize(value: number) {
this._maxCacheSize = value;
}
// #endregion Public Accessors (6)
// #region Public Methods (5)
/**
* Add the data loading options from a session.
*
* @param sessionId
* @param callbacks
*/
public addDataLoading(sessionId: string, callbacks: {

@@ -58,9 +106,26 @@ getAsset: (url: string) => Promise<[ArrayBuffer, string, string]>,

} else if (isGBRequestError(e)) {
throw new ShapeDiverGeometryBackendRequestError(e.message, e.desc)
} else if(isGBError(e)) {
throw new ShapeDiverGeometryBackendError(e.message)
throw new ShapeDiverGeometryBackendRequestError(e.message, e.desc);
} else if (isGBError(e)) {
throw new ShapeDiverGeometryBackendError(e.message);
}
}
public async get(href: string, config: AxiosRequestConfig = { responseType: 'arraybuffer' }, textureLoading: boolean = false): Promise<HttpResponse<any>> {
/**
* Get the requested resource either as a download or from the cache.
* If available, the registered session loading is used for download.
* Textures are downloaded via a specific endpoint and can be converted in this step as well.
* Depending on the provided caching options, the requested resource might already be cached.
*
* @param href
* @param config
* @param textureLoading
* @param textureConversion
* @returns
*/
public async get(href: string, config: AxiosRequestConfig = { responseType: 'arraybuffer' }, textureLoading: boolean = false, textureConversion: boolean = false): Promise<HttpResponse<unknown>> {
const dataKey = this.hrefToDataKey(href);
// return element if it exists in cache
if (this._dataCache.has(dataKey)) return this.getFromCache(dataKey);
// try to get sessionId from href

@@ -81,2 +146,4 @@ let sessionId = this.getSessionId(href);

let loadingPromise;
// separation texture vs everything else

@@ -87,17 +154,46 @@ if (textureLoading) {

// take first session to load a texture that is not session related
return new Promise<HttpResponse<any>>((resolve, reject) => {
sessionLoading!.downloadTexture(sessionId!, href).then((result) => {
resolve({
data: result[0],
headers: {
'content-type': result[1]
}
})
}).catch(e => reject(e))
}).catch(e => { throw this.convertError(e) });
loadingPromise = new Promise<HttpResponse<ArrayBuffer | HTMLImageElement>>((resolve, reject) => {
sessionLoading!.downloadTexture(sessionId!, href).then(async (result) => {
if (textureConversion) {
const image = await Converter.instance.responseToImage({
data: result[0],
headers: {
'content-type': result[1]
}
});
resolve({
data: image,
size: result[0].byteLength,
headers: {
'content-type': result[1]
}
});
} else {
resolve({
data: result[0],
headers: {
'content-type': result[1]
}
});
}
}).catch(e => reject(e));
}).catch(e => { throw this.convertError(e); });
} else {
// we can load blobs and data urls directly
// or load it directly if we don't have a session
return axios(href, Object.assign({ method: 'get' }, config))
.catch(e => { throw this.convertError(e) });
loadingPromise = axios(href, Object.assign({ method: 'get' }, config))
.then(async (result) => {
if (textureConversion) {
const image = await Converter.instance.responseToImage(result);
return {
data: image,
size: result.data.byteLength,
headers: result.headers
};
} else {
return result;
}
})
.catch(e => { throw this.convertError(e); });
}

@@ -107,7 +203,7 @@ } else {

// if there is no session to load from, we use the fallback option
return axios(href, Object.assign({ method: 'get' }, config))
.catch(e => { throw this.convertError(e) });
loadingPromise = axios(href, Object.assign({ method: 'get' }, config))
.catch(e => { throw this.convertError(e); });
} else {
// all data links where we could somehow find a session to load it with
return new Promise<HttpResponse<ArrayBuffer>>((resolve, reject) => {
loadingPromise = new Promise<HttpResponse<ArrayBuffer>>((resolve, reject) => {
sessionLoading!.getAsset(href)

@@ -120,3 +216,3 @@ .then((result) => {

}
})
});
})

@@ -126,14 +222,30 @@ .catch(() => {

const axiosPromise = axios(href, Object.assign({ method: 'get' }, config));
axiosPromise.catch(e => reject(e))
axiosPromise.catch(e => reject(e));
resolve(axiosPromise);
});
}).catch(e => { throw this.convertError(e) });
}).catch(e => { throw this.convertError(e); });
}
}
if (this.enableCaching)
this.addToCache(dataKey, loadingPromise);
return loadingPromise;
}
public async loadTexture(href: string): Promise<HttpResponse<ArrayBuffer>> {
return this.get(href, undefined, true);
/**
* Get the requested texture either as a download or from the cache.
*
* @param href
* @returns
*/
public async loadTexture(href: string): Promise<HttpResponse<HTMLImageElement>> {
return this.get(href, undefined, true, true) as Promise<HttpResponse<HTMLImageElement>>;
}
/**
* Add the data loading options from a session.
*
* @param sessionId
*/
public removeDataLoading(sessionId: string) {

@@ -145,4 +257,61 @@ delete this._sessionLoading[sessionId];

// #region Private Methods (1)
// #region Private Methods (5)
/**
* Add
*
* @param key
* @param value
*/
private addToCache(key: string, value: Promise<HttpResponse<unknown>>) {
// Remove items from the cache until the cache size is smaller than the maximum cache size.
// Only resolved promises are evaluated, as unresolved promises don't add any size.
while (this.calculateCacheSize() >= this._maxCacheSize) {
// Remove the oldest entry if the cache is full
const oldestKey = this._dataCache.keys().next().value;
this._dataCache.delete(oldestKey);
}
const timestamp = Date.now();
this._dataCache.set(key, { value, timestamp, resolved: false });
// once the promise resolves, set resolved and size properties
value.then((promiseResult) => {
const size = promiseResult.size ? promiseResult.size : (promiseResult.data as ArrayBuffer).byteLength;
this._dataCache.set(key, { value, timestamp, resolved: true, size });
}).catch(e => { throw this.convertError(e); });
}
/**
* Calculate the current cache size from all resolved promises.
*
* @returns
*/
private calculateCacheSize() {
let size = 0;
this._dataCache.forEach(value => {
if (value.resolved === true)
size += value.size!;
});
return size;
}
/**
* Get the value of an object from the cache.
*
* @param key
* @returns
*/
private getFromCache(key: string): Promise<HttpResponse<unknown>> {
const cachedObject = this._dataCache.get(key)!;
this._dataCache.set(key, { value: cachedObject.value, timestamp: Date.now(), resolved: cachedObject.resolved, size: cachedObject.size });
return cachedObject.value;
}
/**
* Get the session id of the provided href.
*
* @param href
* @returns
*/
private getSessionId(href: string): string | undefined {

@@ -163,3 +332,27 @@ // searching for "/session/SESSION_ID/{'output' | 'export' | 'texture'}/ASSET_DATA"

// #endregion Private Methods (1)
/**
* Convert the provided href to a data cache key.
* In this conversion the excludedQueryParameters are removed from the href.
*
* @param href
* @returns
*/
private hrefToDataKey(href: string) {
const url = new URL(href);
// Create a URLSearchParams object from the existing query parameters
const params = new URLSearchParams(url.search);
for (let i = 0; i < this._excludedQueryParameters.length; i++)
// Remove specific query parameters
params.delete(this._excludedQueryParameters[i]);
// Reconstruct the URL with the modified query parameters
url.search = params.toString();
const hrefAsKey = url.toString();
return window.btoa(hrefAsKey);
}
// #endregion Private Methods (5)
}

@@ -0,4 +1,6 @@

/* eslint-disable @typescript-eslint/no-explicit-any */
export interface HttpResponse<T = any> {
data: T;
headers: any
headers: any,
size?: number
}

@@ -11,2 +11,3 @@ export class PerformanceEvaluator {

start: number;
continued?: number;
end?: number;

@@ -30,5 +31,19 @@ duration?: number;

// #region Public Methods (6)
// #region Public Methods (8)
/**
* Continue the performance evaluation.
*
* @param id
*/
public continueSection(sectionId: string): void {
if (!this._eval) return;
if (this._eval.end) return;
if (!this._eval.section[sectionId]) return;
if (this._eval.section[sectionId].end) return;
this._eval.section[sectionId].continued = performance.now();
}
/**
* End the performance evaluation and calculate the duration.

@@ -59,3 +74,3 @@ *

this._eval.section[sectionId].duration = this._eval.section[sectionId].end! - this._eval.section[sectionId].start;
this._eval.section[sectionId].duration = (this._eval.section[sectionId].duration || 0) + (this._eval.section[sectionId].end! - (this._eval.section[sectionId].continued || this._eval.section[sectionId].start));
}

@@ -73,2 +88,3 @@

start: number,
continued?: number,
end?: number,

@@ -95,2 +111,16 @@ duration?: number

/**
* Pause the performance evaluation.
*
* @param id
*/
public pauseSection(sectionId: string): void {
if (!this._eval) return;
if (this._eval.end) return;
if (!this._eval.section[sectionId]) return;
if (this._eval.section[sectionId].end) return;
this._eval.section[sectionId].duration = (this._eval.section[sectionId].duration || 0) + performance.now() - (this._eval.section[sectionId].continued || this._eval.section[sectionId].start);
}
/**
* Start the evaluation with a specific id.

@@ -120,3 +150,3 @@ *

// #endregion Public Methods (6)
// #endregion Public Methods (8)
}

@@ -100,3 +100,3 @@ import { convert, validate, Defaults, ISettings, versions, latestVersion } from '@shapediver/viewer.settings';

const prevVersions = ['1.0', '2.0', '3.0', '3.1', '3.2', '3.3', '3.4'];
const prevVersions = ['1.0', '2.0', '3.0', '3.1', '3.2', '3.3', '3.4', '4.0'];
for(let i = 0; i < prevVersions.length; i++) {

@@ -103,0 +103,0 @@ const v = prevVersions[i];

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc