@selfcommunity/utils
Advanced tools
Comparing version
"use strict"; | ||
exports.__esModule = true; | ||
var _string = require("./utils/string"); | ||
exports.capitalize = _string.capitalize; | ||
exports.isString = _string.isString; | ||
exports.stripHtml = _string.stripHtml; | ||
exports.camelCase = _string.camelCase; | ||
exports.copyTextToClipboard = _string.copyTextToClipboard; | ||
exports.fallbackCopyTextToClipboard = _string.fallbackCopyTextToClipboard; | ||
exports.random = _string.random; | ||
var _url = require("./utils/url"); | ||
exports.isValidUrl = _url.isValidUrl; | ||
exports.isValidUrls = _url.isValidUrls; | ||
exports.urlReplacer = _url.urlReplacer; | ||
exports.getDomain = _url.getDomain; | ||
exports.appendURLSearchParams = _url.appendURLSearchParams; | ||
exports.urlB64ToUint8Array = _url.urlB64ToUint8Array; | ||
var _window = require("./utils/window"); | ||
exports.getHighestSafeWindowContext = _window.getHighestSafeWindowContext; | ||
exports.getWindowWidth = _window.getWindowWidth; | ||
exports.getWindowHeight = _window.getWindowHeight; | ||
var _object = require("./utils/object"); | ||
exports.mergeDeep = _object.mergeDeep; | ||
exports.isObject = _object.isObject; | ||
var _browser = require("./utils/browser"); | ||
exports.loadVersionBrowser = _browser.loadVersionBrowser; | ||
var _logger = require("./utils/logger"); | ||
exports.Logger = _logger.Logger; | ||
var _websocket = _interopRequireWildcard(require("./utils/websocket")); | ||
exports.WSClient = _websocket.default; | ||
exports.WSClientType = _websocket.WSClientType; | ||
exports.WSClientPropTypes = _websocket.WSClientPropTypes; | ||
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } | ||
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.loadVersionBrowser = exports.WSClient = exports.isObject = exports.mergeDeep = exports.Logger = exports.isClientSideRendering = exports.getWindowHeight = exports.getWindowWidth = exports.getHighestSafeWindowContext = exports.urlB64ToUint8Array = exports.appendURLSearchParams = exports.getDomain = exports.urlReplacer = exports.isValidUrls = exports.isValidUrl = exports.random = exports.fallbackCopyTextToClipboard = exports.copyTextToClipboard = exports.camelCase = exports.stripHtml = exports.isString = exports.capitalize = void 0; | ||
const string_1 = require("./utils/string"); | ||
Object.defineProperty(exports, "capitalize", { enumerable: true, get: function () { return string_1.capitalize; } }); | ||
Object.defineProperty(exports, "isString", { enumerable: true, get: function () { return string_1.isString; } }); | ||
Object.defineProperty(exports, "stripHtml", { enumerable: true, get: function () { return string_1.stripHtml; } }); | ||
Object.defineProperty(exports, "camelCase", { enumerable: true, get: function () { return string_1.camelCase; } }); | ||
Object.defineProperty(exports, "copyTextToClipboard", { enumerable: true, get: function () { return string_1.copyTextToClipboard; } }); | ||
Object.defineProperty(exports, "fallbackCopyTextToClipboard", { enumerable: true, get: function () { return string_1.fallbackCopyTextToClipboard; } }); | ||
Object.defineProperty(exports, "random", { enumerable: true, get: function () { return string_1.random; } }); | ||
const url_1 = require("./utils/url"); | ||
Object.defineProperty(exports, "isValidUrl", { enumerable: true, get: function () { return url_1.isValidUrl; } }); | ||
Object.defineProperty(exports, "isValidUrls", { enumerable: true, get: function () { return url_1.isValidUrls; } }); | ||
Object.defineProperty(exports, "urlReplacer", { enumerable: true, get: function () { return url_1.urlReplacer; } }); | ||
Object.defineProperty(exports, "getDomain", { enumerable: true, get: function () { return url_1.getDomain; } }); | ||
Object.defineProperty(exports, "appendURLSearchParams", { enumerable: true, get: function () { return url_1.appendURLSearchParams; } }); | ||
Object.defineProperty(exports, "urlB64ToUint8Array", { enumerable: true, get: function () { return url_1.urlB64ToUint8Array; } }); | ||
const window_1 = require("./utils/window"); | ||
Object.defineProperty(exports, "getHighestSafeWindowContext", { enumerable: true, get: function () { return window_1.getHighestSafeWindowContext; } }); | ||
Object.defineProperty(exports, "getWindowWidth", { enumerable: true, get: function () { return window_1.getWindowWidth; } }); | ||
Object.defineProperty(exports, "getWindowHeight", { enumerable: true, get: function () { return window_1.getWindowHeight; } }); | ||
Object.defineProperty(exports, "isClientSideRendering", { enumerable: true, get: function () { return window_1.isClientSideRendering; } }); | ||
const object_1 = require("./utils/object"); | ||
Object.defineProperty(exports, "mergeDeep", { enumerable: true, get: function () { return object_1.mergeDeep; } }); | ||
Object.defineProperty(exports, "isObject", { enumerable: true, get: function () { return object_1.isObject; } }); | ||
const browser_1 = require("./utils/browser"); | ||
Object.defineProperty(exports, "loadVersionBrowser", { enumerable: true, get: function () { return browser_1.loadVersionBrowser; } }); | ||
const logger_1 = require("./utils/logger"); | ||
Object.defineProperty(exports, "Logger", { enumerable: true, get: function () { return logger_1.Logger; } }); | ||
const websocket_1 = __importDefault(require("./utils/websocket")); | ||
exports.WSClient = websocket_1.default; | ||
//# sourceMappingURL=index.js.map |
"use strict"; | ||
exports.__esModule = true; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.loadVersionBrowser = void 0; | ||
/** | ||
@@ -11,81 +9,67 @@ * Get browser version to track on backend | ||
const loadVersionBrowser = () => { | ||
if ('userAgentData' in navigator) { | ||
// navigator.userAgentData is not available in | ||
// Firefox and Safari | ||
const uaData = navigator['userAgentData']; // Outputs of navigator.userAgentData.brands[n].brand are e.g. | ||
// Chrome: 'Google Chrome' | ||
// Edge: 'Microsoft Edge' | ||
// Opera: 'Opera' | ||
let browsername; | ||
let browserversion; | ||
let chromeVersion = null; | ||
for (let i = 0; i < uaData['brands'].length; i++) { | ||
const brand = uaData['brands'][i].brand; | ||
browserversion = uaData['brands'][i].version; | ||
if (brand.match(/opera|chrome|edge|safari|firefox|msie|trident/i) !== null) { | ||
// If we have a chrome match, save the match, but try to find another match | ||
// E.g. Edge can also produce a false Chrome match. | ||
if (brand.match(/chrome/i) !== null) { | ||
chromeVersion = browserversion; | ||
} // If this is not a chrome match return immediately | ||
else { | ||
browsername = brand.substr(brand.indexOf(' ') + 1); | ||
return { | ||
name: browsername, | ||
version: browserversion | ||
}; | ||
if ('userAgentData' in navigator) { | ||
// navigator.userAgentData is not available in | ||
// Firefox and Safari | ||
const uaData = navigator['userAgentData']; | ||
// Outputs of navigator.userAgentData.brands[n].brand are e.g. | ||
// Chrome: 'Google Chrome' | ||
// Edge: 'Microsoft Edge' | ||
// Opera: 'Opera' | ||
let browsername; | ||
let browserversion; | ||
let chromeVersion = null; | ||
for (let i = 0; i < uaData['brands'].length; i++) { | ||
const brand = uaData['brands'][i].brand; | ||
browserversion = uaData['brands'][i].version; | ||
if (brand.match(/opera|chrome|edge|safari|firefox|msie|trident/i) !== null) { | ||
// If we have a chrome match, save the match, but try to find another match | ||
// E.g. Edge can also produce a false Chrome match. | ||
if (brand.match(/chrome/i) !== null) { | ||
chromeVersion = browserversion; | ||
} | ||
// If this is not a chrome match return immediately | ||
else { | ||
browsername = brand.substr(brand.indexOf(' ') + 1); | ||
return { | ||
name: browsername, | ||
version: browserversion, | ||
}; | ||
} | ||
} | ||
} | ||
} | ||
} // No non-Chrome match was found. If we have a chrome match, return it. | ||
if (chromeVersion !== null) { | ||
return { | ||
name: 'chrome', | ||
version: chromeVersion | ||
}; | ||
// No non-Chrome match was found. If we have a chrome match, return it. | ||
if (chromeVersion !== null) { | ||
return { | ||
name: 'chrome', | ||
version: chromeVersion, | ||
}; | ||
} | ||
} | ||
} // If no userAgentData is not present, or if no match via userAgentData was found, | ||
// try to extract the browser name and version from userAgent | ||
const userAgent = navigator.userAgent; | ||
let ua = userAgent; | ||
let tem; | ||
let M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; | ||
if (/trident/i.test(M[1])) { | ||
tem = /\brv[ :]+(\d+)/g.exec(ua) || []; | ||
// If no userAgentData is not present, or if no match via userAgentData was found, | ||
// try to extract the browser name and version from userAgent | ||
const userAgent = navigator.userAgent; | ||
let ua = userAgent; | ||
let tem; | ||
let M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; | ||
if (/trident/i.test(M[1])) { | ||
tem = /\brv[ :]+(\d+)/g.exec(ua) || []; | ||
return { name: 'IE', version: tem[1] || '' }; | ||
} | ||
if (M[1] === 'Chrome') { | ||
tem = ua.match(/\bOPR\/(\d+)/); | ||
if (tem != null) { | ||
return { name: 'Opera', version: tem[1] }; | ||
} | ||
} | ||
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?']; | ||
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec | ||
if ((tem = ua.match(/version\/(\d+)/i)) != null) { | ||
M.splice(1, 1, tem[1]); | ||
} | ||
return { | ||
name: 'IE', | ||
version: tem[1] || '' | ||
name: M[0], | ||
version: M[1], | ||
}; | ||
} | ||
if (M[1] === 'Chrome') { | ||
tem = ua.match(/\bOPR\/(\d+)/); | ||
if (tem != null) { | ||
return { | ||
name: 'Opera', | ||
version: tem[1] | ||
}; | ||
} | ||
} | ||
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?']; // eslint-disable-next-line @typescript-eslint/prefer-regexp-exec | ||
if ((tem = ua.match(/version\/(\d+)/i)) != null) { | ||
M.splice(1, 1, tem[1]); | ||
} | ||
return { | ||
name: M[0], | ||
version: M[1] | ||
}; | ||
}; | ||
exports.loadVersionBrowser = loadVersionBrowser; | ||
exports.loadVersionBrowser = loadVersionBrowser; | ||
//# sourceMappingURL=browser.js.map |
"use strict"; | ||
exports.__esModule = true; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Logger = void 0; | ||
/** | ||
@@ -10,24 +8,19 @@ * Emit styled message | ||
class Logger { | ||
static info(scope, message) { | ||
console.info(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static warn(scope, message) { | ||
console.warn(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static error(scope, message) { | ||
console.error(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static log(scope, message) { | ||
console.log(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static debug(scope, message) { | ||
console.debug(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static info(scope, message) { | ||
console.info(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static warn(scope, message) { | ||
console.warn(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static error(scope, message) { | ||
console.error(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static log(scope, message) { | ||
console.log(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static debug(scope, message) { | ||
console.debug(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
} | ||
exports.Logger = Logger; | ||
exports.Logger = Logger; | ||
//# sourceMappingURL=logger.js.map |
"use strict"; | ||
exports.__esModule = true; | ||
exports.isObject = isObject; | ||
exports.mergeDeep = mergeDeep; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.mergeDeep = exports.isObject = void 0; | ||
/** | ||
@@ -12,4 +9,5 @@ * Check if v is an object | ||
function isObject(v) { | ||
return typeof v === 'object' && !Array.isArray(v) && v !== null; | ||
return typeof v === 'object' && !Array.isArray(v) && v !== null; | ||
} | ||
exports.isObject = isObject; | ||
/** | ||
@@ -21,26 +19,22 @@ * Perfrom deep merge of two objects (not a shallow merge) | ||
*/ | ||
function mergeDeep(target, source) { | ||
let output = Object.assign({}, target); | ||
if (isObject(target) && isObject(source)) { | ||
Object.keys(source).forEach(key => { | ||
if (isObject(source[key])) { | ||
if (!(key in target)) { | ||
Object.assign(output, { | ||
[key]: source[key] | ||
}); | ||
} else { | ||
output[key] = mergeDeep(target[key], source[key]); | ||
} | ||
} else { | ||
Object.assign(output, { | ||
[key]: source[key] | ||
let output = Object.assign({}, target); | ||
if (isObject(target) && isObject(source)) { | ||
Object.keys(source).forEach((key) => { | ||
if (isObject(source[key])) { | ||
if (!(key in target)) { | ||
Object.assign(output, { [key]: source[key] }); | ||
} | ||
else { | ||
output[key] = mergeDeep(target[key], source[key]); | ||
} | ||
} | ||
else { | ||
Object.assign(output, { [key]: source[key] }); | ||
} | ||
}); | ||
} | ||
}); | ||
} | ||
return output; | ||
} | ||
} | ||
return output; | ||
} | ||
exports.mergeDeep = mergeDeep; | ||
//# sourceMappingURL=object.js.map |
"use strict"; | ||
exports.__esModule = true; | ||
exports.camelCase = camelCase; | ||
exports.capitalize = capitalize; | ||
exports.copyTextToClipboard = copyTextToClipboard; | ||
exports.fallbackCopyTextToClipboard = fallbackCopyTextToClipboard; | ||
exports.isString = isString; | ||
exports.random = random; | ||
exports.stripHtml = stripHtml; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.copyTextToClipboard = exports.fallbackCopyTextToClipboard = exports.random = exports.stripHtml = exports.camelCase = exports.capitalize = exports.isString = void 0; | ||
/** | ||
@@ -17,4 +9,5 @@ * Check if v is a string | ||
function isString(v) { | ||
return typeof v === 'string' || v instanceof String; | ||
return typeof v === 'string' || v instanceof String; | ||
} | ||
exports.isString = isString; | ||
/** | ||
@@ -24,14 +17,11 @@ * Capitalize a string | ||
*/ | ||
function capitalize(str) { | ||
let strVal = ''; | ||
let strArr = str.split(' '); | ||
for (let chr = 0; chr < strArr.length; chr++) { | ||
strVal += strArr[chr].substring(0, 1).toUpperCase() + strArr[chr].substring(1, strArr[chr].length); | ||
} | ||
return strVal; | ||
let strVal = ''; | ||
let strArr = str.split(' '); | ||
for (let chr = 0; chr < strArr.length; chr++) { | ||
strVal += strArr[chr].substring(0, 1).toUpperCase() + strArr[chr].substring(1, strArr[chr].length); | ||
} | ||
return strVal; | ||
} | ||
exports.capitalize = capitalize; | ||
/** | ||
@@ -41,15 +31,19 @@ * CamelCase a string | ||
*/ | ||
function camelCase(str) { | ||
// Lower cases the string | ||
return str.toLowerCase() // Replaces any - or _ characters with a space | ||
.replace(/[-_]+/g, ' ') // Removes any non alphanumeric characters | ||
.replace(/[^\w\s]/g, '') // Uppercases the first character in each group immediately following a space | ||
// (delimited by spaces) | ||
.replace(/ (.)/g, $1 => { | ||
return $1.toUpperCase(); | ||
}) // Removes spaces | ||
.replace(/ /g, ''); | ||
// Lower cases the string | ||
return (str | ||
.toLowerCase() | ||
// Replaces any - or _ characters with a space | ||
.replace(/[-_]+/g, ' ') | ||
// Removes any non alphanumeric characters | ||
.replace(/[^\w\s]/g, '') | ||
// Uppercases the first character in each group immediately following a space | ||
// (delimited by spaces) | ||
.replace(/ (.)/g, ($1) => { | ||
return $1.toUpperCase(); | ||
}) | ||
// Removes spaces | ||
.replace(/ /g, '')); | ||
} | ||
exports.camelCase = camelCase; | ||
/** | ||
@@ -59,11 +53,10 @@ * Stripe html tags from a string | ||
*/ | ||
function stripHtml(str) { | ||
return str.replace(/<[^>]*>?/gm, '').trim(); | ||
return str.replace(/<[^>]*>?/gm, '').trim(); | ||
} | ||
exports.stripHtml = stripHtml; | ||
function random() { | ||
return (Math.random() + 1).toString(36).substring(7); | ||
return (Math.random() + 1).toString(36).substring(7); | ||
} | ||
exports.random = random; | ||
/** | ||
@@ -74,24 +67,23 @@ * Fallback if navigator.clipboard doensn't exist | ||
*/ | ||
function fallbackCopyTextToClipboard(text) { | ||
let textArea = document.createElement('textarea'); | ||
textArea.value = text; // Avoid scrolling to bottom | ||
textArea.style.top = '0'; | ||
textArea.style.left = '0'; | ||
textArea.style.position = 'fixed'; | ||
document.body.appendChild(textArea); | ||
textArea.focus(); | ||
textArea.select(); | ||
try { | ||
document.execCommand('copy'); | ||
document.body.removeChild(textArea); | ||
return Promise.resolve(); | ||
} catch (err) { | ||
document.body.removeChild(textArea); | ||
return Promise.reject(err); | ||
} | ||
let textArea = document.createElement('textarea'); | ||
textArea.value = text; | ||
// Avoid scrolling to bottom | ||
textArea.style.top = '0'; | ||
textArea.style.left = '0'; | ||
textArea.style.position = 'fixed'; | ||
document.body.appendChild(textArea); | ||
textArea.focus(); | ||
textArea.select(); | ||
try { | ||
document.execCommand('copy'); | ||
document.body.removeChild(textArea); | ||
return Promise.resolve(); | ||
} | ||
catch (err) { | ||
document.body.removeChild(textArea); | ||
return Promise.reject(err); | ||
} | ||
} | ||
exports.fallbackCopyTextToClipboard = fallbackCopyTextToClipboard; | ||
/** | ||
@@ -111,10 +103,9 @@ * Copy text to clipboard | ||
*/ | ||
function copyTextToClipboard(text) { | ||
if (!navigator.clipboard) { | ||
return fallbackCopyTextToClipboard(text); | ||
} | ||
return navigator.clipboard.writeText(text); | ||
} | ||
if (!navigator.clipboard) { | ||
return fallbackCopyTextToClipboard(text); | ||
} | ||
return navigator.clipboard.writeText(text); | ||
} | ||
exports.copyTextToClipboard = copyTextToClipboard; | ||
//# sourceMappingURL=string.js.map |
"use strict"; | ||
exports.__esModule = true; | ||
exports.appendURLSearchParams = appendURLSearchParams; | ||
exports.urlReplacer = exports.urlB64ToUint8Array = exports.isValidUrls = exports.isValidUrl = exports.getDomain = void 0; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.urlB64ToUint8Array = exports.appendURLSearchParams = exports.isValidUrls = exports.isValidUrl = exports.getDomain = exports.urlReplacer = void 0; | ||
/** | ||
@@ -11,18 +8,16 @@ * Utility Url Replacer | ||
*/ | ||
const urlReplacer = path => { | ||
const replacer = function replacer(tpl, data) { | ||
const re = /\$\(([^)]+)?\)/g; | ||
let match = re.exec(tpl); | ||
while (match) { | ||
tpl = tpl.replace(match[0], data[match[1]]); | ||
re.lastIndex = 0; | ||
match = re.exec(tpl); | ||
} | ||
return tpl; | ||
}; | ||
return params => replacer(path, params); | ||
const urlReplacer = (path) => { | ||
const replacer = function (tpl, data) { | ||
const re = /\$\(([^)]+)?\)/g; | ||
let match = re.exec(tpl); | ||
while (match) { | ||
tpl = tpl.replace(match[0], data[match[1]]); | ||
re.lastIndex = 0; | ||
match = re.exec(tpl); | ||
} | ||
return tpl; | ||
}; | ||
return (params) => replacer(path, params); | ||
}; | ||
exports.urlReplacer = urlReplacer; | ||
/** | ||
@@ -32,16 +27,11 @@ * Get domain | ||
*/ | ||
exports.urlReplacer = urlReplacer; | ||
const getDomain = url => { | ||
// eslint-disable-next-line no-useless-escape,@typescript-eslint/prefer-regexp-exec | ||
const matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i); | ||
if (matches && matches[1]) { | ||
return matches[1]; | ||
} | ||
return ''; | ||
const getDomain = (url) => { | ||
// eslint-disable-next-line no-useless-escape,@typescript-eslint/prefer-regexp-exec | ||
const matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i); | ||
if (matches && matches[1]) { | ||
return matches[1]; | ||
} | ||
return ''; | ||
}; | ||
exports.getDomain = getDomain; | ||
/** | ||
@@ -51,10 +41,7 @@ * Check a str is a valid url pattern | ||
*/ | ||
exports.getDomain = getDomain; | ||
const isValidUrl = url => { | ||
const regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/; | ||
return regexp.test(url); | ||
const isValidUrl = (url) => { | ||
const regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/; | ||
return regexp.test(url); | ||
}; | ||
exports.isValidUrl = isValidUrl; | ||
/** | ||
@@ -65,10 +52,7 @@ * Check a str is a valid list of urls separated by delimiter | ||
*/ | ||
exports.isValidUrl = isValidUrl; | ||
const isValidUrls = (value, delimiter) => { | ||
const urls = value.trim().split(delimiter); | ||
return urls.every(isValidUrl); | ||
const urls = value.trim().split(delimiter); | ||
return urls.every(exports.isValidUrl); | ||
}; | ||
exports.isValidUrls = isValidUrls; | ||
/** | ||
@@ -79,20 +63,15 @@ * Append params | ||
*/ | ||
exports.isValidUrls = isValidUrls; | ||
function appendURLSearchParams(baseUrl, queryParams) { | ||
let _url = baseUrl; | ||
if (queryParams.length && _url) { | ||
const key = Object.keys(queryParams[0])[0]; | ||
_url += (_url.split('?')[1] ? '&' : '?') + `${key}=${queryParams[0][key]}`; | ||
queryParams.slice(1).map(p => { | ||
const key = Object.keys(p)[0]; | ||
_url += `&${key}=${p[key]}`; | ||
}); | ||
} | ||
return _url; | ||
let _url = baseUrl; | ||
if (queryParams.length && _url) { | ||
const key = Object.keys(queryParams[0])[0]; | ||
_url += (_url.split('?')[1] ? '&' : '?') + `${key}=${queryParams[0][key]}`; | ||
queryParams.slice(1).map((p) => { | ||
const key = Object.keys(p)[0]; | ||
_url += `&${key}=${p[key]}`; | ||
}); | ||
} | ||
return _url; | ||
} | ||
exports.appendURLSearchParams = appendURLSearchParams; | ||
/** | ||
@@ -102,17 +81,13 @@ * Take the application server's public key, which is Base64 URL-safe encoded, | ||
*/ | ||
const urlB64ToUint8Array = base64String => { | ||
const padding = '='.repeat((4 - base64String.length % 4) % 4); | ||
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/'); | ||
const rawData = window.atob(base64); | ||
const outputArray = new Uint8Array(rawData.length); | ||
for (let i = 0; i < rawData.length; ++i) { | ||
outputArray[i] = rawData.charCodeAt(i); | ||
} | ||
return outputArray; | ||
const urlB64ToUint8Array = (base64String) => { | ||
const padding = '='.repeat((4 - (base64String.length % 4)) % 4); | ||
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/'); | ||
const rawData = window.atob(base64); | ||
const outputArray = new Uint8Array(rawData.length); | ||
for (let i = 0; i < rawData.length; ++i) { | ||
outputArray[i] = rawData.charCodeAt(i); | ||
} | ||
return outputArray; | ||
}; | ||
exports.urlB64ToUint8Array = urlB64ToUint8Array; | ||
exports.urlB64ToUint8Array = urlB64ToUint8Array; | ||
//# sourceMappingURL=url.js.map |
"use strict"; | ||
exports.__esModule = true; | ||
exports.default = void 0; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
/** | ||
* WSClientPropTypes interface | ||
*/ | ||
/** | ||
* WSClient: manage socket connection | ||
@@ -16,293 +9,237 @@ * @param options | ||
class WSClient { | ||
/** | ||
* Constructor | ||
* @param cfg | ||
*/ | ||
constructor(cfg) { | ||
this._attempts = 1; | ||
this._heartbeatInterval = null; | ||
this._missedHeartbeats = 0; | ||
if (!this.isValidOptions(cfg)) { | ||
return; | ||
/** | ||
* Constructor | ||
* @param cfg | ||
*/ | ||
constructor(cfg) { | ||
this._attempts = 1; | ||
this._heartbeatInterval = null; | ||
this._missedHeartbeats = 0; | ||
if (!this.isValidOptions(cfg)) { | ||
return; | ||
} | ||
this._cfg = Object.assign({}, { heartbeatMsg: null, debug: false, mustReconnect: true }, cfg); | ||
this.connect(); | ||
} | ||
this._cfg = Object.assign({}, { | ||
heartbeatMsg: null, | ||
debug: false, | ||
mustReconnect: true | ||
}, cfg); | ||
this.connect(); | ||
} | ||
/** | ||
* Get instance | ||
*/ | ||
static getInstance(cfg) { | ||
this._instance = this._instance || new WSClient(cfg); | ||
return this._instance; | ||
} | ||
/** | ||
* Connect | ||
*/ | ||
connect() { | ||
try { | ||
if (this._ws && (this.isConnecting() || this.isConnected())) { | ||
// There is already a connection | ||
this._cfg.debug && console.info('Websocket is connecting or already connected.'); | ||
return; | ||
} // Callback 'connecting' if exist | ||
typeof this._cfg.connecting === 'function' && this._cfg.connecting(); | ||
this._cfg.debug && console.info(`Connecting to ${this._cfg.uri} ...`); // Open the connection | ||
this._ws = new WebSocket(this._cfg.uri, this._cfg.protocols); | ||
this._ws.onopen = this.onOpen.bind(this); | ||
this._ws.onmessage = this.onMessage.bind(this); | ||
this._ws.onerror = this.onError.bind(this); | ||
this._ws.onclose = this.onClose.bind(this); | ||
this._timer = null; | ||
} catch (err) { | ||
console.error(err); | ||
this.tryToReconnect(); | ||
/** | ||
* Get instance | ||
*/ | ||
static getInstance(cfg) { | ||
this._instance = this._instance || new WSClient(cfg); | ||
return this._instance; | ||
} | ||
} | ||
/** | ||
* Validate options | ||
* @param cfg | ||
*/ | ||
isValidOptions(cfg) { | ||
let _error = false; | ||
if (!cfg) { | ||
console.error('Invalid WSClient options.'); | ||
return _error; | ||
/** | ||
* Connect | ||
*/ | ||
connect() { | ||
try { | ||
if (this._ws && (this.isConnecting() || this.isConnected())) { | ||
// There is already a connection | ||
this._cfg.debug && console.info('Websocket is connecting or already connected.'); | ||
return; | ||
} | ||
// Callback 'connecting' if exist | ||
typeof this._cfg.connecting === 'function' && this._cfg.connecting(); | ||
this._cfg.debug && console.info(`Connecting to ${this._cfg.uri} ...`); | ||
// Open the connection | ||
this._ws = new WebSocket(this._cfg.uri, this._cfg.protocols); | ||
this._ws.onopen = this.onOpen.bind(this); | ||
this._ws.onmessage = this.onMessage.bind(this); | ||
this._ws.onerror = this.onError.bind(this); | ||
this._ws.onclose = this.onClose.bind(this); | ||
this._timer = null; | ||
} | ||
catch (err) { | ||
console.error(err); | ||
this.tryToReconnect(); | ||
} | ||
} | ||
if (!cfg.uri) { | ||
console.error('Invalid WSClient Uri options.'); | ||
_error = true; | ||
/** | ||
* Validate options | ||
* @param cfg | ||
*/ | ||
isValidOptions(cfg) { | ||
let _error = false; | ||
if (!cfg) { | ||
console.error('Invalid WSClient options.'); | ||
return _error; | ||
} | ||
if (!cfg.uri) { | ||
console.error('Invalid WSClient Uri options.'); | ||
_error = true; | ||
} | ||
if (cfg && cfg.connecting && !(typeof cfg.connecting === 'function')) { | ||
console.error('Invalid WSClient connecting options.'); | ||
_error = true; | ||
} | ||
if (cfg && cfg.connected && !(typeof cfg.connected === 'function')) { | ||
console.error('Invalid WSClient connected options.'); | ||
_error = true; | ||
} | ||
if (cfg && cfg.receiveMessage && !(typeof cfg.receiveMessage === 'function')) { | ||
console.error('Invalid WSClient receiveMessage options.'); | ||
_error = true; | ||
} | ||
if (cfg && cfg.disconnected && !(typeof cfg.disconnected === 'function')) { | ||
console.error('Invalid WSClient connecting options.'); | ||
_error = true; | ||
} | ||
if (cfg && cfg.heartbeatMsg && !(typeof cfg.heartbeatMsg === 'string')) { | ||
console.error('Invalid WSClient heartbeatMsg options.'); | ||
_error = true; | ||
} | ||
if (cfg && cfg.debug && !(typeof cfg.debug === 'boolean')) { | ||
console.error('Invalid WSClient debug options.'); | ||
_error = true; | ||
} | ||
return !_error; | ||
} | ||
if (cfg && cfg.connecting && !(typeof cfg.connecting === 'function')) { | ||
console.error('Invalid WSClient connecting options.'); | ||
_error = true; | ||
/** | ||
* Try to reconnect if previous connection failed | ||
* Generate an interval, after that try to reconnect | ||
*/ | ||
tryToReconnect() { | ||
if (this._cfg.mustReconnect && !this._timer) { | ||
this._cfg.debug && console.info(`Reconnecting...`); | ||
let interval = this.generateInteval(this._attempts); | ||
this._timer = setTimeout(this.reconnect.bind(this), interval); | ||
} | ||
} | ||
if (cfg && cfg.connected && !(typeof cfg.connected === 'function')) { | ||
console.error('Invalid WSClient connected options.'); | ||
_error = true; | ||
/** | ||
* Reestablish the connection | ||
* Increase the number of attempts | ||
*/ | ||
reconnect() { | ||
this._attempts++; | ||
this.connect(); | ||
} | ||
if (cfg && cfg.receiveMessage && !(typeof cfg.receiveMessage === 'function')) { | ||
console.error('Invalid WSClient receiveMessage options.'); | ||
_error = true; | ||
/** | ||
* Send heartbeat every 5 seconds | ||
* If missing more than 3 heartbeats close connection | ||
*/ | ||
sendHeartbeat() { | ||
try { | ||
this._missedHeartbeats++; | ||
if (this._missedHeartbeats > 3) | ||
throw new Error('Too many missed heartbeats.'); | ||
this._ws.send(this._cfg.heartbeatMsg); | ||
} | ||
catch (e) { | ||
clearInterval(this._heartbeatInterval); | ||
this._heartbeatInterval = null; | ||
this._cfg.debug && console.warn(`Closing connection. Reason: ${e.message}`); | ||
if (!this.isClosing() && !this.isClosed()) { | ||
this.close(); | ||
} | ||
} | ||
} | ||
if (cfg && cfg.disconnected && !(typeof cfg.disconnected === 'function')) { | ||
console.error('Invalid WSClient connecting options.'); | ||
_error = true; | ||
/** | ||
* Established the new connection | ||
* Reset this._attempts counter | ||
*/ | ||
onOpen() { | ||
this._cfg.debug && console.info('Connected!'); | ||
this._attempts = 1; | ||
if (this._cfg.heartbeatMsg && this._heartbeatInterval === null) { | ||
this._missedHeartbeats = 0; | ||
this._heartbeatInterval = setInterval(this.sendHeartbeat.bind(this), 5000); | ||
} | ||
typeof this._cfg.connected === 'function' && this._cfg.connected(); | ||
} | ||
if (cfg && cfg.heartbeatMsg && !(typeof cfg.heartbeatMsg === 'string')) { | ||
console.error('Invalid WSClient heartbeatMsg options.'); | ||
_error = true; | ||
/** | ||
* Connection closed. Try to reconnect. | ||
* @param evt | ||
*/ | ||
onClose(evt) { | ||
this._cfg.debug && console.info('Connection closed!'); | ||
typeof this._cfg.disconnected === 'function' && this._cfg.disconnected(evt); | ||
this.tryToReconnect(); | ||
} | ||
if (cfg && cfg.debug && !(typeof cfg.debug === 'boolean')) { | ||
console.error('Invalid WSClient debug options.'); | ||
_error = true; | ||
/** | ||
* An error occured | ||
* @param evt | ||
*/ | ||
onError(evt) { | ||
this._cfg.debug && console.error('Websocket connection is broken!'); | ||
this._cfg.debug && console.error(evt); | ||
} | ||
return !_error; | ||
} | ||
/** | ||
* Try to reconnect if previous connection failed | ||
* Generate an interval, after that try to reconnect | ||
*/ | ||
tryToReconnect() { | ||
if (this._cfg.mustReconnect && !this._timer) { | ||
this._cfg.debug && console.info(`Reconnecting...`); | ||
let interval = this.generateInteval(this._attempts); | ||
this._timer = setTimeout(this.reconnect.bind(this), interval); | ||
/** | ||
* A message has arrived. | ||
* If it is the heartbeat -> reset this._missedHeartbeats | ||
* If it is data pass data to the callback | ||
* @param evt | ||
*/ | ||
onMessage(evt) { | ||
if (this._cfg.heartbeatMsg && evt.data === this._cfg.heartbeatMsg) { | ||
// reset the counter for missed heartbeats | ||
this._missedHeartbeats = 0; | ||
} | ||
else if (typeof this._cfg.receiveMessage === 'function') { | ||
return this._cfg.receiveMessage(evt.data); | ||
} | ||
} | ||
} | ||
/** | ||
* Reestablish the connection | ||
* Increase the number of attempts | ||
*/ | ||
reconnect() { | ||
this._attempts++; | ||
this.connect(); | ||
} | ||
/** | ||
* Send heartbeat every 5 seconds | ||
* If missing more than 3 heartbeats close connection | ||
*/ | ||
sendHeartbeat() { | ||
try { | ||
this._missedHeartbeats++; | ||
if (this._missedHeartbeats > 3) throw new Error('Too many missed heartbeats.'); | ||
this._ws.send(this._cfg.heartbeatMsg); | ||
} catch (e) { | ||
clearInterval(this._heartbeatInterval); | ||
this._heartbeatInterval = null; | ||
this._cfg.debug && console.warn(`Closing connection. Reason: ${e.message}`); | ||
if (!this.isClosing() && !this.isClosed()) { | ||
this.close(); | ||
} | ||
/** | ||
* Generate an interval that is randomly between 0 and 2^k - 1, where k is | ||
* the number of connection attmpts, with a maximum interval of 30 seconds, | ||
* so it starts at 0 - 1 seconds and maxes out at 0 - 30 seconds | ||
*/ | ||
generateInteval(k) { | ||
let maxInterval = (Math.pow(2, k) - 1) * 1000; | ||
// If the generated interval is more than 30 seconds, truncate it down to 30 seconds. | ||
if (maxInterval > 30 * 1000) { | ||
maxInterval = 30 * 1000; | ||
} | ||
// generate the interval to a random number between 0 and the maxInterval determined from above | ||
return Math.random() * maxInterval; | ||
} | ||
} | ||
/** | ||
* Established the new connection | ||
* Reset this._attempts counter | ||
*/ | ||
onOpen() { | ||
this._cfg.debug && console.info('Connected!'); | ||
this._attempts = 1; | ||
if (this._cfg.heartbeatMsg && this._heartbeatInterval === null) { | ||
this._missedHeartbeats = 0; | ||
this._heartbeatInterval = setInterval(this.sendHeartbeat.bind(this), 5000); | ||
/** | ||
* Send message | ||
* @param message | ||
*/ | ||
sendMessage(message) { | ||
this._ws && this._ws.send(message); | ||
} | ||
typeof this._cfg.connected === 'function' && this._cfg.connected(); | ||
} | ||
/** | ||
* Connection closed. Try to reconnect. | ||
* @param evt | ||
*/ | ||
onClose(evt) { | ||
this._cfg.debug && console.info('Connection closed!'); | ||
typeof this._cfg.disconnected === 'function' && this._cfg.disconnected(evt); | ||
this.tryToReconnect(); | ||
} | ||
/** | ||
* An error occured | ||
* @param evt | ||
*/ | ||
onError(evt) { | ||
this._cfg.debug && console.error('Websocket connection is broken!'); | ||
this._cfg.debug && console.error(evt); | ||
} | ||
/** | ||
* A message has arrived. | ||
* If it is the heartbeat -> reset this._missedHeartbeats | ||
* If it is data pass data to the callback | ||
* @param evt | ||
*/ | ||
onMessage(evt) { | ||
if (this._cfg.heartbeatMsg && evt.data === this._cfg.heartbeatMsg) { | ||
// reset the counter for missed heartbeats | ||
this._missedHeartbeats = 0; | ||
} else if (typeof this._cfg.receiveMessage === 'function') { | ||
return this._cfg.receiveMessage(evt.data); | ||
/** | ||
* Get the ws state | ||
*/ | ||
getState() { | ||
return this._ws && this._ws.readyState; | ||
} | ||
} | ||
/** | ||
* Generate an interval that is randomly between 0 and 2^k - 1, where k is | ||
* the number of connection attmpts, with a maximum interval of 30 seconds, | ||
* so it starts at 0 - 1 seconds and maxes out at 0 - 30 seconds | ||
*/ | ||
generateInteval(k) { | ||
let maxInterval = (Math.pow(2, k) - 1) * 1000; // If the generated interval is more than 30 seconds, truncate it down to 30 seconds. | ||
if (maxInterval > 30 * 1000) { | ||
maxInterval = 30 * 1000; | ||
} // generate the interval to a random number between 0 and the maxInterval determined from above | ||
return Math.random() * maxInterval; | ||
} | ||
/** | ||
* Send message | ||
* @param message | ||
*/ | ||
sendMessage(message) { | ||
this._ws && this._ws.send(message); | ||
} | ||
/** | ||
* Get the ws state | ||
*/ | ||
getState() { | ||
return this._ws && this._ws.readyState; | ||
} | ||
/** | ||
* Check if ws is in connecting state | ||
*/ | ||
isConnecting() { | ||
return this._ws && this._ws.readyState === 0; | ||
} | ||
/** | ||
* Check if ws is connected | ||
*/ | ||
isConnected() { | ||
return this._ws && this._ws.readyState === 1; | ||
} | ||
/** | ||
* Check if ws is in closing state | ||
*/ | ||
isClosing() { | ||
return this._ws && this._ws.readyState === 2; | ||
} | ||
/** | ||
* Check if ws is closed | ||
*/ | ||
isClosed() { | ||
return this._ws && this._ws.readyState === 3; | ||
} | ||
/** | ||
* Close the connection | ||
*/ | ||
close() { | ||
clearInterval(this._heartbeatInterval); | ||
this._cfg.mustReconnect = false; | ||
if (!this.isClosing() || !this.isClosed()) { | ||
this._ws.close(); | ||
this._cfg.debug && console.error('Websocket closed.'); | ||
/** | ||
* Check if ws is in connecting state | ||
*/ | ||
isConnecting() { | ||
return this._ws && this._ws.readyState === 0; | ||
} | ||
} | ||
/** | ||
* Check if ws is connected | ||
*/ | ||
isConnected() { | ||
return this._ws && this._ws.readyState === 1; | ||
} | ||
/** | ||
* Check if ws is in closing state | ||
*/ | ||
isClosing() { | ||
return this._ws && this._ws.readyState === 2; | ||
} | ||
/** | ||
* Check if ws is closed | ||
*/ | ||
isClosed() { | ||
return this._ws && this._ws.readyState === 3; | ||
} | ||
/** | ||
* Close the connection | ||
*/ | ||
close() { | ||
clearInterval(this._heartbeatInterval); | ||
this._cfg.mustReconnect = false; | ||
if (!this.isClosing() || !this.isClosed()) { | ||
this._ws.close(); | ||
this._cfg.debug && console.error('Websocket closed.'); | ||
} | ||
} | ||
} | ||
exports.default = WSClient; | ||
exports.default = WSClient; | ||
//# sourceMappingURL=websocket.js.map |
"use strict"; | ||
exports.__esModule = true; | ||
exports.getHighestSafeWindowContext = getHighestSafeWindowContext; | ||
exports.getWindowHeight = getWindowHeight; | ||
exports.getWindowWidth = getWindowWidth; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isClientSideRendering = exports.getHighestSafeWindowContext = exports.getWindowHeight = exports.getWindowWidth = void 0; | ||
function getWindowWidth() { | ||
return typeof global.window !== 'undefined' ? global.window.innerWidth : 0; | ||
return typeof global.window !== 'undefined' ? global.window.innerWidth : 0; | ||
} | ||
exports.getWindowWidth = getWindowWidth; | ||
function getWindowHeight() { | ||
return typeof global.window !== 'undefined' ? global.window.innerHeight : 0; | ||
return typeof global.window !== 'undefined' ? global.window.innerHeight : 0; | ||
} | ||
exports.getWindowHeight = getWindowHeight; | ||
const isCrossOriginFrame = () => { | ||
try { | ||
return global.window.location.hostname !== global.window.parent.location.hostname; | ||
} catch (e) { | ||
return true; | ||
} | ||
}; // Get the highest window context that isn't cross-origin | ||
try { | ||
return global.window.location.hostname !== global.window.parent.location.hostname; | ||
} | ||
catch (e) { | ||
return true; | ||
} | ||
}; | ||
// Get the highest window context that isn't cross-origin | ||
// (When in an iframe) | ||
function getHighestSafeWindowContext(self = global.window.self) { | ||
// If we reached the top level, return self | ||
if (self === global.window.top) { | ||
// If we reached the top level, return self | ||
if (self === global.window.top) { | ||
return self; | ||
} | ||
// If parent is the same origin, we can move up one context | ||
// Reference: https://stackoverflow.com/a/21965342/1601953 | ||
if (!isCrossOriginFrame()) { | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore | ||
// @ts-ignore | ||
return getHighestSafeWindowContext(self.parent); | ||
} | ||
// If a different origin, we consider the current level | ||
// as the top reachable one | ||
return self; | ||
} // If parent is the same origin, we can move up one context | ||
// Reference: https://stackoverflow.com/a/21965342/1601953 | ||
if (!isCrossOriginFrame()) { | ||
return getHighestSafeWindowContext(self.parent); | ||
} // If a different origin, we consider the current level | ||
// as the top reachable one | ||
return self; | ||
} | ||
} | ||
exports.getHighestSafeWindowContext = getHighestSafeWindowContext; | ||
function isClientSideRendering() { | ||
return typeof window !== 'undefined'; | ||
} | ||
exports.isClientSideRendering = isClientSideRendering; | ||
//# sourceMappingURL=window.js.map |
@@ -1,51 +0,12 @@ | ||
"use strict"; | ||
exports.__esModule = true; | ||
var _string = require("./utils/string"); | ||
exports.capitalize = _string.capitalize; | ||
exports.isString = _string.isString; | ||
exports.stripHtml = _string.stripHtml; | ||
exports.camelCase = _string.camelCase; | ||
exports.copyTextToClipboard = _string.copyTextToClipboard; | ||
exports.fallbackCopyTextToClipboard = _string.fallbackCopyTextToClipboard; | ||
exports.random = _string.random; | ||
var _url = require("./utils/url"); | ||
exports.isValidUrl = _url.isValidUrl; | ||
exports.isValidUrls = _url.isValidUrls; | ||
exports.urlReplacer = _url.urlReplacer; | ||
exports.getDomain = _url.getDomain; | ||
exports.appendURLSearchParams = _url.appendURLSearchParams; | ||
exports.urlB64ToUint8Array = _url.urlB64ToUint8Array; | ||
var _window = require("./utils/window"); | ||
exports.getHighestSafeWindowContext = _window.getHighestSafeWindowContext; | ||
exports.getWindowWidth = _window.getWindowWidth; | ||
exports.getWindowHeight = _window.getWindowHeight; | ||
var _object = require("./utils/object"); | ||
exports.mergeDeep = _object.mergeDeep; | ||
exports.isObject = _object.isObject; | ||
var _browser = require("./utils/browser"); | ||
exports.loadVersionBrowser = _browser.loadVersionBrowser; | ||
var _logger = require("./utils/logger"); | ||
exports.Logger = _logger.Logger; | ||
var _websocket = _interopRequireWildcard(require("./utils/websocket")); | ||
exports.WSClient = _websocket.default; | ||
exports.WSClientType = _websocket.WSClientType; | ||
exports.WSClientPropTypes = _websocket.WSClientPropTypes; | ||
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } | ||
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } | ||
import { capitalize, isString, stripHtml, camelCase, copyTextToClipboard, fallbackCopyTextToClipboard, random } from './utils/string'; | ||
import { isValidUrl, isValidUrls, urlReplacer, getDomain, appendURLSearchParams, urlB64ToUint8Array } from './utils/url'; | ||
import { getHighestSafeWindowContext, getWindowWidth, getWindowHeight, isClientSideRendering } from './utils/window'; | ||
import { mergeDeep, isObject } from './utils/object'; | ||
import { loadVersionBrowser } from './utils/browser'; | ||
import { Logger } from './utils/logger'; | ||
import WSClient from './utils/websocket'; | ||
/** | ||
* Export all utilities | ||
*/ | ||
export { capitalize, isString, stripHtml, camelCase, copyTextToClipboard, fallbackCopyTextToClipboard, random, isValidUrl, isValidUrls, urlReplacer, getDomain, appendURLSearchParams, urlB64ToUint8Array, getHighestSafeWindowContext, getWindowWidth, getWindowHeight, isClientSideRendering, Logger, mergeDeep, isObject, WSClient, loadVersionBrowser }; | ||
//# sourceMappingURL=index.js.map |
@@ -1,6 +0,1 @@ | ||
"use strict"; | ||
exports.__esModule = true; | ||
exports.loadVersionBrowser = void 0; | ||
/** | ||
@@ -10,82 +5,67 @@ * Get browser version to track on backend | ||
*/ | ||
const loadVersionBrowser = () => { | ||
if ('userAgentData' in navigator) { | ||
// navigator.userAgentData is not available in | ||
// Firefox and Safari | ||
const uaData = navigator['userAgentData']; // Outputs of navigator.userAgentData.brands[n].brand are e.g. | ||
// Chrome: 'Google Chrome' | ||
// Edge: 'Microsoft Edge' | ||
// Opera: 'Opera' | ||
let browsername; | ||
let browserversion; | ||
let chromeVersion = null; | ||
for (let i = 0; i < uaData['brands'].length; i++) { | ||
const brand = uaData['brands'][i].brand; | ||
browserversion = uaData['brands'][i].version; | ||
if (brand.match(/opera|chrome|edge|safari|firefox|msie|trident/i) !== null) { | ||
// If we have a chrome match, save the match, but try to find another match | ||
// E.g. Edge can also produce a false Chrome match. | ||
if (brand.match(/chrome/i) !== null) { | ||
chromeVersion = browserversion; | ||
} // If this is not a chrome match return immediately | ||
else { | ||
browsername = brand.substr(brand.indexOf(' ') + 1); | ||
return { | ||
name: browsername, | ||
version: browserversion | ||
}; | ||
export const loadVersionBrowser = () => { | ||
if ('userAgentData' in navigator) { | ||
// navigator.userAgentData is not available in | ||
// Firefox and Safari | ||
const uaData = navigator['userAgentData']; | ||
// Outputs of navigator.userAgentData.brands[n].brand are e.g. | ||
// Chrome: 'Google Chrome' | ||
// Edge: 'Microsoft Edge' | ||
// Opera: 'Opera' | ||
let browsername; | ||
let browserversion; | ||
let chromeVersion = null; | ||
for (let i = 0; i < uaData['brands'].length; i++) { | ||
const brand = uaData['brands'][i].brand; | ||
browserversion = uaData['brands'][i].version; | ||
if (brand.match(/opera|chrome|edge|safari|firefox|msie|trident/i) !== null) { | ||
// If we have a chrome match, save the match, but try to find another match | ||
// E.g. Edge can also produce a false Chrome match. | ||
if (brand.match(/chrome/i) !== null) { | ||
chromeVersion = browserversion; | ||
} | ||
// If this is not a chrome match return immediately | ||
else { | ||
browsername = brand.substr(brand.indexOf(' ') + 1); | ||
return { | ||
name: browsername, | ||
version: browserversion, | ||
}; | ||
} | ||
} | ||
} | ||
} | ||
} // No non-Chrome match was found. If we have a chrome match, return it. | ||
if (chromeVersion !== null) { | ||
return { | ||
name: 'chrome', | ||
version: chromeVersion | ||
}; | ||
// No non-Chrome match was found. If we have a chrome match, return it. | ||
if (chromeVersion !== null) { | ||
return { | ||
name: 'chrome', | ||
version: chromeVersion, | ||
}; | ||
} | ||
} | ||
} // If no userAgentData is not present, or if no match via userAgentData was found, | ||
// try to extract the browser name and version from userAgent | ||
const userAgent = navigator.userAgent; | ||
let ua = userAgent; | ||
let tem; | ||
let M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; | ||
if (/trident/i.test(M[1])) { | ||
tem = /\brv[ :]+(\d+)/g.exec(ua) || []; | ||
// If no userAgentData is not present, or if no match via userAgentData was found, | ||
// try to extract the browser name and version from userAgent | ||
const userAgent = navigator.userAgent; | ||
let ua = userAgent; | ||
let tem; | ||
let M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; | ||
if (/trident/i.test(M[1])) { | ||
tem = /\brv[ :]+(\d+)/g.exec(ua) || []; | ||
return { name: 'IE', version: tem[1] || '' }; | ||
} | ||
if (M[1] === 'Chrome') { | ||
tem = ua.match(/\bOPR\/(\d+)/); | ||
if (tem != null) { | ||
return { name: 'Opera', version: tem[1] }; | ||
} | ||
} | ||
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?']; | ||
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec | ||
if ((tem = ua.match(/version\/(\d+)/i)) != null) { | ||
M.splice(1, 1, tem[1]); | ||
} | ||
return { | ||
name: 'IE', | ||
version: tem[1] || '' | ||
name: M[0], | ||
version: M[1], | ||
}; | ||
} | ||
if (M[1] === 'Chrome') { | ||
tem = ua.match(/\bOPR\/(\d+)/); | ||
if (tem != null) { | ||
return { | ||
name: 'Opera', | ||
version: tem[1] | ||
}; | ||
} | ||
} | ||
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?']; // eslint-disable-next-line @typescript-eslint/prefer-regexp-exec | ||
if ((tem = ua.match(/version\/(\d+)/i)) != null) { | ||
M.splice(1, 1, tem[1]); | ||
} | ||
return { | ||
name: M[0], | ||
version: M[1] | ||
}; | ||
}; | ||
exports.loadVersionBrowser = loadVersionBrowser; | ||
//# sourceMappingURL=browser.js.map |
@@ -1,32 +0,21 @@ | ||
"use strict"; | ||
exports.__esModule = true; | ||
exports.Logger = void 0; | ||
/** | ||
* Emit styled message | ||
*/ | ||
class Logger { | ||
static info(scope, message) { | ||
console.info(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static warn(scope, message) { | ||
console.warn(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static error(scope, message) { | ||
console.error(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static log(scope, message) { | ||
console.log(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static debug(scope, message) { | ||
console.debug(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
export class Logger { | ||
static info(scope, message) { | ||
console.info(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static warn(scope, message) { | ||
console.warn(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static error(scope, message) { | ||
console.error(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static log(scope, message) { | ||
console.log(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
static debug(scope, message) { | ||
console.debug(`%c[${scope}]`, 'color:#008080', ` ${message}`); | ||
} | ||
} | ||
exports.Logger = Logger; | ||
//# sourceMappingURL=logger.js.map |
@@ -1,7 +0,1 @@ | ||
"use strict"; | ||
exports.__esModule = true; | ||
exports.isObject = isObject; | ||
exports.mergeDeep = mergeDeep; | ||
/** | ||
@@ -11,4 +5,4 @@ * Check if v is an object | ||
*/ | ||
function isObject(v) { | ||
return typeof v === 'object' && !Array.isArray(v) && v !== null; | ||
export function isObject(v) { | ||
return typeof v === 'object' && !Array.isArray(v) && v !== null; | ||
} | ||
@@ -21,26 +15,21 @@ /** | ||
*/ | ||
function mergeDeep(target, source) { | ||
let output = Object.assign({}, target); | ||
if (isObject(target) && isObject(source)) { | ||
Object.keys(source).forEach(key => { | ||
if (isObject(source[key])) { | ||
if (!(key in target)) { | ||
Object.assign(output, { | ||
[key]: source[key] | ||
}); | ||
} else { | ||
output[key] = mergeDeep(target[key], source[key]); | ||
} | ||
} else { | ||
Object.assign(output, { | ||
[key]: source[key] | ||
export function mergeDeep(target, source) { | ||
let output = Object.assign({}, target); | ||
if (isObject(target) && isObject(source)) { | ||
Object.keys(source).forEach((key) => { | ||
if (isObject(source[key])) { | ||
if (!(key in target)) { | ||
Object.assign(output, { [key]: source[key] }); | ||
} | ||
else { | ||
output[key] = mergeDeep(target[key], source[key]); | ||
} | ||
} | ||
else { | ||
Object.assign(output, { [key]: source[key] }); | ||
} | ||
}); | ||
} | ||
}); | ||
} | ||
return output; | ||
} | ||
} | ||
return output; | ||
} | ||
//# sourceMappingURL=object.js.map |
@@ -1,12 +0,1 @@ | ||
"use strict"; | ||
exports.__esModule = true; | ||
exports.camelCase = camelCase; | ||
exports.capitalize = capitalize; | ||
exports.copyTextToClipboard = copyTextToClipboard; | ||
exports.fallbackCopyTextToClipboard = fallbackCopyTextToClipboard; | ||
exports.isString = isString; | ||
exports.random = random; | ||
exports.stripHtml = stripHtml; | ||
/** | ||
@@ -16,4 +5,4 @@ * Check if v is a string | ||
*/ | ||
function isString(v) { | ||
return typeof v === 'string' || v instanceof String; | ||
export function isString(v) { | ||
return typeof v === 'string' || v instanceof String; | ||
} | ||
@@ -24,13 +13,9 @@ /** | ||
*/ | ||
function capitalize(str) { | ||
let strVal = ''; | ||
let strArr = str.split(' '); | ||
for (let chr = 0; chr < strArr.length; chr++) { | ||
strVal += strArr[chr].substring(0, 1).toUpperCase() + strArr[chr].substring(1, strArr[chr].length); | ||
} | ||
return strVal; | ||
export function capitalize(str) { | ||
let strVal = ''; | ||
let strArr = str.split(' '); | ||
for (let chr = 0; chr < strArr.length; chr++) { | ||
strVal += strArr[chr].substring(0, 1).toUpperCase() + strArr[chr].substring(1, strArr[chr].length); | ||
} | ||
return strVal; | ||
} | ||
@@ -41,14 +26,17 @@ /** | ||
*/ | ||
function camelCase(str) { | ||
// Lower cases the string | ||
return str.toLowerCase() // Replaces any - or _ characters with a space | ||
.replace(/[-_]+/g, ' ') // Removes any non alphanumeric characters | ||
.replace(/[^\w\s]/g, '') // Uppercases the first character in each group immediately following a space | ||
// (delimited by spaces) | ||
.replace(/ (.)/g, $1 => { | ||
return $1.toUpperCase(); | ||
}) // Removes spaces | ||
.replace(/ /g, ''); | ||
export function camelCase(str) { | ||
// Lower cases the string | ||
return (str | ||
.toLowerCase() | ||
// Replaces any - or _ characters with a space | ||
.replace(/[-_]+/g, ' ') | ||
// Removes any non alphanumeric characters | ||
.replace(/[^\w\s]/g, '') | ||
// Uppercases the first character in each group immediately following a space | ||
// (delimited by spaces) | ||
.replace(/ (.)/g, ($1) => { | ||
return $1.toUpperCase(); | ||
}) | ||
// Removes spaces | ||
.replace(/ /g, '')); | ||
} | ||
@@ -59,10 +47,7 @@ /** | ||
*/ | ||
function stripHtml(str) { | ||
return str.replace(/<[^>]*>?/gm, '').trim(); | ||
export function stripHtml(str) { | ||
return str.replace(/<[^>]*>?/gm, '').trim(); | ||
} | ||
function random() { | ||
return (Math.random() + 1).toString(36).substring(7); | ||
export function random() { | ||
return (Math.random() + 1).toString(36).substring(7); | ||
} | ||
@@ -74,23 +59,21 @@ /** | ||
*/ | ||
function fallbackCopyTextToClipboard(text) { | ||
let textArea = document.createElement('textarea'); | ||
textArea.value = text; // Avoid scrolling to bottom | ||
textArea.style.top = '0'; | ||
textArea.style.left = '0'; | ||
textArea.style.position = 'fixed'; | ||
document.body.appendChild(textArea); | ||
textArea.focus(); | ||
textArea.select(); | ||
try { | ||
document.execCommand('copy'); | ||
document.body.removeChild(textArea); | ||
return Promise.resolve(); | ||
} catch (err) { | ||
document.body.removeChild(textArea); | ||
return Promise.reject(err); | ||
} | ||
export function fallbackCopyTextToClipboard(text) { | ||
let textArea = document.createElement('textarea'); | ||
textArea.value = text; | ||
// Avoid scrolling to bottom | ||
textArea.style.top = '0'; | ||
textArea.style.left = '0'; | ||
textArea.style.position = 'fixed'; | ||
document.body.appendChild(textArea); | ||
textArea.focus(); | ||
textArea.select(); | ||
try { | ||
document.execCommand('copy'); | ||
document.body.removeChild(textArea); | ||
return Promise.resolve(); | ||
} | ||
catch (err) { | ||
document.body.removeChild(textArea); | ||
return Promise.reject(err); | ||
} | ||
} | ||
@@ -111,10 +94,8 @@ /** | ||
*/ | ||
function copyTextToClipboard(text) { | ||
if (!navigator.clipboard) { | ||
return fallbackCopyTextToClipboard(text); | ||
} | ||
return navigator.clipboard.writeText(text); | ||
} | ||
export function copyTextToClipboard(text) { | ||
if (!navigator.clipboard) { | ||
return fallbackCopyTextToClipboard(text); | ||
} | ||
return navigator.clipboard.writeText(text); | ||
} | ||
//# sourceMappingURL=string.js.map |
@@ -1,7 +0,1 @@ | ||
"use strict"; | ||
exports.__esModule = true; | ||
exports.appendURLSearchParams = appendURLSearchParams; | ||
exports.urlReplacer = exports.urlB64ToUint8Array = exports.isValidUrls = exports.isValidUrl = exports.getDomain = void 0; | ||
/** | ||
@@ -11,17 +5,14 @@ * Utility Url Replacer | ||
*/ | ||
const urlReplacer = path => { | ||
const replacer = function replacer(tpl, data) { | ||
const re = /\$\(([^)]+)?\)/g; | ||
let match = re.exec(tpl); | ||
while (match) { | ||
tpl = tpl.replace(match[0], data[match[1]]); | ||
re.lastIndex = 0; | ||
match = re.exec(tpl); | ||
} | ||
return tpl; | ||
}; | ||
return params => replacer(path, params); | ||
export const urlReplacer = (path) => { | ||
const replacer = function (tpl, data) { | ||
const re = /\$\(([^)]+)?\)/g; | ||
let match = re.exec(tpl); | ||
while (match) { | ||
tpl = tpl.replace(match[0], data[match[1]]); | ||
re.lastIndex = 0; | ||
match = re.exec(tpl); | ||
} | ||
return tpl; | ||
}; | ||
return (params) => replacer(path, params); | ||
}; | ||
@@ -32,15 +23,9 @@ /** | ||
*/ | ||
exports.urlReplacer = urlReplacer; | ||
const getDomain = url => { | ||
// eslint-disable-next-line no-useless-escape,@typescript-eslint/prefer-regexp-exec | ||
const matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i); | ||
if (matches && matches[1]) { | ||
return matches[1]; | ||
} | ||
return ''; | ||
export const getDomain = (url) => { | ||
// eslint-disable-next-line no-useless-escape,@typescript-eslint/prefer-regexp-exec | ||
const matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i); | ||
if (matches && matches[1]) { | ||
return matches[1]; | ||
} | ||
return ''; | ||
}; | ||
@@ -51,9 +36,5 @@ /** | ||
*/ | ||
exports.getDomain = getDomain; | ||
const isValidUrl = url => { | ||
const regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/; | ||
return regexp.test(url); | ||
export const isValidUrl = (url) => { | ||
const regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/; | ||
return regexp.test(url); | ||
}; | ||
@@ -65,9 +46,5 @@ /** | ||
*/ | ||
exports.isValidUrl = isValidUrl; | ||
const isValidUrls = (value, delimiter) => { | ||
const urls = value.trim().split(delimiter); | ||
return urls.every(isValidUrl); | ||
export const isValidUrls = (value, delimiter) => { | ||
const urls = value.trim().split(delimiter); | ||
return urls.every(isValidUrl); | ||
}; | ||
@@ -79,19 +56,13 @@ /** | ||
*/ | ||
exports.isValidUrls = isValidUrls; | ||
function appendURLSearchParams(baseUrl, queryParams) { | ||
let _url = baseUrl; | ||
if (queryParams.length && _url) { | ||
const key = Object.keys(queryParams[0])[0]; | ||
_url += (_url.split('?')[1] ? '&' : '?') + `${key}=${queryParams[0][key]}`; | ||
queryParams.slice(1).map(p => { | ||
const key = Object.keys(p)[0]; | ||
_url += `&${key}=${p[key]}`; | ||
}); | ||
} | ||
return _url; | ||
export function appendURLSearchParams(baseUrl, queryParams) { | ||
let _url = baseUrl; | ||
if (queryParams.length && _url) { | ||
const key = Object.keys(queryParams[0])[0]; | ||
_url += (_url.split('?')[1] ? '&' : '?') + `${key}=${queryParams[0][key]}`; | ||
queryParams.slice(1).map((p) => { | ||
const key = Object.keys(p)[0]; | ||
_url += `&${key}=${p[key]}`; | ||
}); | ||
} | ||
return _url; | ||
} | ||
@@ -102,17 +73,12 @@ /** | ||
*/ | ||
const urlB64ToUint8Array = base64String => { | ||
const padding = '='.repeat((4 - base64String.length % 4) % 4); | ||
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/'); | ||
const rawData = window.atob(base64); | ||
const outputArray = new Uint8Array(rawData.length); | ||
for (let i = 0; i < rawData.length; ++i) { | ||
outputArray[i] = rawData.charCodeAt(i); | ||
} | ||
return outputArray; | ||
export const urlB64ToUint8Array = (base64String) => { | ||
const padding = '='.repeat((4 - (base64String.length % 4)) % 4); | ||
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/'); | ||
const rawData = window.atob(base64); | ||
const outputArray = new Uint8Array(rawData.length); | ||
for (let i = 0; i < rawData.length; ++i) { | ||
outputArray[i] = rawData.charCodeAt(i); | ||
} | ||
return outputArray; | ||
}; | ||
exports.urlB64ToUint8Array = urlB64ToUint8Array; | ||
//# sourceMappingURL=url.js.map |
@@ -1,11 +0,2 @@ | ||
"use strict"; | ||
exports.__esModule = true; | ||
exports.default = void 0; | ||
/** | ||
* WSClientPropTypes interface | ||
*/ | ||
/** | ||
* WSClient: manage socket connection | ||
@@ -15,294 +6,237 @@ * @param options | ||
*/ | ||
class WSClient { | ||
/** | ||
* Constructor | ||
* @param cfg | ||
*/ | ||
constructor(cfg) { | ||
this._attempts = 1; | ||
this._heartbeatInterval = null; | ||
this._missedHeartbeats = 0; | ||
if (!this.isValidOptions(cfg)) { | ||
return; | ||
export default class WSClient { | ||
/** | ||
* Constructor | ||
* @param cfg | ||
*/ | ||
constructor(cfg) { | ||
this._attempts = 1; | ||
this._heartbeatInterval = null; | ||
this._missedHeartbeats = 0; | ||
if (!this.isValidOptions(cfg)) { | ||
return; | ||
} | ||
this._cfg = Object.assign({}, { heartbeatMsg: null, debug: false, mustReconnect: true }, cfg); | ||
this.connect(); | ||
} | ||
this._cfg = Object.assign({}, { | ||
heartbeatMsg: null, | ||
debug: false, | ||
mustReconnect: true | ||
}, cfg); | ||
this.connect(); | ||
} | ||
/** | ||
* Get instance | ||
*/ | ||
static getInstance(cfg) { | ||
this._instance = this._instance || new WSClient(cfg); | ||
return this._instance; | ||
} | ||
/** | ||
* Connect | ||
*/ | ||
connect() { | ||
try { | ||
if (this._ws && (this.isConnecting() || this.isConnected())) { | ||
// There is already a connection | ||
this._cfg.debug && console.info('Websocket is connecting or already connected.'); | ||
return; | ||
} // Callback 'connecting' if exist | ||
typeof this._cfg.connecting === 'function' && this._cfg.connecting(); | ||
this._cfg.debug && console.info(`Connecting to ${this._cfg.uri} ...`); // Open the connection | ||
this._ws = new WebSocket(this._cfg.uri, this._cfg.protocols); | ||
this._ws.onopen = this.onOpen.bind(this); | ||
this._ws.onmessage = this.onMessage.bind(this); | ||
this._ws.onerror = this.onError.bind(this); | ||
this._ws.onclose = this.onClose.bind(this); | ||
this._timer = null; | ||
} catch (err) { | ||
console.error(err); | ||
this.tryToReconnect(); | ||
/** | ||
* Get instance | ||
*/ | ||
static getInstance(cfg) { | ||
this._instance = this._instance || new WSClient(cfg); | ||
return this._instance; | ||
} | ||
} | ||
/** | ||
* Validate options | ||
* @param cfg | ||
*/ | ||
isValidOptions(cfg) { | ||
let _error = false; | ||
if (!cfg) { | ||
console.error('Invalid WSClient options.'); | ||
return _error; | ||
/** | ||
* Connect | ||
*/ | ||
connect() { | ||
try { | ||
if (this._ws && (this.isConnecting() || this.isConnected())) { | ||
// There is already a connection | ||
this._cfg.debug && console.info('Websocket is connecting or already connected.'); | ||
return; | ||
} | ||
// Callback 'connecting' if exist | ||
typeof this._cfg.connecting === 'function' && this._cfg.connecting(); | ||
this._cfg.debug && console.info(`Connecting to ${this._cfg.uri} ...`); | ||
// Open the connection | ||
this._ws = new WebSocket(this._cfg.uri, this._cfg.protocols); | ||
this._ws.onopen = this.onOpen.bind(this); | ||
this._ws.onmessage = this.onMessage.bind(this); | ||
this._ws.onerror = this.onError.bind(this); | ||
this._ws.onclose = this.onClose.bind(this); | ||
this._timer = null; | ||
} | ||
catch (err) { | ||
console.error(err); | ||
this.tryToReconnect(); | ||
} | ||
} | ||
if (!cfg.uri) { | ||
console.error('Invalid WSClient Uri options.'); | ||
_error = true; | ||
/** | ||
* Validate options | ||
* @param cfg | ||
*/ | ||
isValidOptions(cfg) { | ||
let _error = false; | ||
if (!cfg) { | ||
console.error('Invalid WSClient options.'); | ||
return _error; | ||
} | ||
if (!cfg.uri) { | ||
console.error('Invalid WSClient Uri options.'); | ||
_error = true; | ||
} | ||
if (cfg && cfg.connecting && !(typeof cfg.connecting === 'function')) { | ||
console.error('Invalid WSClient connecting options.'); | ||
_error = true; | ||
} | ||
if (cfg && cfg.connected && !(typeof cfg.connected === 'function')) { | ||
console.error('Invalid WSClient connected options.'); | ||
_error = true; | ||
} | ||
if (cfg && cfg.receiveMessage && !(typeof cfg.receiveMessage === 'function')) { | ||
console.error('Invalid WSClient receiveMessage options.'); | ||
_error = true; | ||
} | ||
if (cfg && cfg.disconnected && !(typeof cfg.disconnected === 'function')) { | ||
console.error('Invalid WSClient connecting options.'); | ||
_error = true; | ||
} | ||
if (cfg && cfg.heartbeatMsg && !(typeof cfg.heartbeatMsg === 'string')) { | ||
console.error('Invalid WSClient heartbeatMsg options.'); | ||
_error = true; | ||
} | ||
if (cfg && cfg.debug && !(typeof cfg.debug === 'boolean')) { | ||
console.error('Invalid WSClient debug options.'); | ||
_error = true; | ||
} | ||
return !_error; | ||
} | ||
if (cfg && cfg.connecting && !(typeof cfg.connecting === 'function')) { | ||
console.error('Invalid WSClient connecting options.'); | ||
_error = true; | ||
/** | ||
* Try to reconnect if previous connection failed | ||
* Generate an interval, after that try to reconnect | ||
*/ | ||
tryToReconnect() { | ||
if (this._cfg.mustReconnect && !this._timer) { | ||
this._cfg.debug && console.info(`Reconnecting...`); | ||
let interval = this.generateInteval(this._attempts); | ||
this._timer = setTimeout(this.reconnect.bind(this), interval); | ||
} | ||
} | ||
if (cfg && cfg.connected && !(typeof cfg.connected === 'function')) { | ||
console.error('Invalid WSClient connected options.'); | ||
_error = true; | ||
/** | ||
* Reestablish the connection | ||
* Increase the number of attempts | ||
*/ | ||
reconnect() { | ||
this._attempts++; | ||
this.connect(); | ||
} | ||
if (cfg && cfg.receiveMessage && !(typeof cfg.receiveMessage === 'function')) { | ||
console.error('Invalid WSClient receiveMessage options.'); | ||
_error = true; | ||
/** | ||
* Send heartbeat every 5 seconds | ||
* If missing more than 3 heartbeats close connection | ||
*/ | ||
sendHeartbeat() { | ||
try { | ||
this._missedHeartbeats++; | ||
if (this._missedHeartbeats > 3) | ||
throw new Error('Too many missed heartbeats.'); | ||
this._ws.send(this._cfg.heartbeatMsg); | ||
} | ||
catch (e) { | ||
clearInterval(this._heartbeatInterval); | ||
this._heartbeatInterval = null; | ||
this._cfg.debug && console.warn(`Closing connection. Reason: ${e.message}`); | ||
if (!this.isClosing() && !this.isClosed()) { | ||
this.close(); | ||
} | ||
} | ||
} | ||
if (cfg && cfg.disconnected && !(typeof cfg.disconnected === 'function')) { | ||
console.error('Invalid WSClient connecting options.'); | ||
_error = true; | ||
/** | ||
* Established the new connection | ||
* Reset this._attempts counter | ||
*/ | ||
onOpen() { | ||
this._cfg.debug && console.info('Connected!'); | ||
this._attempts = 1; | ||
if (this._cfg.heartbeatMsg && this._heartbeatInterval === null) { | ||
this._missedHeartbeats = 0; | ||
this._heartbeatInterval = setInterval(this.sendHeartbeat.bind(this), 5000); | ||
} | ||
typeof this._cfg.connected === 'function' && this._cfg.connected(); | ||
} | ||
if (cfg && cfg.heartbeatMsg && !(typeof cfg.heartbeatMsg === 'string')) { | ||
console.error('Invalid WSClient heartbeatMsg options.'); | ||
_error = true; | ||
/** | ||
* Connection closed. Try to reconnect. | ||
* @param evt | ||
*/ | ||
onClose(evt) { | ||
this._cfg.debug && console.info('Connection closed!'); | ||
typeof this._cfg.disconnected === 'function' && this._cfg.disconnected(evt); | ||
this.tryToReconnect(); | ||
} | ||
if (cfg && cfg.debug && !(typeof cfg.debug === 'boolean')) { | ||
console.error('Invalid WSClient debug options.'); | ||
_error = true; | ||
/** | ||
* An error occured | ||
* @param evt | ||
*/ | ||
onError(evt) { | ||
this._cfg.debug && console.error('Websocket connection is broken!'); | ||
this._cfg.debug && console.error(evt); | ||
} | ||
return !_error; | ||
} | ||
/** | ||
* Try to reconnect if previous connection failed | ||
* Generate an interval, after that try to reconnect | ||
*/ | ||
tryToReconnect() { | ||
if (this._cfg.mustReconnect && !this._timer) { | ||
this._cfg.debug && console.info(`Reconnecting...`); | ||
let interval = this.generateInteval(this._attempts); | ||
this._timer = setTimeout(this.reconnect.bind(this), interval); | ||
/** | ||
* A message has arrived. | ||
* If it is the heartbeat -> reset this._missedHeartbeats | ||
* If it is data pass data to the callback | ||
* @param evt | ||
*/ | ||
onMessage(evt) { | ||
if (this._cfg.heartbeatMsg && evt.data === this._cfg.heartbeatMsg) { | ||
// reset the counter for missed heartbeats | ||
this._missedHeartbeats = 0; | ||
} | ||
else if (typeof this._cfg.receiveMessage === 'function') { | ||
return this._cfg.receiveMessage(evt.data); | ||
} | ||
} | ||
} | ||
/** | ||
* Reestablish the connection | ||
* Increase the number of attempts | ||
*/ | ||
reconnect() { | ||
this._attempts++; | ||
this.connect(); | ||
} | ||
/** | ||
* Send heartbeat every 5 seconds | ||
* If missing more than 3 heartbeats close connection | ||
*/ | ||
sendHeartbeat() { | ||
try { | ||
this._missedHeartbeats++; | ||
if (this._missedHeartbeats > 3) throw new Error('Too many missed heartbeats.'); | ||
this._ws.send(this._cfg.heartbeatMsg); | ||
} catch (e) { | ||
clearInterval(this._heartbeatInterval); | ||
this._heartbeatInterval = null; | ||
this._cfg.debug && console.warn(`Closing connection. Reason: ${e.message}`); | ||
if (!this.isClosing() && !this.isClosed()) { | ||
this.close(); | ||
} | ||
/** | ||
* Generate an interval that is randomly between 0 and 2^k - 1, where k is | ||
* the number of connection attmpts, with a maximum interval of 30 seconds, | ||
* so it starts at 0 - 1 seconds and maxes out at 0 - 30 seconds | ||
*/ | ||
generateInteval(k) { | ||
let maxInterval = (Math.pow(2, k) - 1) * 1000; | ||
// If the generated interval is more than 30 seconds, truncate it down to 30 seconds. | ||
if (maxInterval > 30 * 1000) { | ||
maxInterval = 30 * 1000; | ||
} | ||
// generate the interval to a random number between 0 and the maxInterval determined from above | ||
return Math.random() * maxInterval; | ||
} | ||
} | ||
/** | ||
* Established the new connection | ||
* Reset this._attempts counter | ||
*/ | ||
onOpen() { | ||
this._cfg.debug && console.info('Connected!'); | ||
this._attempts = 1; | ||
if (this._cfg.heartbeatMsg && this._heartbeatInterval === null) { | ||
this._missedHeartbeats = 0; | ||
this._heartbeatInterval = setInterval(this.sendHeartbeat.bind(this), 5000); | ||
/** | ||
* Send message | ||
* @param message | ||
*/ | ||
sendMessage(message) { | ||
this._ws && this._ws.send(message); | ||
} | ||
typeof this._cfg.connected === 'function' && this._cfg.connected(); | ||
} | ||
/** | ||
* Connection closed. Try to reconnect. | ||
* @param evt | ||
*/ | ||
onClose(evt) { | ||
this._cfg.debug && console.info('Connection closed!'); | ||
typeof this._cfg.disconnected === 'function' && this._cfg.disconnected(evt); | ||
this.tryToReconnect(); | ||
} | ||
/** | ||
* An error occured | ||
* @param evt | ||
*/ | ||
onError(evt) { | ||
this._cfg.debug && console.error('Websocket connection is broken!'); | ||
this._cfg.debug && console.error(evt); | ||
} | ||
/** | ||
* A message has arrived. | ||
* If it is the heartbeat -> reset this._missedHeartbeats | ||
* If it is data pass data to the callback | ||
* @param evt | ||
*/ | ||
onMessage(evt) { | ||
if (this._cfg.heartbeatMsg && evt.data === this._cfg.heartbeatMsg) { | ||
// reset the counter for missed heartbeats | ||
this._missedHeartbeats = 0; | ||
} else if (typeof this._cfg.receiveMessage === 'function') { | ||
return this._cfg.receiveMessage(evt.data); | ||
/** | ||
* Get the ws state | ||
*/ | ||
getState() { | ||
return this._ws && this._ws.readyState; | ||
} | ||
} | ||
/** | ||
* Generate an interval that is randomly between 0 and 2^k - 1, where k is | ||
* the number of connection attmpts, with a maximum interval of 30 seconds, | ||
* so it starts at 0 - 1 seconds and maxes out at 0 - 30 seconds | ||
*/ | ||
generateInteval(k) { | ||
let maxInterval = (Math.pow(2, k) - 1) * 1000; // If the generated interval is more than 30 seconds, truncate it down to 30 seconds. | ||
if (maxInterval > 30 * 1000) { | ||
maxInterval = 30 * 1000; | ||
} // generate the interval to a random number between 0 and the maxInterval determined from above | ||
return Math.random() * maxInterval; | ||
} | ||
/** | ||
* Send message | ||
* @param message | ||
*/ | ||
sendMessage(message) { | ||
this._ws && this._ws.send(message); | ||
} | ||
/** | ||
* Get the ws state | ||
*/ | ||
getState() { | ||
return this._ws && this._ws.readyState; | ||
} | ||
/** | ||
* Check if ws is in connecting state | ||
*/ | ||
isConnecting() { | ||
return this._ws && this._ws.readyState === 0; | ||
} | ||
/** | ||
* Check if ws is connected | ||
*/ | ||
isConnected() { | ||
return this._ws && this._ws.readyState === 1; | ||
} | ||
/** | ||
* Check if ws is in closing state | ||
*/ | ||
isClosing() { | ||
return this._ws && this._ws.readyState === 2; | ||
} | ||
/** | ||
* Check if ws is closed | ||
*/ | ||
isClosed() { | ||
return this._ws && this._ws.readyState === 3; | ||
} | ||
/** | ||
* Close the connection | ||
*/ | ||
close() { | ||
clearInterval(this._heartbeatInterval); | ||
this._cfg.mustReconnect = false; | ||
if (!this.isClosing() || !this.isClosed()) { | ||
this._ws.close(); | ||
this._cfg.debug && console.error('Websocket closed.'); | ||
/** | ||
* Check if ws is in connecting state | ||
*/ | ||
isConnecting() { | ||
return this._ws && this._ws.readyState === 0; | ||
} | ||
} | ||
/** | ||
* Check if ws is connected | ||
*/ | ||
isConnected() { | ||
return this._ws && this._ws.readyState === 1; | ||
} | ||
/** | ||
* Check if ws is in closing state | ||
*/ | ||
isClosing() { | ||
return this._ws && this._ws.readyState === 2; | ||
} | ||
/** | ||
* Check if ws is closed | ||
*/ | ||
isClosed() { | ||
return this._ws && this._ws.readyState === 3; | ||
} | ||
/** | ||
* Close the connection | ||
*/ | ||
close() { | ||
clearInterval(this._heartbeatInterval); | ||
this._cfg.mustReconnect = false; | ||
if (!this.isClosing() || !this.isClosed()) { | ||
this._ws.close(); | ||
this._cfg.debug && console.error('Websocket closed.'); | ||
} | ||
} | ||
} | ||
exports.default = WSClient; | ||
//# sourceMappingURL=websocket.js.map |
@@ -1,41 +0,36 @@ | ||
"use strict"; | ||
exports.__esModule = true; | ||
exports.getHighestSafeWindowContext = getHighestSafeWindowContext; | ||
exports.getWindowHeight = getWindowHeight; | ||
exports.getWindowWidth = getWindowWidth; | ||
function getWindowWidth() { | ||
return typeof global.window !== 'undefined' ? global.window.innerWidth : 0; | ||
export function getWindowWidth() { | ||
return typeof global.window !== 'undefined' ? global.window.innerWidth : 0; | ||
} | ||
function getWindowHeight() { | ||
return typeof global.window !== 'undefined' ? global.window.innerHeight : 0; | ||
export function getWindowHeight() { | ||
return typeof global.window !== 'undefined' ? global.window.innerHeight : 0; | ||
} | ||
const isCrossOriginFrame = () => { | ||
try { | ||
return global.window.location.hostname !== global.window.parent.location.hostname; | ||
} catch (e) { | ||
return true; | ||
} | ||
}; // Get the highest window context that isn't cross-origin | ||
try { | ||
return global.window.location.hostname !== global.window.parent.location.hostname; | ||
} | ||
catch (e) { | ||
return true; | ||
} | ||
}; | ||
// Get the highest window context that isn't cross-origin | ||
// (When in an iframe) | ||
function getHighestSafeWindowContext(self = global.window.self) { | ||
// If we reached the top level, return self | ||
if (self === global.window.top) { | ||
export function getHighestSafeWindowContext(self = global.window.self) { | ||
// If we reached the top level, return self | ||
if (self === global.window.top) { | ||
return self; | ||
} | ||
// If parent is the same origin, we can move up one context | ||
// Reference: https://stackoverflow.com/a/21965342/1601953 | ||
if (!isCrossOriginFrame()) { | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore | ||
// @ts-ignore | ||
return getHighestSafeWindowContext(self.parent); | ||
} | ||
// If a different origin, we consider the current level | ||
// as the top reachable one | ||
return self; | ||
} // If parent is the same origin, we can move up one context | ||
// Reference: https://stackoverflow.com/a/21965342/1601953 | ||
if (!isCrossOriginFrame()) { | ||
return getHighestSafeWindowContext(self.parent); | ||
} // If a different origin, we consider the current level | ||
// as the top reachable one | ||
return self; | ||
} | ||
} | ||
export function isClientSideRendering() { | ||
return typeof window !== 'undefined'; | ||
} | ||
//# sourceMappingURL=window.js.map |
/*! For license information please see utils.js.LICENSE.txt */ | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SelfCommunityUtils=t():e.SelfCommunityUtils=t()}(self,(()=>(()=>{"use strict";var e={285:(e,t)=>{t.__esModule=!0,t.loadVersionBrowser=void 0,t.loadVersionBrowser=()=>{if("userAgentData"in navigator){const e=navigator.userAgentData;let t,n,o=null;for(let i=0;i<e.brands.length;i++){const r=e.brands[i].brand;if(n=e.brands[i].version,null!==r.match(/opera|chrome|edge|safari|firefox|msie|trident/i)){if(null===r.match(/chrome/i))return t=r.substr(r.indexOf(" ")+1),{name:t,version:n};o=n}}if(null!==o)return{name:"chrome",version:o}}let e,t=navigator.userAgent,n=t.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];return/trident/i.test(n[1])?(e=/\brv[ :]+(\d+)/g.exec(t)||[],{name:"IE",version:e[1]||""}):"Chrome"===n[1]&&(e=t.match(/\bOPR\/(\d+)/),null!=e)?{name:"Opera",version:e[1]}:(n=n[2]?[n[1],n[2]]:[navigator.appName,navigator.appVersion,"-?"],null!=(e=t.match(/version\/(\d+)/i))&&n.splice(1,1,e[1]),{name:n[0],version:n[1]})}},502:(e,t)=>{t.__esModule=!0,t.Logger=void 0,t.Logger=class{static info(e,t){console.info(`%c[${e}]`,"color:#008080",` ${t}`)}static warn(e,t){console.warn(`%c[${e}]`,"color:#008080",` ${t}`)}static error(e,t){console.error(`%c[${e}]`,"color:#008080",` ${t}`)}static log(e,t){console.log(`%c[${e}]`,"color:#008080",` ${t}`)}static debug(e,t){console.debug(`%c[${e}]`,"color:#008080",` ${t}`)}}},297:(e,t)=>{function n(e){return"object"==typeof e&&!Array.isArray(e)&&null!==e}t.__esModule=!0,t.isObject=n,t.mergeDeep=function e(t,o){let i=Object.assign({},t);return n(t)&&n(o)&&Object.keys(o).forEach((r=>{n(o[r])?r in t?i[r]=e(t[r],o[r]):Object.assign(i,{[r]:o[r]}):Object.assign(i,{[r]:o[r]})})),i}},884:(e,t)=>{function n(e){let t=document.createElement("textarea");t.value=e,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t),t.focus(),t.select();try{return document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch(e){return document.body.removeChild(t),Promise.reject(e)}}t.__esModule=!0,t.camelCase=function(e){return e.toLowerCase().replace(/[-_]+/g," ").replace(/[^\w\s]/g,"").replace(/ (.)/g,(e=>e.toUpperCase())).replace(/ /g,"")},t.capitalize=function(e){let t="",n=e.split(" ");for(let e=0;e<n.length;e++)t+=n[e].substring(0,1).toUpperCase()+n[e].substring(1,n[e].length);return t},t.copyTextToClipboard=function(e){return navigator.clipboard?navigator.clipboard.writeText(e):n(e)},t.fallbackCopyTextToClipboard=n,t.isString=function(e){return"string"==typeof e||e instanceof String},t.random=function(){return(Math.random()+1).toString(36).substring(7)},t.stripHtml=function(e){return e.replace(/<[^>]*>?/gm,"").trim()}},735:(e,t)=>{t.__esModule=!0,t.appendURLSearchParams=function(e,t){let n=e;if(t.length&&n){const e=Object.keys(t[0])[0];n+=(n.split("?")[1]?"&":"?")+`${e}=${t[0][e]}`,t.slice(1).map((e=>{const t=Object.keys(e)[0];n+=`&${t}=${e[t]}`}))}return n},t.urlReplacer=t.urlB64ToUint8Array=t.isValidUrls=t.isValidUrl=t.getDomain=void 0,t.urlReplacer=e=>t=>function(e,t){const n=/\$\(([^)]+)?\)/g;let o=n.exec(e);for(;o;)e=e.replace(o[0],t[o[1]]),n.lastIndex=0,o=n.exec(e);return e}(e,t),t.getDomain=e=>{const t=e.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);return t&&t[1]?t[1]:""};const n=e=>/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/.test(e);t.isValidUrl=n,t.isValidUrls=(e,t)=>e.trim().split(t).every(n),t.urlB64ToUint8Array=e=>{const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),n=window.atob(t),o=new Uint8Array(n.length);for(let e=0;e<n.length;++e)o[e]=n.charCodeAt(e);return o}},507:(e,t)=>{t.__esModule=!0,t.default=void 0;class n{constructor(e){this._attempts=1,this._heartbeatInterval=null,this._missedHeartbeats=0,this.isValidOptions(e)&&(this._cfg=Object.assign({},{heartbeatMsg:null,debug:!1,mustReconnect:!0},e),this.connect())}static getInstance(e){return this._instance=this._instance||new n(e),this._instance}connect(){try{if(this._ws&&(this.isConnecting()||this.isConnected()))return void(this._cfg.debug&&console.info("Websocket is connecting or already connected."));"function"==typeof this._cfg.connecting&&this._cfg.connecting(),this._cfg.debug&&console.info(`Connecting to ${this._cfg.uri} ...`),this._ws=new WebSocket(this._cfg.uri,this._cfg.protocols),this._ws.onopen=this.onOpen.bind(this),this._ws.onmessage=this.onMessage.bind(this),this._ws.onerror=this.onError.bind(this),this._ws.onclose=this.onClose.bind(this),this._timer=null}catch(e){console.error(e),this.tryToReconnect()}}isValidOptions(e){let t=!1;return e?(e.uri||(console.error("Invalid WSClient Uri options."),t=!0),e&&e.connecting&&"function"!=typeof e.connecting&&(console.error("Invalid WSClient connecting options."),t=!0),e&&e.connected&&"function"!=typeof e.connected&&(console.error("Invalid WSClient connected options."),t=!0),e&&e.receiveMessage&&"function"!=typeof e.receiveMessage&&(console.error("Invalid WSClient receiveMessage options."),t=!0),e&&e.disconnected&&"function"!=typeof e.disconnected&&(console.error("Invalid WSClient connecting options."),t=!0),e&&e.heartbeatMsg&&"string"!=typeof e.heartbeatMsg&&(console.error("Invalid WSClient heartbeatMsg options."),t=!0),e&&e.debug&&"boolean"!=typeof e.debug&&(console.error("Invalid WSClient debug options."),t=!0),!t):(console.error("Invalid WSClient options."),t)}tryToReconnect(){if(this._cfg.mustReconnect&&!this._timer){this._cfg.debug&&console.info("Reconnecting...");let e=this.generateInteval(this._attempts);this._timer=setTimeout(this.reconnect.bind(this),e)}}reconnect(){this._attempts++,this.connect()}sendHeartbeat(){try{if(this._missedHeartbeats++,this._missedHeartbeats>3)throw new Error("Too many missed heartbeats.");this._ws.send(this._cfg.heartbeatMsg)}catch(e){clearInterval(this._heartbeatInterval),this._heartbeatInterval=null,this._cfg.debug&&console.warn(`Closing connection. Reason: ${e.message}`),this.isClosing()||this.isClosed()||this.close()}}onOpen(){this._cfg.debug&&console.info("Connected!"),this._attempts=1,this._cfg.heartbeatMsg&&null===this._heartbeatInterval&&(this._missedHeartbeats=0,this._heartbeatInterval=setInterval(this.sendHeartbeat.bind(this),5e3)),"function"==typeof this._cfg.connected&&this._cfg.connected()}onClose(e){this._cfg.debug&&console.info("Connection closed!"),"function"==typeof this._cfg.disconnected&&this._cfg.disconnected(e),this.tryToReconnect()}onError(e){this._cfg.debug&&console.error("Websocket connection is broken!"),this._cfg.debug&&console.error(e)}onMessage(e){if(this._cfg.heartbeatMsg&&e.data===this._cfg.heartbeatMsg)this._missedHeartbeats=0;else if("function"==typeof this._cfg.receiveMessage)return this._cfg.receiveMessage(e.data)}generateInteval(e){let t=1e3*(Math.pow(2,e)-1);return t>3e4&&(t=3e4),Math.random()*t}sendMessage(e){this._ws&&this._ws.send(e)}getState(){return this._ws&&this._ws.readyState}isConnecting(){return this._ws&&0===this._ws.readyState}isConnected(){return this._ws&&1===this._ws.readyState}isClosing(){return this._ws&&2===this._ws.readyState}isClosed(){return this._ws&&3===this._ws.readyState}close(){clearInterval(this._heartbeatInterval),this._cfg.mustReconnect=!1,this.isClosing()&&this.isClosed()||(this._ws.close(),this._cfg.debug&&console.error("Websocket closed."))}}t.default=n},449:(e,t,n)=>{t.__esModule=!0,t.getHighestSafeWindowContext=function e(t=n.g.window.self){return t===n.g.window.top||(()=>{try{return n.g.window.location.hostname!==n.g.window.parent.location.hostname}catch(e){return!0}})()?t:e(t.parent)},t.getWindowHeight=function(){return void 0!==n.g.window?n.g.window.innerHeight:0},t.getWindowWidth=function(){return void 0!==n.g.window?n.g.window.innerWidth:0}}},t={};function n(o){var i=t[o];if(void 0!==i)return i.exports;var r=t[o]={exports:{}};return e[o](r,r.exports,n),r.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}();var o={};return(()=>{var e=o;e.__esModule=!0;var t=n(884);e.capitalize=t.capitalize,e.isString=t.isString,e.stripHtml=t.stripHtml,e.camelCase=t.camelCase,e.copyTextToClipboard=t.copyTextToClipboard,e.fallbackCopyTextToClipboard=t.fallbackCopyTextToClipboard,e.random=t.random;var i=n(735);e.isValidUrl=i.isValidUrl,e.isValidUrls=i.isValidUrls,e.urlReplacer=i.urlReplacer,e.getDomain=i.getDomain,e.appendURLSearchParams=i.appendURLSearchParams,e.urlB64ToUint8Array=i.urlB64ToUint8Array;var r=n(449);e.getHighestSafeWindowContext=r.getHighestSafeWindowContext,e.getWindowWidth=r.getWindowWidth,e.getWindowHeight=r.getWindowHeight;var s=n(297);e.mergeDeep=s.mergeDeep,e.isObject=s.isObject;var a=n(285);e.loadVersionBrowser=a.loadVersionBrowser;var c=n(502);e.Logger=c.Logger;var l=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=d(t);if(n&&n.has(e))return n.get(e);var o={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var r in e)if("default"!==r&&Object.prototype.hasOwnProperty.call(e,r)){var s=i?Object.getOwnPropertyDescriptor(e,r):null;s&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r]}return o.default=e,n&&n.set(e,o),o}(n(507));function d(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(d=function(e){return e?n:t})(e)}e.WSClient=l.default,e.WSClientType=l.WSClientType,e.WSClientPropTypes=l.WSClientPropTypes})(),o})())); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SelfCommunityUtils=t():e.SelfCommunityUtils=t()}(self,(()=>(()=>{"use strict";var e={285:(e,t)=>{t.__esModule=!0,t.loadVersionBrowser=void 0,t.loadVersionBrowser=()=>{if("userAgentData"in navigator){const e=navigator.userAgentData;let t,n,i=null;for(let o=0;o<e.brands.length;o++){const r=e.brands[o].brand;if(n=e.brands[o].version,null!==r.match(/opera|chrome|edge|safari|firefox|msie|trident/i)){if(null===r.match(/chrome/i))return t=r.substr(r.indexOf(" ")+1),{name:t,version:n};i=n}}if(null!==i)return{name:"chrome",version:i}}let e,t=navigator.userAgent,n=t.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];return/trident/i.test(n[1])?(e=/\brv[ :]+(\d+)/g.exec(t)||[],{name:"IE",version:e[1]||""}):"Chrome"===n[1]&&(e=t.match(/\bOPR\/(\d+)/),null!=e)?{name:"Opera",version:e[1]}:(n=n[2]?[n[1],n[2]]:[navigator.appName,navigator.appVersion,"-?"],null!=(e=t.match(/version\/(\d+)/i))&&n.splice(1,1,e[1]),{name:n[0],version:n[1]})}},502:(e,t)=>{t.__esModule=!0,t.Logger=void 0,t.Logger=class{static info(e,t){console.info(`%c[${e}]`,"color:#008080",` ${t}`)}static warn(e,t){console.warn(`%c[${e}]`,"color:#008080",` ${t}`)}static error(e,t){console.error(`%c[${e}]`,"color:#008080",` ${t}`)}static log(e,t){console.log(`%c[${e}]`,"color:#008080",` ${t}`)}static debug(e,t){console.debug(`%c[${e}]`,"color:#008080",` ${t}`)}}},297:(e,t)=>{function n(e){return"object"==typeof e&&!Array.isArray(e)&&null!==e}t.__esModule=!0,t.isObject=n,t.mergeDeep=function e(t,i){let o=Object.assign({},t);return n(t)&&n(i)&&Object.keys(i).forEach((r=>{n(i[r])?r in t?o[r]=e(t[r],i[r]):Object.assign(o,{[r]:i[r]}):Object.assign(o,{[r]:i[r]})})),o}},884:(e,t)=>{function n(e){let t=document.createElement("textarea");t.value=e,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t),t.focus(),t.select();try{return document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch(e){return document.body.removeChild(t),Promise.reject(e)}}t.__esModule=!0,t.camelCase=function(e){return e.toLowerCase().replace(/[-_]+/g," ").replace(/[^\w\s]/g,"").replace(/ (.)/g,(e=>e.toUpperCase())).replace(/ /g,"")},t.capitalize=function(e){let t="",n=e.split(" ");for(let e=0;e<n.length;e++)t+=n[e].substring(0,1).toUpperCase()+n[e].substring(1,n[e].length);return t},t.copyTextToClipboard=function(e){return navigator.clipboard?navigator.clipboard.writeText(e):n(e)},t.fallbackCopyTextToClipboard=n,t.isString=function(e){return"string"==typeof e||e instanceof String},t.random=function(){return(Math.random()+1).toString(36).substring(7)},t.stripHtml=function(e){return e.replace(/<[^>]*>?/gm,"").trim()}},735:(e,t)=>{t.__esModule=!0,t.appendURLSearchParams=function(e,t){let n=e;if(t.length&&n){const e=Object.keys(t[0])[0];n+=(n.split("?")[1]?"&":"?")+`${e}=${t[0][e]}`,t.slice(1).map((e=>{const t=Object.keys(e)[0];n+=`&${t}=${e[t]}`}))}return n},t.urlReplacer=t.urlB64ToUint8Array=t.isValidUrls=t.isValidUrl=t.getDomain=void 0,t.urlReplacer=e=>t=>function(e,t){const n=/\$\(([^)]+)?\)/g;let i=n.exec(e);for(;i;)e=e.replace(i[0],t[i[1]]),n.lastIndex=0,i=n.exec(e);return e}(e,t),t.getDomain=e=>{const t=e.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);return t&&t[1]?t[1]:""};const n=e=>/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/.test(e);t.isValidUrl=n,t.isValidUrls=(e,t)=>e.trim().split(t).every(n),t.urlB64ToUint8Array=e=>{const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),n=window.atob(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;++e)i[e]=n.charCodeAt(e);return i}},507:(e,t)=>{t.__esModule=!0,t.default=void 0;class n{constructor(e){this._attempts=1,this._heartbeatInterval=null,this._missedHeartbeats=0,this.isValidOptions(e)&&(this._cfg=Object.assign({},{heartbeatMsg:null,debug:!1,mustReconnect:!0},e),this.connect())}static getInstance(e){return this._instance=this._instance||new n(e),this._instance}connect(){try{if(this._ws&&(this.isConnecting()||this.isConnected()))return void(this._cfg.debug&&console.info("Websocket is connecting or already connected."));"function"==typeof this._cfg.connecting&&this._cfg.connecting(),this._cfg.debug&&console.info(`Connecting to ${this._cfg.uri} ...`),this._ws=new WebSocket(this._cfg.uri,this._cfg.protocols),this._ws.onopen=this.onOpen.bind(this),this._ws.onmessage=this.onMessage.bind(this),this._ws.onerror=this.onError.bind(this),this._ws.onclose=this.onClose.bind(this),this._timer=null}catch(e){console.error(e),this.tryToReconnect()}}isValidOptions(e){let t=!1;return e?(e.uri||(console.error("Invalid WSClient Uri options."),t=!0),e&&e.connecting&&"function"!=typeof e.connecting&&(console.error("Invalid WSClient connecting options."),t=!0),e&&e.connected&&"function"!=typeof e.connected&&(console.error("Invalid WSClient connected options."),t=!0),e&&e.receiveMessage&&"function"!=typeof e.receiveMessage&&(console.error("Invalid WSClient receiveMessage options."),t=!0),e&&e.disconnected&&"function"!=typeof e.disconnected&&(console.error("Invalid WSClient connecting options."),t=!0),e&&e.heartbeatMsg&&"string"!=typeof e.heartbeatMsg&&(console.error("Invalid WSClient heartbeatMsg options."),t=!0),e&&e.debug&&"boolean"!=typeof e.debug&&(console.error("Invalid WSClient debug options."),t=!0),!t):(console.error("Invalid WSClient options."),t)}tryToReconnect(){if(this._cfg.mustReconnect&&!this._timer){this._cfg.debug&&console.info("Reconnecting...");let e=this.generateInteval(this._attempts);this._timer=setTimeout(this.reconnect.bind(this),e)}}reconnect(){this._attempts++,this.connect()}sendHeartbeat(){try{if(this._missedHeartbeats++,this._missedHeartbeats>3)throw new Error("Too many missed heartbeats.");this._ws.send(this._cfg.heartbeatMsg)}catch(e){clearInterval(this._heartbeatInterval),this._heartbeatInterval=null,this._cfg.debug&&console.warn(`Closing connection. Reason: ${e.message}`),this.isClosing()||this.isClosed()||this.close()}}onOpen(){this._cfg.debug&&console.info("Connected!"),this._attempts=1,this._cfg.heartbeatMsg&&null===this._heartbeatInterval&&(this._missedHeartbeats=0,this._heartbeatInterval=setInterval(this.sendHeartbeat.bind(this),5e3)),"function"==typeof this._cfg.connected&&this._cfg.connected()}onClose(e){this._cfg.debug&&console.info("Connection closed!"),"function"==typeof this._cfg.disconnected&&this._cfg.disconnected(e),this.tryToReconnect()}onError(e){this._cfg.debug&&console.error("Websocket connection is broken!"),this._cfg.debug&&console.error(e)}onMessage(e){if(this._cfg.heartbeatMsg&&e.data===this._cfg.heartbeatMsg)this._missedHeartbeats=0;else if("function"==typeof this._cfg.receiveMessage)return this._cfg.receiveMessage(e.data)}generateInteval(e){let t=1e3*(Math.pow(2,e)-1);return t>3e4&&(t=3e4),Math.random()*t}sendMessage(e){this._ws&&this._ws.send(e)}getState(){return this._ws&&this._ws.readyState}isConnecting(){return this._ws&&0===this._ws.readyState}isConnected(){return this._ws&&1===this._ws.readyState}isClosing(){return this._ws&&2===this._ws.readyState}isClosed(){return this._ws&&3===this._ws.readyState}close(){clearInterval(this._heartbeatInterval),this._cfg.mustReconnect=!1,this.isClosing()&&this.isClosed()||(this._ws.close(),this._cfg.debug&&console.error("Websocket closed."))}}t.default=n},474:(e,t,n)=>{t.__esModule=!0,t.getHighestSafeWindowContext=function e(t=n.g.window.self){return t===n.g.window.top||(()=>{try{return n.g.window.location.hostname!==n.g.window.parent.location.hostname}catch(e){return!0}})()?t:e(t.parent)},t.getWindowHeight=function(){return void 0!==n.g.window?n.g.window.innerHeight:0},t.getWindowWidth=function(){return void 0!==n.g.window?n.g.window.innerWidth:0},t.isClientSideRendering=function(){return"undefined"!=typeof window}}},t={};function n(i){var o=t[i];if(void 0!==o)return o.exports;var r=t[i]={exports:{}};return e[i](r,r.exports,n),r.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}();var i={};return(()=>{var e=i;e.__esModule=!0;var t=n(884);e.capitalize=t.capitalize,e.isString=t.isString,e.stripHtml=t.stripHtml,e.camelCase=t.camelCase,e.copyTextToClipboard=t.copyTextToClipboard,e.fallbackCopyTextToClipboard=t.fallbackCopyTextToClipboard,e.random=t.random;var o=n(735);e.isValidUrl=o.isValidUrl,e.isValidUrls=o.isValidUrls,e.urlReplacer=o.urlReplacer,e.getDomain=o.getDomain,e.appendURLSearchParams=o.appendURLSearchParams,e.urlB64ToUint8Array=o.urlB64ToUint8Array;var r=n(474);e.getHighestSafeWindowContext=r.getHighestSafeWindowContext,e.getWindowWidth=r.getWindowWidth,e.getWindowHeight=r.getWindowHeight,e.isClientSideRendering=r.isClientSideRendering;var s=n(297);e.mergeDeep=s.mergeDeep,e.isObject=s.isObject;var a=n(285);e.loadVersionBrowser=a.loadVersionBrowser;var c=n(502);e.Logger=c.Logger;var l=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=d(t);if(n&&n.has(e))return n.get(e);var i={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var r in e)if("default"!==r&&Object.prototype.hasOwnProperty.call(e,r)){var s=o?Object.getOwnPropertyDescriptor(e,r):null;s&&(s.get||s.set)?Object.defineProperty(i,r,s):i[r]=e[r]}return i.default=e,n&&n.set(e,i),i}(n(507));function d(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(d=function(e){return e?n:t})(e)}e.WSClient=l.default,e.WSClientType=l.WSClientType,e.WSClientPropTypes=l.WSClientPropTypes})(),i})())); | ||
//# sourceMappingURL=utils.js.map |
{ | ||
"name": "@selfcommunity/utils", | ||
"version": "0.1.7", | ||
"version": "0.1.8-alpha.0", | ||
"license": "MIT", | ||
@@ -8,3 +8,2 @@ "private": false, | ||
"module": "./lib/esm/index.js", | ||
"types": "./lib/types/index.d.ts", | ||
"description": "Utilities to integrate a Community.", | ||
@@ -30,7 +29,6 @@ "author": "SelfCommunity <https://www.selfcommunity.com>", | ||
"clean:node_modules": "rimraf node_modules", | ||
"build:commonjs": "cross-env BABEL_ENV=commonjs babel --root-mode upward --extensions .js,.jsx,.ts,.tsx ./src --out-dir lib/cjs --ignore **/*.stories.js,**/*.spec.js --copy-files", | ||
"build:es": "cross-env BABEL_ENV=es babel --root-mode upward --extensions .js,.jsx,.ts,.tsx ./src --out-dir lib/esm --ignore **/*.stories.js,**/*.spec.js --copy-files", | ||
"build:commonjs": "tsc -b tsconfig-cjs.build.json", | ||
"build:esm": "tsc -b tsconfig-esm.build.json", | ||
"build:umd": "webpack --mode production", | ||
"build:types": "tsc -b tsconfig.build.json", | ||
"build": "yarn clean:lib && yarn build:commonjs && yarn build:es && yarn build:umd && yarn build:types", | ||
"build": "yarn clean:lib && yarn build:commonjs && yarn build:esm && yarn build:umd", | ||
"prerelease": "yarn run clean:lib && yarn run build" | ||
@@ -107,3 +105,3 @@ }, | ||
}, | ||
"gitHead": "7fe84fe2d8f6a205ae8db967af7394ebc434ede4" | ||
"gitHead": "e8bf7ef8b5fb5693fbfe5e1aaff1a86e86922881" | ||
} |
Sorry, the diff of this file is not supported yet
148791
11.07%70
79.49%1855
18.15%