scichart
Version:
Fast WebGL JavaScript Charting Library and Framework
884 lines • 77.3 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.licenseManager = exports.getLicenseInfo = exports.applyLicense = exports.getLicenseCookie = exports.setUseLicenseWizard = exports.setRuntimeLicenseKey = exports.setLicenseCallback = exports.getLicenseLog = exports.debug = exports.logInfo = exports.setIsDebugLicensing = exports.setDependencies = void 0;
var app_1 = require("../../constants/app");
var BuildStamp_1 = require("../../Core/BuildStamp");
var Dictionary_1 = require("../../Core/Dictionary");
var Globals_1 = require("../../Core/Globals");
var localStorageApi_1 = require("../../Core/storage/localStorageApi");
var Telemetry_1 = require("../../Core/Telemetry");
var Color_1 = require("../../types/Color");
var licensingClasses_1 = require("../../types/licensingClasses");
var SurfaceType_1 = require("../../types/SurfaceType");
var cookie_1 = require("../../utils/cookie");
var licenseManager2dState_1 = require("./licenseManager2dState");
var licenseWizardPort = 24278;
var licenseWizardAlternatePort = 24279;
var portOverride = localStorageApi_1.localStorageApi.getLicenseWizardPort();
if (portOverride) {
licenseWizardPort = portOverride;
licenseWizardAlternatePort = licenseWizardPort + 1;
}
var fetchFromWizard = function (path) { return __awaiter(void 0, void 0, void 0, function () {
var wizardUrl, response, err_1, maxport, wizardUrl, response, err_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 9]);
wizardUrl = "http://localhost:" + licenseWizardPort.toString() + path;
return [4 /*yield*/, fetch(wizardUrl)];
case 1:
response = _a.sent();
return [2 /*return*/, response];
case 2:
err_1 = _a.sent();
(0, exports.debug)("Could not connect to license wizard on port " + licenseWizardPort.toString());
if (!(typeof localStorage !== "undefined")) return [3 /*break*/, 8];
maxport = localStorageApi_1.localStorageApi.getLicenseWizardMaxPort();
if (!maxport) return [3 /*break*/, 8];
_a.label = 3;
case 3:
if (!(licenseWizardAlternatePort <= maxport)) return [3 /*break*/, 8];
_a.label = 4;
case 4:
_a.trys.push([4, 6, , 7]);
wizardUrl = "http://localhost:" + licenseWizardAlternatePort.toString() + path;
return [4 /*yield*/, fetch(wizardUrl)];
case 5:
response = _a.sent();
licenseWizardPort = licenseWizardAlternatePort;
return [2 /*return*/, response];
case 6:
err_2 = _a.sent();
(0, exports.debug)("Could not connect to license wizard on port " + licenseWizardAlternatePort.toString());
licenseWizardAlternatePort = licenseWizardAlternatePort + 1;
return [3 /*break*/, 7];
case 7: return [3 /*break*/, 3];
case 8: throw err_1;
case 9: return [2 /*return*/];
}
});
}); };
var licenseDependencies = {
fetchFromWizard: function (url) { return fetchFromWizard(url); },
setCookie: function (name, val, validDays) { return (0, cookie_1.setCookie)(name, val, validDays); },
getCookie: function (name) { return (0, cookie_1.getCookie)(name); },
fetchForChallenge: function (url) { return fetch(url); },
getInitialToken: function () {
var _a;
if (typeof document === "undefined")
return null;
var meta = document.querySelector('meta[name="x-scichart-license"]');
return (_a = meta === null || meta === void 0 ? void 0 : meta.content) !== null && _a !== void 0 ? _a : null;
},
generateSimpleToken: function (orderId) { return null; }
};
var setDependencies = function (dependencies) { return (licenseDependencies = dependencies); };
exports.setDependencies = setDependencies;
var isDebug = null;
var setIsDebugLicensing = function (value, persist) {
if (persist === void 0) { persist = false; }
isDebug = value;
if (persist || !value) {
localStorageApi_1.localStorageApi.setIsLicenseDebug(value);
}
};
exports.setIsDebugLicensing = setIsDebugLicensing;
var infoLog = [];
var debugLog = [];
var MAX_INFO_LOG_ENTRIES = 50;
var MAX_DEBUG_LOG_ENTRIES = 200;
var LS_LICENSE_LOG_KEY = 'scichartLicenseLog';
var logLevel = 'debug';
var outputMode = 'none';
var defaultEmitLog = function (entry) {
var _a;
if (outputMode === 'console' || isDebug) {
console.log(entry.message);
}
if (outputMode === 'localStorage' && typeof localStorage !== 'undefined') {
var t = new Date(entry.timestamp).toISOString().substring(11, 23);
var line = "[".concat(entry.level === 'info' ? 'INFO ' : 'DEBUG', "] ").concat(t, " ").concat(entry.message, "\n");
try {
localStorage.setItem(LS_LICENSE_LOG_KEY, ((_a = localStorage.getItem(LS_LICENSE_LOG_KEY)) !== null && _a !== void 0 ? _a : '') + line);
}
catch (_) { /* storage full */ }
}
};
var emitLogFn = defaultEmitLog;
/** @internal exported for testing */
var logInfo = function (message) {
if (infoLog.length >= MAX_INFO_LOG_ENTRIES)
infoLog.shift();
var entry = { timestamp: Date.now(), level: 'info', message: message };
infoLog.push(entry);
if (logLevel === 'info' || logLevel === 'debug') {
emitLogFn(entry);
}
};
exports.logInfo = logInfo;
/** @internal exported for testing */
var debug = function (message) {
if (isDebug === null) {
isDebug = localStorageApi_1.localStorageApi.getIsLicenseDebug();
}
if (app_1.IS_TEST_ENV || isDebug) {
var entry = { timestamp: Date.now(), level: 'debug', message: message };
if (debugLog.length >= MAX_DEBUG_LOG_ENTRIES)
debugLog.shift();
debugLog.push(entry);
if (logLevel === 'debug') {
emitLogFn(entry);
}
}
};
exports.debug = debug;
var getLicenseLog = function () {
return __spreadArray(__spreadArray([], infoLog, true), debugLog, true).sort(function (a, b) { return a.timestamp - b.timestamp; });
};
exports.getLicenseLog = getLicenseLog;
var formatLicenseLog = function () {
return (0, exports.getLicenseLog)()
.map(function (e) {
var t = new Date(e.timestamp).toISOString().substring(11, 23);
return "[".concat(e.level === 'info' ? 'INFO ' : 'DEBUG', "] ").concat(t, " ").concat(e.message);
})
.join('\n');
};
var clearLogs = function () {
infoLog.length = 0;
debugLog.length = 0;
};
(0, exports.logInfo)("SciChart version " + BuildStamp_1.libraryVersion);
// tslint:disable: no-console
var licenseCallback;
var setLicenseCallback = function (callback) {
licenseCallback = callback;
};
exports.setLicenseCallback = setLicenseCallback;
// Cheap non-cryptographic hash for debug diagnostics — lets a customer compare
// the fingerprint of the key they pasted against a known-good fingerprint
// without having to share the full key. FNV-1a 32-bit; 8 hex chars.
var hashLicenseKey = function (key) {
var h = 0x811c9dc5;
for (var i = 0; i < key.length; i++) {
h ^= key.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return (h >>> 0).toString(16).padStart(8, "0");
};
// Validation-state helpers — pick developer-licence vs runtime-key statuses based
// on whether we're talking to the local licensing wizard or a remote server.
var validatingStatus = function () {
return licenseManager2dState_1.licenseManager2dState.isDev
? licensingClasses_1.LicenseCheckStatus.ValidatingDeveloperLicense
: licensingClasses_1.LicenseCheckStatus.ValidatingRuntimeKey;
};
var failedValidateStatus = function () {
return licenseManager2dState_1.licenseManager2dState.isDev
? licensingClasses_1.LicenseCheckStatus.FailedToValidateDeveloperLicense
: licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey;
};
var isValidating = function (s) {
return s === licensingClasses_1.LicenseCheckStatus.ValidatingDeveloperLicense ||
s === licensingClasses_1.LicenseCheckStatus.ValidatingRuntimeKey;
};
var runtimeLicenseKey = "";
var getRuntimeLicenseKey = function () { return runtimeLicenseKey; };
var setRuntimeLicenseKey = function (value) {
var prev = runtimeLicenseKey;
runtimeLicenseKey = value;
if (runtimeLicenseKey !== prev && runtimeLicenseKey !== "") {
getAllLicenseContexts().forEach(function (lc) { return (0, exports.applyLicense)(lc, "setRuntimeLicenseKey"); });
}
};
exports.setRuntimeLicenseKey = setRuntimeLicenseKey;
var useLicenseWizard = true;
var setUseLicenseWizard = function (value) {
useLicenseWizard = value;
};
exports.setUseLicenseWizard = setUseLicenseWizard;
var retryTime = app_1.IS_TEST_ENV ? 0.1 : 5;
var maxretries = app_1.IS_TEST_ENV ? 12 : 10;
var serverLicenseEndpoint = "api/license";
var getServerLicenseEndpoint = function () { return serverLicenseEndpoint; };
var setServerLicenseEndpoint = function (value) {
serverLicenseEndpoint = value;
};
var getLicenseFailCounts = 0;
var wizardTimer;
var licenseChallengeTimeout;
var getlicenseFromWizard = function (licenseContext) { return __awaiter(void 0, void 0, void 0, function () {
var response, keyCode, _a, requiresValidation, trialExpired, err_3, licenseInfo;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_b.trys.push([0, 5, , 6]);
if (checkStatus !== licensingClasses_1.LicenseCheckStatus.StartLookingForLicenseWizard &&
checkStatus !== licensingClasses_1.LicenseCheckStatus.LookingForLicenseWizard &&
checkStatus !== licensingClasses_1.LicenseCheckStatus.NoLicenseInWizard)
return [2 /*return*/];
(0, exports.debug)("Trying to get license from local license wizard");
response = void 0;
return [4 /*yield*/, licenseDependencies.fetchFromWizard("/license")];
case 1:
response = _b.sent();
if (!response.ok) return [3 /*break*/, 3];
return [4 /*yield*/, response.text()];
case 2:
keyCode = _b.sent();
_a = setNewLicense(keyCode, licenseContext), requiresValidation = _a.requiresValidation, trialExpired = _a.trialExpired;
if (requiresValidation) {
(0, exports.logInfo)("Got a developer license from local license wizard. Validating...");
checkStatus = licensingClasses_1.LicenseCheckStatus.ValidatingDeveloperLicense;
dolicenseChallenge(licenseContext);
}
else if (trialExpired) {
checkStatus = licensingClasses_1.LicenseCheckStatus.NoLicenseInWizard;
(0, exports.debug)("No valid license available in licensing wizard. Trying again in ".concat(retryTime, " seconds"));
wizardTimer = setTimeout(function () { return getlicenseFromWizard(licenseContext); }, retryTime * 1000);
}
else {
(0, exports.logInfo)("Got a valid license from local license wizard.");
checkStatus = licensingClasses_1.LicenseCheckStatus.LicenseOK;
}
return [3 /*break*/, 4];
case 3:
checkStatus = licensingClasses_1.LicenseCheckStatus.NoLicenseInWizard;
(0, exports.debug)("No license available in licensing wizard. Trying again in ".concat(retryTime, " seconds"));
wizardTimer = setTimeout(function () { return getlicenseFromWizard(licenseContext); }, retryTime * 1000);
_b.label = 4;
case 4: return [3 /*break*/, 6];
case 5:
err_3 = _b.sent();
checkStatus = licensingClasses_1.LicenseCheckStatus.LookingForLicenseWizard;
// Failed to connect. Retry
getLicenseFailCounts += 1;
if (getLicenseFailCounts < maxretries) {
(0, exports.debug)("Could not find licensing wizard. Trying again in ".concat(retryTime, " seconds"));
wizardTimer = setTimeout(function () { return getlicenseFromWizard(licenseContext); }, retryTime * 1000);
}
else {
// give up.
console.log("Failed to connect to licensing wizard. Refresh page to retry.");
getLicenseFailCounts = 0;
checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToFindLicenseWizard;
}
return [3 /*break*/, 6];
case 6:
licenseInfo = (0, exports.getLicenseInfo)(licenseContext);
if (licenseInfo.hasChanged) {
getAllSurfaces().forEach(function (sciChartSurface) {
updateLicenseDisplayInternal(licenseInfo, sciChartSurface, sciChartSurface.surfaceType !== SurfaceType_1.ESurfaceType.SciChart3DSurfaceType);
});
}
return [2 /*return*/];
}
});
}); };
var setLicenseCookie = function (key, token, expirySeconds, lastValidated) {
var cookieVal = "".concat(key, ",").concat(token, ",").concat(expirySeconds, ",").concat(lastValidated);
return licenseDependencies.setCookie("scLicense", cookieVal, 365);
};
var getLicenseCookie = function () {
var cookie;
cookie = licenseDependencies.getCookie("scLicense");
var parts = cookie.split(",");
if (parts.length === 4)
/// TODO worry about UTC here
return {
key: parts[0],
token: parts[1],
expiry: new Date(Number.parseInt(parts[2], 10) * 1000),
lastValidated: new Date(Number.parseInt(parts[3], 10) * 1000)
};
else
return { key: parts[0], token: null, expiry: null, lastValidated: null };
};
exports.getLicenseCookie = getLicenseCookie;
var getAllLicenseContexts = function () {
var lcs = [];
if (Globals_1.sciChartDestinations.length > 0) {
lcs.push(Globals_1.sciChartDestinations[0].sciChartSurface.getLicenseContext());
}
if (Globals_1.sciChart3DDestinations.length > 0) {
lcs.push(Globals_1.sciChart3DDestinations[0].sciChartSurface.getLicenseContext());
}
Globals_1.sciChartSingleDestinations.forEach(function (d) { return lcs.push(d.sciChartSurface.getLicenseContext()); });
Globals_1.sciChart3DSingleDestinations.forEach(function (d) { return lcs.push(d.sciChartSurface.getLicenseContext()); });
return lcs;
};
var getAllSurfaces = function () {
var surfaces = [];
Globals_1.sciChartDestinations.forEach(function (d) { return surfaces.push(d.sciChartSurface); });
Globals_1.sciChart3DDestinations.forEach(function (d) { return surfaces.push(d.sciChartSurface); });
Globals_1.sciChartSingleDestinations.forEach(function (d) { return surfaces.push(d.sciChartSurface); });
Globals_1.sciChart3DSingleDestinations.forEach(function (d) { return surfaces.push(d.sciChartSurface); });
return surfaces;
};
var setChallengeResponse = function (token, licenseContext) {
var expirySeconds = -1;
expirySeconds = licenseContext.SCRTCredentials.ApplyLicenseResponse(token);
getAllLicenseContexts().forEach(function (lc) { return lc.SCRTCredentials.ApplyLicenseResponse(token); });
return expirySeconds;
};
var SIMPLE_RESPONSE_ERRORS = (_a = {},
_a[-1] = "No client secret configured",
_a[-2] = "Client secret missing ; separator",
_a[-3] = "Pubkey in client secret is not valid 32-byte hex",
_a[-4] = "Token does not match expected v2 field count",
_a[-5] = "HMAC field is not exactly 64 hex chars",
_a[-6] = "Server time field is not a valid integer",
_a[-7] = "Token has expired",
_a[-8] = "HMAC field contains non-hex characters",
_a[-9] = "HMAC does not match — wrong signing key",
_a[-11] = "Token has wrong field count, or licence requires round-trip (validate_nonce=1) and an inline token was received",
_a[-12] = "Client-nonce in token does not match the nonce sent (round-trip mode)",
_a[-13] = "Nonce reuse — token already seen this session",
_a[-14] = "Server time has not progressed monotonically since last validation",
_a[-15] = "Licence feature string malformed or out of range",
_a[-16] = "Server / client clock skew exceeds licence-declared max_skew",
_a);
var setSimpleChallengeResponse = function (token, licenseContext) {
var _a;
(0, exports.debug)("setSimpleChallengeResponse ".concat(token));
var expirySeconds = licenseContext.SCRTCredentials.ApplySimpleResponse(token);
getAllLicenseContexts().forEach(function (lc) { return lc.SCRTCredentials.ApplySimpleResponse(token); });
if (expirySeconds < 0) {
(0, exports.debug)("setSimpleChallengeResponse failed (".concat(expirySeconds, "): ").concat((_a = SIMPLE_RESPONSE_ERRORS[expirySeconds]) !== null && _a !== void 0 ? _a : "Unknown error"));
}
return expirySeconds;
};
var challengeFailCounts = 0;
var dolicenseChallenge = function (licenseContext) { return __awaiter(void 0, void 0, void 0, function () {
var lcs, server, challenge, orderId, response, queryString, url, url, token, expirySeconds, key, timeNow, timeToExpiry, err_4, licenseInfo_1, expiry, msg, licenseInfo;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
lcs = getAllLicenseContexts();
if (licenseContext === undefined) {
if (lcs.length > 0) {
licenseContext = lcs[0];
}
else {
return [2 /*return*/];
}
}
server = licenseManager2dState_1.licenseManager2dState.isDev ? "license wizard" : "server";
_a.label = 1;
case 1:
_a.trys.push([1, 11, , 12]);
if (!isValidating(checkStatus))
return [2 /*return*/];
(0, exports.debug)("Attempting to validate license with ".concat(server));
challenge = licenseContext.SCRTCredentials.GetLicenseChallenge();
orderId = licenseContext.SCRTCredentials.GetOrderId();
response = void 0;
queryString = "orderid=".concat(orderId, "&challenge=").concat(challenge);
if (!licenseManager2dState_1.licenseManager2dState.isDev) return [3 /*break*/, 3];
url = "/validate?".concat(queryString);
return [4 /*yield*/, licenseDependencies.fetchFromWizard(url)];
case 2:
response = _a.sent();
return [3 /*break*/, 7];
case 3:
if (!(typeof licenseCallback !== "undefined")) return [3 /*break*/, 5];
return [4 /*yield*/, licenseCallback(queryString)];
case 4:
response = _a.sent();
return [3 /*break*/, 7];
case 5:
url = "/" + serverLicenseEndpoint + (serverLicenseEndpoint.indexOf("?") > 0 ? "&" : "?") + queryString;
return [4 /*yield*/, licenseDependencies.fetchForChallenge(url)];
case 6:
response = _a.sent();
_a.label = 7;
case 7:
if (!response.ok) return [3 /*break*/, 9];
return [4 /*yield*/, response.text()];
case 8:
token = _a.sent();
if (!token.startsWith("Error")) {
expirySeconds = setChallengeResponse(token, licenseContext);
if (expirySeconds > 0) {
key = (0, exports.getLicenseCookie)().key;
if (!key)
key = getRuntimeLicenseKey();
timeNow = Math.floor(new Date().getTime() / 1000);
setLicenseCookie(key, token, expirySeconds, timeNow);
(0, exports.logInfo)("License validated");
checkStatus = licensingClasses_1.LicenseCheckStatus.LicenseOK;
timeToExpiry = expirySeconds - timeNow;
challengeFailCounts = 0;
licenseChallengeTimeout = setTimeout(function () {
checkStatus = validatingStatus();
// Only refresh chart when we have a valid license
licenseManager2dState_1.licenseManager2dState.checkStatus = checkStatus;
dolicenseChallenge(undefined);
}, Math.floor(timeToExpiry * 0.95 * 1000)); // Allow 5%
}
else {
// Something went wrong with the apply
(0, exports.logInfo)("license challenge response was invalid: ".concat(token, " ").concat(expirySeconds));
checkStatus = failedValidateStatus();
}
}
else {
// Challenge rejected by server
(0, exports.logInfo)("Server rejected the license challenge: " + token);
checkStatus = failedValidateStatus();
}
return [3 /*break*/, 10];
case 9:
// Server error or network failure
if (licenseManager2dState_1.licenseManager2dState.isDev) {
console.warn("Error during license validation: " + response.statusText);
checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToValidateDeveloperLicense;
}
else {
// switch to license wizard
throw new Error(response.statusText);
}
_a.label = 10;
case 10: return [3 /*break*/, 12];
case 11:
err_4 = _a.sent();
// switch to license wizard
if (!licenseManager2dState_1.licenseManager2dState.isDev) {
console.warn("Server license validation failed. Looking for local developer license");
runtimeLicenseKey = "";
checkStatus = licensingClasses_1.LicenseCheckStatus.NoLicense;
licenseContext.SCRTCredentials.ResetRuntimeLicense();
lcs.forEach(function (lc) { return lc.SCRTCredentials.ResetRuntimeLicense(); });
isRuntimeKey = false;
licenseManager2dState_1.licenseManager2dState.isDev = true;
checkStatus = licensingClasses_1.LicenseCheckStatus.StartLookingForLicenseWizard;
licenseInfo_1 = (0, exports.getLicenseInfo)(licenseContext);
if (licenseInfo_1.hasChanged) {
getAllSurfaces().forEach(function (sciChartSurface) {
updateLicenseDisplayInternal(licenseInfo_1, sciChartSurface, sciChartSurface.surfaceType !== SurfaceType_1.ESurfaceType.SciChart3DSurfaceType);
});
}
getlicenseFromWizard(licenseContext);
return [2 /*return*/];
}
// Failed to connect. Retry
challengeFailCounts += 1;
if (challengeFailCounts < maxretries) {
(0, exports.debug)("Could not find ".concat(server, "/").concat(serverLicenseEndpoint, ". Trying again in ").concat(retryTime, " seconds"));
licenseChallengeTimeout = setTimeout(function () { return dolicenseChallenge(licenseContext); }, retryTime * 1000);
}
else {
expiry = (0, exports.getLicenseCookie)().expiry;
msg = licenseManager2dState_1.licenseManager2dState.isDev
? "Please run the license wizard, ensure your license is activated, then refresh page to retry."
: "Please check that the endpoint is configured correctly.";
console.error("Failed to connect to ".concat(server, "/").concat(serverLicenseEndpoint, ". ").concat(msg));
if (expiry) {
console.warn("License must be revalidated before ".concat(expiry.toLocaleString(), "."));
}
challengeFailCounts = 0;
// Only actually show failure message if token has expired
if (new Date() > expiry)
checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToFindLicenseWizard;
}
return [3 /*break*/, 12];
case 12:
licenseInfo = (0, exports.getLicenseInfo)(licenseContext);
if (licenseInfo.hasChanged) {
getAllSurfaces().forEach(function (sciChartSurface) {
updateLicenseDisplayInternal(licenseInfo, sciChartSurface, sciChartSurface.surfaceType !== SurfaceType_1.ESurfaceType.SciChart3DSurfaceType);
});
}
return [2 /*return*/];
}
});
}); };
var doSimpleLicenseChallenge = function (licenseContext) { return __awaiter(void 0, void 0, void 0, function () {
var lcs, orderId, inlineToken, applyValidatedToken, expirySeconds, credentials, queryString, clientNonce, response, url, token, expirySeconds, err_5, expiry, licenseInfo;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
lcs = getAllLicenseContexts();
if (licenseContext === undefined) {
if (lcs.length > 0)
licenseContext = lcs[0];
else
return [2 /*return*/];
}
_b.label = 1;
case 1:
_b.trys.push([1, 10, , 11]);
if (!isValidating(checkStatus))
return [2 /*return*/];
(0, exports.debug)("Attempting simple server license validation");
orderId = licenseContext.SCRTCredentials.GetOrderId();
inlineToken = licenseDependencies.generateSimpleToken(orderId);
applyValidatedToken = function (token, expirySeconds) {
var key = (0, exports.getLicenseCookie)().key;
if (!key)
key = getRuntimeLicenseKey();
var timeNow = Math.floor(new Date().getTime() / 1000);
setLicenseCookie(key, token, expirySeconds, timeNow);
(0, exports.logInfo)("Simple server license validated");
checkStatus = licensingClasses_1.LicenseCheckStatus.LicenseOK;
challengeFailCounts = 0;
var timeToExpiry = expirySeconds - timeNow;
licenseChallengeTimeout = setTimeout(function () {
checkStatus = licensingClasses_1.LicenseCheckStatus.ValidatingRuntimeKey;
licenseManager2dState_1.licenseManager2dState.checkStatus = licensingClasses_1.LicenseCheckStatus.ValidatingRuntimeKey;
doSimpleLicenseChallenge(undefined);
}, Math.floor(timeToExpiry * 0.95 * 1000));
};
if (!(inlineToken !== null)) return [3 /*break*/, 2];
if (!inlineToken.startsWith("Error")) {
expirySeconds = setSimpleChallengeResponse(inlineToken, licenseContext);
if (expirySeconds > 0) {
applyValidatedToken(inlineToken, expirySeconds);
}
else {
(0, exports.logInfo)("Simple license response was invalid: ".concat(inlineToken, " ").concat(expirySeconds));
checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey;
}
}
else {
(0, exports.logInfo)("Simple license token error: " + inlineToken);
checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey;
}
return [3 /*break*/, 9];
case 2:
credentials = licenseContext.SCRTCredentials;
queryString = "orderid=".concat(orderId);
if (((_a = credentials.IsRoundTripValidation) === null || _a === void 0 ? void 0 : _a.call(credentials)) && credentials.GenerateClientNonce) {
clientNonce = credentials.GenerateClientNonce();
queryString += "&nonce=".concat(encodeURIComponent(clientNonce));
(0, exports.debug)("Round-trip mode: included client nonce in request");
}
response = void 0;
if (!(typeof licenseCallback !== "undefined")) return [3 /*break*/, 4];
return [4 /*yield*/, licenseCallback(queryString)];
case 3:
response = _b.sent();
return [3 /*break*/, 6];
case 4:
url = "/" + serverLicenseEndpoint +
(serverLicenseEndpoint.indexOf("?") > 0 ? "&" : "?") + queryString;
return [4 /*yield*/, licenseDependencies.fetchForChallenge(url)];
case 5:
response = _b.sent();
_b.label = 6;
case 6:
if (!response.ok) return [3 /*break*/, 8];
return [4 /*yield*/, response.text()];
case 7:
token = _b.sent();
if (!token.startsWith("Error")) {
expirySeconds = setSimpleChallengeResponse(token, licenseContext);
if (expirySeconds > 0) {
applyValidatedToken(token, expirySeconds);
}
else {
(0, exports.logInfo)("Simple license response was invalid: ".concat(token, " ").concat(expirySeconds));
checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey;
}
}
else {
(0, exports.logInfo)("Server rejected simple license request: " + token);
checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey;
}
return [3 /*break*/, 9];
case 8: throw new Error(response.statusText);
case 9: return [3 /*break*/, 11];
case 10:
err_5 = _b.sent();
challengeFailCounts += 1;
if (challengeFailCounts < maxretries) {
(0, exports.debug)("Could not reach /".concat(serverLicenseEndpoint, ". Retrying in ").concat(retryTime, "s"));
licenseChallengeTimeout = setTimeout(function () { return doSimpleLicenseChallenge(licenseContext); }, retryTime * 1000);
}
else {
expiry = (0, exports.getLicenseCookie)().expiry;
console.error("Failed to connect to /".concat(serverLicenseEndpoint, ". Please check the endpoint is configured correctly."));
if (expiry)
console.warn("License must be revalidated before ".concat(expiry.toLocaleString(), "."));
challengeFailCounts = 0;
if (new Date() > expiry)
checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey;
}
return [3 /*break*/, 11];
case 11:
licenseInfo = (0, exports.getLicenseInfo)(licenseContext);
if (licenseInfo.hasChanged) {
getAllSurfaces().forEach(function (s) {
return updateLicenseDisplayInternal(licenseInfo, s, s.surfaceType !== SurfaceType_1.ESurfaceType.SciChart3DSurfaceType);
});
}
return [2 /*return*/];
}
});
}); };
var checkStatus = licensingClasses_1.LicenseCheckStatus.NoLicense;
var isRuntimeKey = false;
var communityNotice = false;
var applyLicense = function (licenseContext, source) {
var _a, _b;
(0, exports.debug)("applyLicense from " + source);
var licenseKey = "";
var lt = licenseContext.SCRTCredentials.GetLicenseType();
(0, exports.logInfo)("Initial license status is " + licensingClasses_1.LicenseType[convertLicenseType(lt, licenseContext)]);
// Get from global store
var runtimelicense = getRuntimeLicenseKey();
if ((checkStatus === licensingClasses_1.LicenseCheckStatus.NoLicense ||
checkStatus === licensingClasses_1.LicenseCheckStatus.LicenseOK ||
checkStatus === licensingClasses_1.LicenseCheckStatus.StartLookingForLicenseWizard ||
checkStatus === licensingClasses_1.LicenseCheckStatus.LookingForLicenseWizard) &&
//lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY &&
runtimelicense) {
(0, exports.logInfo)("Runtime license found");
(0, exports.debug)("runtime license length=".concat(runtimelicense.length, " hash=").concat(hashLicenseKey(runtimelicense), " value=").concat(runtimelicense));
var sep = runtimelicense.indexOf(";");
if (sep > 0) {
var timeNow = Math.floor(new Date().getTime() / 1000);
var token = runtimelicense.substring(sep + 1);
setLicenseCookie(runtimelicense.substr(0, sep), token, timeNow + 60, timeNow);
}
else {
licenseContext.SCRTCredentials.SetRuntimeLicenseKeyW(runtimelicense);
lt = licenseContext.SCRTCredentials.GetLicenseType();
var licenseType = convertLicenseType(lt, licenseContext);
(0, exports.logInfo)("Runtime license status is " + licensingClasses_1.LicenseType[licenseType]);
if (lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_FULL ||
lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL ||
lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY ||
lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_REQUIRES_VALIDATION) {
isRuntimeKey = true;
licenseKey = runtimelicense;
}
else {
var errorMsg = licenseContext.SCRTCredentials.GetLicenseErrors();
(0, exports.logInfo)("Runtime license is invalid: " + errorMsg);
licenseKey = "";
}
}
}
// Get from cookie store
var licenseCookie = (0, exports.getLicenseCookie)();
if (licenseKey === "" && licenseCookie && licenseCookie.key !== "") {
(0, exports.logInfo)("Found license in cookie.");
licenseKey = licenseCookie.key;
licenseContext.SCRTCredentials.SetRuntimeLicenseKeyW(licenseKey);
lt = licenseContext.SCRTCredentials.GetLicenseType();
// if the license in cookie is bad, remove it
if (!(lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_FULL ||
lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL ||
lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_REQUIRES_VALIDATION)) {
(0, exports.logInfo)("License cookie is invalid. " + licenseContext.SCRTCredentials.GetLicenseErrors());
(0, cookie_1.deleteCookie)("scLicense");
licenseKey = "";
lt = licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY;
}
}
else if (checkStatus === licensingClasses_1.LicenseCheckStatus.FetchingFromServer) {
checkStatus = licensingClasses_1.LicenseCheckStatus.NoLicense;
}
if (licenseKey !== "") {
if (lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY) {
// Set the license if we haven't already
licenseContext.SCRTCredentials.SetRuntimeLicenseKeyW(licenseKey);
lt = licenseContext.SCRTCredentials.GetLicenseType();
}
licenseManager2dState_1.licenseManager2dState.isDev = licenseContext.SCRTCredentials.GetAllowDebugging();
if (lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_FULL ||
lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL ||
lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY) {
checkStatus = licensingClasses_1.LicenseCheckStatus.LicenseOK;
(0, exports.logInfo)("license ok");
if (lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY && isRuntimeKey && !communityNotice) {
console.log("Using SciChart Community Edition. To use a license from the License Wizard, remove the call to UseCommunityLicense");
var daysRemaining = licenseContext.SCRTCredentials.GetLicenseDaysRemaining();
console.log("The community license is valid for 6 months from the date the version in use was released. This version ".concat(BuildStamp_1.libraryVersion, " has ").concat(daysRemaining, " day").concat(daysRemaining === 1 ? "" : "s", " remaining"));
communityNotice = true;
}
}
else if (licenseContext.SCRTCredentials.RequiresValidation()) {
(0, exports.logInfo)("license requires validation");
var metaToken = null;
if (licenseContext.SCRTCredentials.IsSimpleValidation()) {
try {
metaToken = licenseDependencies.getInitialToken();
}
catch (_) {
metaToken = null;
}
}
if (isRuntimeKey && licenseManager2dState_1.licenseManager2dState.isDev) {
// clear key
licenseContext.SCRTCredentials.ResetRuntimeLicense();
(0, cookie_1.deleteCookie)("scLicense");
checkStatus = licensingClasses_1.LicenseCheckStatus.DevKeyInRuntimeKey;
}
else if (metaToken !== null || (licenseCookie.expiry > new Date() && licenseCookie.key === licenseKey)) {
var token = metaToken !== null && metaToken !== void 0 ? metaToken : licenseCookie.token;
(0, exports.debug)(metaToken !== null ? "token from page meta tag" : "current token in cookie");
var expirySeconds = licenseContext.SCRTCredentials.IsSimpleValidation()
? setSimpleChallengeResponse(token, licenseContext)
: setChallengeResponse(token, licenseContext);
lt = licenseContext.SCRTCredentials.GetLicenseType();
if (lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_FULL ||
lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL) {
checkStatus = licensingClasses_1.LicenseCheckStatus.LicenseOK;
}
var timeNow = Math.floor(new Date().getTime() / 1000);
if (metaToken !== null && expirySeconds <= 0) {
(0, exports.logInfo)("Meta-tag license token was rejected (".concat(expirySeconds, "): ").concat((_a = SIMPLE_RESPONSE_ERRORS[expirySeconds]) !== null && _a !== void 0 ? _a : "Unknown error"));
checkStatus = failedValidateStatus();
}
else {
if (metaToken !== null || expirySeconds * 1000 > licenseCookie.expiry.getTime()) {
setLicenseCookie(licenseKey, token, expirySeconds, timeNow);
}
// Force re-validation at most once a day, or sooner if the
// licence's valid_time is shorter than that (cap at the token's
// own validity duration so a 30-min licence still re-validates
// within its window rather than waiting 24h).
// Meta-token path: the cookie is being written this tick (line above) with timeNow
// as lastValidated, but the in-memory licenseCookie snapshot is still pre-write
// (and lastValidated can be null if no prior cookie existed). Use timeNow to
// reflect the value about to be persisted.
var lastValidatedSec = metaToken !== null
? timeNow
: Math.floor(licenseCookie.lastValidated.getTime() / 1000);
var validityDuration = Math.max(0, expirySeconds - lastValidatedSec);
var validationInterval = Math.min(60 * 60 * 24, validityDuration);
var secondsSinceValidated = metaToken !== null ? 0 : (new Date().getTime() - licenseCookie.lastValidated.getTime()) / 1000;
(0, exports.debug)("License expires in ".concat(expirySeconds - timeNow, " seconds. Last validated ").concat(secondsSinceValidated, " seconds ago"));
if (secondsSinceValidated > validationInterval &&
!isValidating(checkStatus)) {
// revalidate now
checkStatus = validatingStatus();
licenseManager2dState_1.licenseManager2dState.checkStatus = checkStatus;
if (licenseContext.SCRTCredentials.IsSimpleValidation() && !licenseManager2dState_1.licenseManager2dState.isDev) {
doSimpleLicenseChallenge(licenseContext);
}
else {
dolicenseChallenge(licenseContext);
}
}
else if (licenseChallengeTimeout === undefined) {
// set timer to revaildate later
licenseChallengeTimeout = setTimeout(function () {
checkStatus = validatingStatus();
// Only refresh chart when we have a valid license
licenseManager2dState_1.licenseManager2dState.checkStatus = checkStatus;
if (licenseContext.SCRTCredentials.IsSimpleValidation() && !licenseManager2dState_1.licenseManager2dState.isDev) {
doSimpleLicenseChallenge(undefined);
}
else {
dolicenseChallenge(undefined);
}
}, Math.floor((expirySeconds - timeNow) * 0.95 * 1000)); // Allow 5%
}
}
}
else if (checkStatus === licensingClasses_1.LicenseCheckStatus.NoLicense) {
checkStatus = validatingStatus();
if (licenseContext.SCRTCredentials.IsSimpleValidation() && !licenseManager2dState_1.licenseManager2dState.isDev) {
doSimpleLicenseChallenge(licenseContext);
}
else {
dolicenseChallenge(licenseContext);
}
}
}
else {
(0, exports.logInfo)("license is invalid: " + licenseContext.SCRTCredentials.GetLicenseErrors());
}
}
(0, exports.logInfo)("checkstatus: " + licensingClasses_1.LicenseCheckStatus[checkStatus]);
if (checkStatus === licensingClasses_1.LicenseCheckStatus.NoLicense) {
if (lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY && !communityNotice) {
console.log("Defaulting to SciChart Community Edition. Usage constitutes acceptance of our EULA and terms at https://www.scichart.com/community-licensing. See https://store.scichart.com for commercial licensing options.");
var daysRemaining = licenseContext.SCRTCredentials.GetLicenseDaysRemaining();
console.log("The community license is valid for 6 months from the date the version in use was released. This version ".concat(BuildStamp_1.libraryVersion, " has ").concat(daysRemaining, " day").concat(daysRemaining === 1 ? "" : "s", " remaining"));
if (!app_1.IS_TEST_ENV && ((_b = document === null || document === void 0 ? void 0 : document.location) === null || _b === void 0 ? void 0 : _b.hostname.startsWith("localhost")) && useLicenseWizard) {
console.log("SciChart is looking for a paid developer activation from the scichart licensing wizard... To disable this call SciChartSurface.UseCommunityLicense()");
}
communityNotice = true;
}
if (wizardTimer === undefined && useLicenseWizard) {
checkStatus = licensingClasses_1.LicenseCheckStatus.StartLookingForLicenseWizard;
licenseManager2dState_1.licenseManager2dState.isDev = true;
getlicenseFromWizard(licenseContext);
}
}
};
exports.applyLicense = applyLicense;
var licenseModal;
var openLicenseModal = function () {
console.error("Modal not initialized");
};
var setNewLicense = function (keyCode, licenseContext) {
var requiresValidation = false;
var trialExpired;
if (licenseModal) {
licenseModal.style.display = "none";
}
isRuntimeKey = false;
setLicenseCookie(keyCode, null, null, null);
licenseContext.SCRTCredentials.SetRuntimeLicenseKeyW(keyCode);
requiresValidation = licenseContext.SCRTCredentials.RequiresValidation();
trialExpired = licenseContext.SCRTCredentials.GetLicenseType() === licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL_EXPIRED;
getAllLicenseContexts().forEach(function (lc) { return lc.SCRTCredentials.SetRuntimeLicenseKeyW(keyCode); });
return { requiresValidation: requiresValidation, trialExpired: trialExpired };
};
var insertedRules = new Dictionary_1.Dictionary();
var insertStyleSheetRule = function (ruleName, ruleText) {
if (insertedRules.containsKey(ruleName))
return