New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@therms/web-js

Package Overview
Dependencies
Maintainers
3
Versions
54
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@therms/web-js - npm Package Compare versions

Comparing version 2.5.1 to 2.5.2

dist/constants/timezones.d.ts.map

7

CHANGELOG.md

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

## [2.5.2](https://bitbucket.org/thermsio/web-js/compare/v2.5.1...v2.5.2) (2022-08-21)
### Bug Fixes
* force version ([f9c8911](https://bitbucket.org/thermsio/web-js/commits/f9c89119220138ac39eb6547e7c921a59cb86938))
## [2.5.1](https://bitbucket.org/thermsio/web-js/compare/v2.5.0...v2.5.1) (2022-08-20)

@@ -2,0 +9,0 @@

992

dist/cjs.js

@@ -1,880 +0,178 @@

'use strict';
import { CookieAttributes } from 'js-cookie';
Object.defineProperty(exports, '__esModule', { value: true });
var Cookie = require('js-cookie');
var dayjs = require('dayjs');
var Browser = require('bowser');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var Cookie__default = /*#__PURE__*/_interopDefaultLegacy(Cookie);
var dayjs__default = /*#__PURE__*/_interopDefaultLegacy(dayjs);
var Browser__default = /*#__PURE__*/_interopDefaultLegacy(Browser);
exports.Timezone = void 0;
(function (Timezone) {
Timezone["Pacific/Pago_Pago"] = "Pacific/Pago_Pago";
Timezone["Pacific/Honolulu"] = "Pacific/Honolulu";
Timezone["Pacific/Tahiti"] = "Pacific/Tahiti";
Timezone["America/Anchorage"] = "America/Anchorage";
Timezone["America/Los_Angeles"] = "America/Los_Angeles";
Timezone["America/Denver"] = "America/Denver";
Timezone["America/Chicago"] = "America/Chicago";
Timezone["America/New_York"] = "America/New_York";
Timezone["America/Halifax"] = "America/Halifax";
Timezone["America/Buenos_Aires"] = "America/Buenos_Aires";
Timezone["America/Sao_Paulo"] = "America/Sao_Paulo";
Timezone["Atlantic/Azores"] = "Atlantic/Azores";
Timezone["Europe/London"] = "Europe/London";
Timezone["Europe/Berlin"] = "Europe/Berlin";
Timezone["Europe/Helsinki"] = "Europe/Helsinki";
Timezone["Europe/Istanbul"] = "Europe/Istanbul";
Timezone["Asia/Dubai"] = "Asia/Dubai";
Timezone["Asia/Kabul"] = "Asia/Kabul";
Timezone["Indian/Maldives"] = "Indian/Maldives";
Timezone["Asia/Calcutta"] = "Asia/Calcutta";
Timezone["Asia/Kathmandu"] = "Asia/Kathmandu";
Timezone["Asia/Dhaka"] = "Asia/Dhaka";
Timezone["Indian/Cocos"] = "Indian/Cocos";
Timezone["Asia/Bangkok"] = "Asia/Bangkok";
Timezone["Asia/Hong_Kong"] = "Asia/Hong_Kong";
Timezone["Asia/Pyongyang"] = "Asia/Pyongyang";
Timezone["Asia/Tokyo"] = "Asia/Tokyo";
Timezone["Australia/Darwin"] = "Australia/Darwin";
Timezone["Australia/Brisbane"] = "Australia/Brisbane";
Timezone["Australia/Adelaide"] = "Australia/Adelaide";
Timezone["Australia/Sydney"] = "Australia/Sydney";
Timezone["Pacific/Nauru"] = "Pacific/Nauru";
Timezone["Pacific/Auckland"] = "Pacific/Auckland";
Timezone["Pacific/Kiritimati"] = "Pacific/Kiritimati";
})(exports.Timezone || (exports.Timezone = {}));
const timezones = [
{
offset: '-11:00',
label: '(GMT-11:00) Pago Pago',
tzCode: exports.Timezone['Pacific/Pago_Pago'],
},
{
offset: '-10:00',
label: '(GMT-10:00) Hawaii Time',
tzCode: exports.Timezone['Pacific/Honolulu'],
},
{
offset: '-10:00',
label: '(GMT-10:00) Tahiti',
tzCode: exports.Timezone['Pacific/Tahiti'],
},
{
offset: '-09:00',
label: '(GMT-09:00) Alaska Time',
tzCode: exports.Timezone['America/Anchorage'],
},
{
offset: '-08:00',
label: '(GMT-08:00) Pacific Time',
tzCode: exports.Timezone['America/Los_Angeles'],
},
{
offset: '-07:00',
label: '(GMT-07:00) Mountain Time',
tzCode: exports.Timezone['America/Denver'],
},
{
offset: '-06:00',
label: '(GMT-06:00) Central Time',
tzCode: exports.Timezone['America/Chicago'],
},
{
offset: '-05:00',
label: '(GMT-05:00) Eastern Time',
tzCode: exports.Timezone['America/New_York'],
},
{
offset: '-04:00',
label: '(GMT-04:00) Atlantic Time - Halifax',
tzCode: exports.Timezone['America/Halifax'],
},
{
offset: '-03:00',
label: '(GMT-03:00) Buenos Aires',
tzCode: exports.Timezone['America/Buenos_Aires'],
},
{
offset: '-02:00',
label: '(GMT-02:00) Sao Paulo',
tzCode: exports.Timezone['America/Sao_Paulo'],
},
{
offset: '-01:00',
label: '(GMT-01:00) Azores',
tzCode: exports.Timezone['Atlantic/Azores'],
},
{
offset: '+00:00',
label: '(GMT+00:00) London',
tzCode: exports.Timezone['Europe/London'],
},
{
offset: '+01:00',
label: '(GMT+01:00) Berlin',
tzCode: exports.Timezone['Europe/Berlin'],
},
{
offset: '+02:00',
label: '(GMT+02:00) Helsinki',
tzCode: exports.Timezone['Europe/Helsinki'],
},
{
offset: '+03:00',
label: '(GMT+03:00) Istanbul',
tzCode: exports.Timezone['Europe/Istanbul'],
},
{
offset: '+04:00',
label: '(GMT+04:00) Dubai',
tzCode: exports.Timezone['Asia/Dubai'],
},
{
offset: '+04:30',
label: '(GMT+04:30) Kabul',
tzCode: exports.Timezone['Asia/Kabul'],
},
{
offset: '+05:00',
label: '(GMT+05:00) Maldives',
tzCode: exports.Timezone['Indian/Maldives'],
},
{
offset: '+05:30',
label: '(GMT+05:30) India Standard Time',
tzCode: exports.Timezone['Asia/Calcutta'],
},
{
offset: '+05:45',
label: '(GMT+05:45) Kathmandu',
tzCode: exports.Timezone['Asia/Kathmandu'],
},
{
offset: '+06:00',
label: '(GMT+06:00) Dhaka',
tzCode: exports.Timezone['Asia/Dhaka'],
},
{
offset: '+06:30',
label: '(GMT+06:30) Cocos',
tzCode: exports.Timezone['Indian/Cocos'],
},
{
offset: '+07:00',
label: '(GMT+07:00) Bangkok',
tzCode: exports.Timezone['Asia/Bangkok'],
},
{
offset: '+08:00',
label: '(GMT+08:00) Hong Kong',
tzCode: exports.Timezone['Asia/Hong_Kong'],
},
{
offset: '+08:30',
label: '(GMT+08:30) Pyongyang',
tzCode: exports.Timezone['Asia/Pyongyang'],
},
{
offset: '+09:00',
label: '(GMT+09:00) Tokyo',
tzCode: exports.Timezone['Asia/Tokyo'],
},
{
offset: '+09:30',
label: '(GMT+09:30) Central Time - Darwin',
tzCode: exports.Timezone['Australia/Darwin'],
},
{
offset: '+10:00',
label: '(GMT+10:00) Eastern Time - Brisbane',
tzCode: exports.Timezone['Australia/Brisbane'],
},
{
offset: '+10:30',
label: '(GMT+10:30) Central Time - Adelaide',
tzCode: exports.Timezone['Australia/Adelaide'],
},
{
offset: '+11:00',
label: '(GMT+11:00) Eastern Time - Melbourne, Sydney',
tzCode: exports.Timezone['Australia/Sydney'],
},
{
offset: '+12:00',
label: '(GMT+12:00) Nauru',
tzCode: exports.Timezone['Pacific/Nauru'],
},
{
offset: '+13:00',
label: '(GMT+13:00) Auckland',
tzCode: exports.Timezone['Pacific/Auckland'],
},
{
offset: '+14:00',
label: '(GMT+14:00) Kiritimati',
tzCode: exports.Timezone['Pacific/Kiritimati'],
},
];
const checkIsBrowserVisible = () => document.visibilityState !== 'hidden';
let callbacks = [];
function isVisible() {
callbacks.forEach((cb) => cb(true));
declare enum Timezone {
'Pacific/Pago_Pago' = "Pacific/Pago_Pago",
'Pacific/Honolulu' = "Pacific/Honolulu",
'Pacific/Tahiti' = "Pacific/Tahiti",
'America/Anchorage' = "America/Anchorage",
'America/Los_Angeles' = "America/Los_Angeles",
'America/Denver' = "America/Denver",
'America/Chicago' = "America/Chicago",
'America/New_York' = "America/New_York",
'America/Halifax' = "America/Halifax",
'America/Buenos_Aires' = "America/Buenos_Aires",
'America/Sao_Paulo' = "America/Sao_Paulo",
'Atlantic/Azores' = "Atlantic/Azores",
'Europe/London' = "Europe/London",
'Europe/Berlin' = "Europe/Berlin",
'Europe/Helsinki' = "Europe/Helsinki",
'Europe/Istanbul' = "Europe/Istanbul",
'Asia/Dubai' = "Asia/Dubai",
'Asia/Kabul' = "Asia/Kabul",
'Indian/Maldives' = "Indian/Maldives",
'Asia/Calcutta' = "Asia/Calcutta",
'Asia/Kathmandu' = "Asia/Kathmandu",
'Asia/Dhaka' = "Asia/Dhaka",
'Indian/Cocos' = "Indian/Cocos",
'Asia/Bangkok' = "Asia/Bangkok",
'Asia/Hong_Kong' = "Asia/Hong_Kong",
'Asia/Pyongyang' = "Asia/Pyongyang",
'Asia/Tokyo' = "Asia/Tokyo",
'Australia/Darwin' = "Australia/Darwin",
'Australia/Brisbane' = "Australia/Brisbane",
'Australia/Adelaide' = "Australia/Adelaide",
'Australia/Sydney' = "Australia/Sydney",
'Pacific/Nauru' = "Pacific/Nauru",
'Pacific/Auckland' = "Pacific/Auckland",
'Pacific/Kiritimati' = "Pacific/Kiritimati"
}
function isHidden() {
callbacks.forEach((cb) => cb(false));
}
if ('hidden' in document) {
document.addEventListener('visibilitychange', () => {
(document.hidden ? isHidden : isVisible)();
});
}
if ('mozHidden' in document) {
document.addEventListener('mozvisibilitychange', () => {
(document.mozHidden ? isHidden : isVisible)();
});
}
if ('webkitHidden' in document) {
document.addEventListener('webkitvisibilitychange', () => {
(document.webkitHidden ? isHidden : isVisible)();
});
}
if ('msHidden' in document) {
document.addEventListener('msvisibilitychange', () => {
(document.msHidden ? isHidden : isVisible)();
});
}
function onBrowserVisibilityChange(callback) {
callbacks.push(callback);
return () => {
callbacks = callbacks.filter((cb) => cb !== callback);
};
}
declare const timezones: {
offset: string;
label: string;
tzCode: Timezone;
}[];
let flashInterval;
let flashTimeout;
function clearTimers() {
clearInterval(flashInterval);
clearTimeout(flashTimeout);
}
function setBrowserTitle(title) {
clearTimers();
document.title = typeof title !== 'undefined' ? title : document.title;
}
function flashBrowserTitle(title) {
const initialTitle = document.title;
flashInterval = window.setInterval(() => {
setBrowserTitle(title);
flashTimeout = window.setTimeout(() => setBrowserTitle(initialTitle), 200);
}, 400);
return function clearFlashingBrowserTitle() {
clearTimers();
};
}
declare const checkIsBrowserVisible: () => boolean;
declare function onBrowserVisibilityChange(callback: (visible: boolean) => void): () => void;
class Vent {
__version = '1';
topics = {};
publish = (event) => {
if (!event) {
console.warn('Vent.publish() empty event', new Error().stack);
}
else if (typeof event === 'string') {
event = { topic: event };
}
if (!this.topics.hasOwnProperty.call(this.topics, event.topic)) {
return;
}
this.topics[event.topic].forEach(async (item) => {
item(event.payload);
});
};
publishAsync = (event) => {
if (!event) {
console.warn('Vent.publishAsync() empty event', new Error().stack);
}
else if (typeof event === 'string') {
event = { topic: event };
}
if (!this.topics.hasOwnProperty.call(this.topics, event.topic)) {
return Promise.resolve();
}
const promises = [];
this.topics[event.topic].forEach((topicSubscriptionHandler) => {
const returned = topicSubscriptionHandler(event.payload);
if (returned && returned.then)
promises.push(returned);
});
return Promise.all(promises).then(() => undefined);
};
publishSync = (event) => {
if (!event) {
console.warn('Vent.publishSync() empty event', new Error().stack);
}
else if (typeof event === 'string') {
event = { topic: event };
}
if (!this.topics.hasOwnProperty.call(this.topics, event.topic)) {
return;
}
this.topics[event.topic].forEach((item) => {
item(event.payload);
});
};
subscribe = (topic, handler) => {
if (!topic) {
console.warn('Vent.subscribe() empty topic', new Error().stack);
}
if (!handler) {
console.warn('Vent.subscribe() empty handler', new Error().stack);
}
if (!this.topics.hasOwnProperty.call(this.topics, topic)) {
this.topics[topic] = [];
}
const index = this.topics[topic].push(handler) - 1;
return {
unsubscribe: () => {
delete this.topics[topic][index];
},
};
};
unsubscribe = (event, handler) => {
if (!event) {
console.warn('Vent.unsubscribe() empty event', new Error().stack);
}
if (!handler) {
console.warn('Vent.unsubscribe() empty handler', new Error().stack);
}
if (!this.topics.hasOwnProperty.call(this.topics, event.topic)) {
this.topics[event.topic] = [];
}
this.topics[event.topic].forEach((topicSubscriptionHandler, index) => {
if (topicSubscriptionHandler === handler) {
delete this.topics[event.topic][index];
}
});
};
}
if (!window.globalVent) {
window.globalVent = new Vent();
}
const globalVent = window.globalVent;
declare function setBrowserTitle(title: string): void;
declare function flashBrowserTitle(title: string): () => void;
class BrowserToBrowserCommunications {
vent;
static browserTempId = Math.random();
static Keys = {
__B2B_COMMS_CH: '__B2B_COMMS_CH',
declare class BrowserToBrowserCommunications {
vent: any;
static browserTempId: number;
static Keys: {
__B2B_COMMS_CH: string;
};
constructor() {
this.vent = new Vent();
window.addEventListener('storage', (event) => {
if (event.storageArea !== localStorage ||
event.key !== BrowserToBrowserCommunications.Keys.__B2B_COMMS_CH)
return;
try {
const { key, value } = JSON.parse(event?.newValue ?? "");
this.publishMsg(key, value);
}
catch (e) {
console.log('BrowserToBrowserCommunications#ctor listener error', e, event.newValue);
}
});
}
onMsg(key, cb) {
const { unsubscribe } = this.vent.subscribe(key, cb);
return { unsubscribe };
}
publishMsg = (key, value) => {
try {
window.localStorage.setItem(BrowserToBrowserCommunications.Keys.__B2B_COMMS_CH, JSON.stringify({ key, value }));
}
catch (e) {
console.log('BrowserToBrowserCommunications#publishMsg (key, error)', key, e);
}
constructor();
onMsg(key: string, cb: any): {
unsubscribe: any;
};
publishMsg: (key: string, value: any) => void;
}
const b2bComms = new BrowserToBrowserCommunications();
declare const b2bComms: BrowserToBrowserCommunications;
const deleteCookie = (name, opts) => {
Cookie__default["default"].remove(name, opts);
};
const getCookie = (name) => Cookie__default["default"].get(name);
const setCookie = (name, value, opts) => {
Cookie__default["default"].set(name, value, opts);
};
declare const deleteCookie: (name: string, opts?: CookieAttributes) => void;
declare const getCookie: (name: string) => string | undefined;
declare const setCookie: (name: string, value: string, opts?: CookieAttributes) => void;
const formatAddress = (address = {
country: '',
locality: '',
region: '',
postalCode: '',
streetAddress: '',
}, inline = true) => {
let value = ``;
if (inline) {
if (address.streetAddress) {
value += `${address.streetAddress}, `;
}
if (address.locality) {
value += `${address.locality}, `;
}
if (address.region) {
value += `${address.region} `;
}
if (address.postalCode) {
value += `${address.postalCode}`;
}
}
else {
if (address.streetAddress) {
value += `${address.streetAddress}
`;
}
if (address.locality) {
value += `${address.locality}, `;
}
if (address.region) {
value += `${address.region} `;
}
if (address.postalCode) {
value += `${address.postalCode}`;
}
}
if (value.replace(' ', '').length === 0)
return '';
return value;
};
declare const formatAddress: (address?: {
country?: string;
locality?: string;
region?: string;
postalCode?: string;
streetAddress?: string;
}, inline?: boolean) => string;
const calculatedMap = {};
function getColorContrast(hex, { darkColor = '#00111af2', lightColor = '#fffffff2' } = {}) {
if (calculatedMap[hex])
return calculatedMap[hex];
if (!hex || typeof hex !== 'string')
return darkColor;
let _hex = hex[0] === '#' ? hex.slice(1) : hex;
if (hex.length < 6) {
_hex = _hex
.split('')
.map((value) => {
return value + value;
})
.join('');
}
const r = parseInt(_hex.substring(0, 2), 16);
const g = parseInt(_hex.substring(2, 4), 16);
const b = parseInt(_hex.substring(4, 5), 16);
const yiq = (r * 299 + g * 587 + b * 114) / 1000;
calculatedMap[hex] = yiq >= 128 ? darkColor : lightColor;
return calculatedMap[hex];
}
function randomHEXColor() {
return '#' + ((Math.random() * 0xffffff) << 0).toString(16).padStart(6, '0');
}
declare function getColorContrast(hex: string, { darkColor, lightColor }?: {
darkColor?: string | undefined;
lightColor?: string | undefined;
}): string;
declare function randomHEXColor(): string;
const dateWithinRange = (from, to, date) => {
const d = date || new Date().toISOString();
if (d < from)
return false;
if (d > to)
return false;
return true;
};
declare const dateWithinRange: (from: string, to: string, date?: string) => boolean;
const MONTH_MIN = (365 / 12) * 24 * 60;
const WEEK_MIN = 7 * 24 * 60;
function getNumberWithOrdinal(n) {
if (!n || isNaN(n))
return '';
const s = ['th', 'st', 'nd', 'rd'];
const v = +n % 100;
return +n + (s[(v - 20) % 10] || s[v] || s[0]);
}
function humanizeMinutes(_min) {
let min = Math.abs(_min);
let months = '';
let weeks = '';
let days = '';
let hrs = '';
let minutes = '';
if (min >= MONTH_MIN) {
months = Math.floor(min / MONTH_MIN);
min %= MONTH_MIN;
if (months > 1)
months = `${months} months`;
else
months = `${months} month`;
}
if (min >= WEEK_MIN) {
weeks = Math.floor(min / WEEK_MIN);
min %= WEEK_MIN;
if (weeks > 1)
weeks = `${weeks} weeks`;
else
weeks = `${weeks} week`;
}
if (min >= 1440) {
days = Math.floor(min / 1440);
min %= 1440;
if (days > 1)
days = `${days} days`;
else
days = `${days} day`;
}
if (min >= 60) {
hrs = Math.floor(min / 60);
min %= 60;
if (hrs > 1)
hrs = `${hrs} hrs`;
else
hrs = `${hrs} hr`;
}
if (min >= 1) {
minutes = min;
if (minutes > 1)
minutes = `${minutes} mins`;
else
minutes = `${minutes} min`;
}
else if (!months && !weeks && !days && !hrs)
minutes = '< 1 min';
if (months) {
return `${months} ${weeks}`.trim();
}
if (weeks) {
return `${weeks} ${days}`.trim();
}
return `${days} ${hrs} ${minutes}`.trim();
}
const humanizeMillis = (millis) => humanizeMinutes(millis / 1000 / 60);
const roundToNearestMin = (date) => {
const coeff = 1000 * 60 * 1;
const d = new Date(date || new Date());
return new Date(Math.round(d.getTime() / coeff) * coeff).toISOString();
};
const setLocaleFirstDayOfWeek = (day = 0) => {
dayjs__default["default"].Ls.en.weekStart = day;
};
declare function getNumberWithOrdinal(n: number): string;
declare function humanizeMinutes(_min: string | number): string;
declare const humanizeMillis: (millis: number) => string;
declare const roundToNearestMin: (date: number | string) => string;
declare const setLocaleFirstDayOfWeek: (day?: number) => void;
function deepClone(obj) {
if (!obj)
return obj;
if (Array.isArray(obj) || typeof obj === 'object') {
try {
return JSON.parse(JSON.stringify(obj));
}
catch (e) {
throw new Error(`unable to deepClone, failed to JSON.parse<-stringify, (${e.message})`);
}
}
else {
throw new Error('an array or object is required');
}
}
declare function deepClone<T>(obj: T): T;
function deepFreeze(object, clone = true) {
const propNames = Object.getOwnPropertyNames(object);
for (const name of propNames) {
const value = object[name];
if (value && typeof value === 'object') {
deepFreeze(value, clone);
}
}
return Object.freeze(clone ? { ...object } : object);
}
declare function deepFreeze(object: any, clone?: boolean): any;
function isObject(item) {
return item && typeof item === 'object' && !Array.isArray(item);
}
function deepMerge(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) {
Object.assign(target, { [key]: {} });
}
deepMerge(target[key], source[key]);
}
else {
Object.assign(target, { [key]: source[key] });
}
}
}
return deepMerge(target, ...sources);
}
declare function deepMerge<T = any>(target: T, ...sources: any[]): T;
const permissionsState = {
'background-sync': 'prompt',
bluetooth: 'prompt',
camera: 'prompt',
geolocation: 'prompt',
backgroundGeolocation: 'prompt',
microphone: 'prompt',
nfc: 'prompt',
notifications: 'prompt',
};
async function hasPermission(permissionName, descriptor) {
return new Promise((resolve) => {
try {
navigator.permissions
.query({ name: permissionName, ...descriptor })
.then((permission) => {
if (permissionsState[permissionName])
permissionsState[permissionName] = permission.state;
switch (permission.state) {
case 'granted':
return resolve(true);
case 'denied':
case 'prompt':
return resolve(false);
default:
return resolve(false);
}
});
}
catch (err) {
console.error(`err checking permission "${permissionName}"`, err);
resolve(false);
}
});
}
function requestGeolocation() {
navigator.geolocation.getCurrentPosition((location) => console.log(location));
}
function requestNotifications() {
Notification.requestPermission();
}
function requestPush() {
navigator.serviceWorker
.getRegistration()
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration?.pushManager.subscribe();
});
}
function requestCamera() {
navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
stream.getTracks().forEach((track) => {
track.stop();
});
});
}
function requestMicrophone() {
navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
stream.getTracks().forEach((track) => {
track.stop();
});
});
}
const checkDevicePermissions = async () => {
const results = await Promise.all([
hasPermission('background-sync'),
hasPermission('camera'),
hasPermission('geolocation'),
hasPermission('microphone'),
hasPermission('notifications', { userVisible: true }),
]);
return {
backgroundSync: results[0],
bluetooth: false,
camera: results[1],
geolocation: results[2],
backgroundGeolocation: false,
microphone: results[3],
nfc: false,
notifications: results[4],
declare type Device = {
name: string;
mac?: string;
os: string;
permissions: {
backgroundSync: boolean;
bluetooth: boolean;
camera: boolean;
geolocation: boolean;
backgroundGeolocation: boolean;
microphone: boolean;
nfc: boolean;
notifications: boolean;
};
type: 'browser';
uuid: string;
};
const getDevice = () => {
const { browser, os, platform } = Browser__default["default"].parse(window?.navigator?.userAgent);
const device = {
name: `${browser.name} ${browser.version}`,
os: `${os.name} ${os.versionName} (${platform.type})`,
permissions: {
backgroundSync: permissionsState['background-sync'] === 'granted',
bluetooth: permissionsState.bluetooth === 'granted',
camera: permissionsState.camera === 'granted',
geolocation: permissionsState.geolocation === 'granted',
backgroundGeolocation: permissionsState.backgroundGeolocation === 'granted',
microphone: permissionsState.microphone === 'granted',
nfc: permissionsState.nfc === 'granted',
notifications: permissionsState.notifications === 'granted',
},
type: 'browser',
uuid: '',
};
const deviceUUID = localStorage.getItem('device-uuid');
if (deviceUUID) {
device.uuid = deviceUUID;
}
else {
const newDeviceUUID = new Date().getTime().toString();
device.uuid = newDeviceUUID;
localStorage.setItem('device-uuid', newDeviceUUID);
}
return device;
};
const isMobileDevice = (userAgent) => {
const ua = userAgent || navigator.userAgent;
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera|Mobi/i.test(ua);
};
declare function requestGeolocation(): void;
declare function requestNotifications(): void;
declare function requestPush(): void;
declare function requestCamera(): void;
declare function requestMicrophone(): void;
declare const checkDevicePermissions: () => Promise<{
backgroundSync: boolean;
bluetooth: boolean;
camera: boolean;
geolocation: boolean;
backgroundGeolocation: boolean;
microphone: boolean;
nfc: boolean;
notifications: boolean;
}>;
declare const getDevice: () => Device;
declare const isMobileDevice: (userAgent: string) => boolean;
function isEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
declare function isEmail(email: string): boolean;
function isHexColor(str) {
return /^#([0-9A-F]{3}){1,2}$/i.test(str);
}
declare function isHexColor(str: string): boolean;
const isIsoDate = (dateString) => {
if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(dateString || ''))
return false;
return new Date(dateString).toISOString() === dateString;
};
declare const isIsoDate: (dateString: string) => boolean;
function isUrl(str) {
const pattern = new RegExp('^(https?:\\/\\/)?' +
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' +
'((\\d{1,3}\\.){3}\\d{1,3}))' +
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' +
'(\\?[;&a-z\\d%_.~+=-]*)?' +
'(\\#[-a-z\\d_]*)?$', 'i');
return !!pattern.test(str);
}
declare function isUrl(str: string): boolean;
function isPlural(array = [], text = '', postfix = 's') {
if (Array.isArray(array) && array.length > 1)
return text + postfix;
if (typeof array === 'number' && array > 1)
return text + postfix;
if (typeof array === 'boolean' && array)
return text + postfix;
return text;
declare function isPlural(array?: never[], text?: string, postfix?: string): string;
declare function pluralize(txt: string | string[], count?: number): string;
declare class PromiseTimeoutError extends Error {
}
function pluralize(txt, count = 0) {
if (count > 1) {
if (Array.isArray(txt)) {
return txt[1];
}
return txt + 's';
}
if (Array.isArray(txt)) {
return txt[0];
}
return txt;
declare class PromiseController<T, E> {
private rejectPromise?;
private resolvePromise?;
readonly promise: Promise<T>;
constructor(timeout?: boolean | number);
reject: (rejectReturnValue?: E) => any;
resolve: (resolveReturnValue: T) => void;
}
const DEFAULT_TIMEOUT = 30000;
class PromiseTimeoutError extends Error {
declare function retryPromise(fn: () => Promise<any>, retryCount?: number, interval?: number): Promise<unknown>;
declare const sleep: (ms: number) => Promise<unknown>;
interface EventPayload<Payload = any> {
payload?: Payload;
topic: string;
}
class PromiseController {
rejectPromise;
resolvePromise;
promise;
constructor(timeout = DEFAULT_TIMEOUT) {
this.promise = new Promise((resolve, reject) => {
let timer;
if (timeout > 0) {
timer = setTimeout(() => {
reject(new PromiseTimeoutError('PromiseWraper timeout'));
}, timeout);
}
this.rejectPromise = (arg) => {
clearTimeout(timer);
reject(arg);
};
this.resolvePromise = (arg) => {
clearTimeout(timer);
resolve(arg);
};
});
}
reject = (rejectReturnValue) => {
if (this.rejectPromise) {
this.rejectPromise(rejectReturnValue);
}
else {
console.error(`PromiseController#rejectPromise does not exist`);
}
declare class Vent {
__version: string;
topics: {
[event: string]: Array<(payload: any) => any>;
};
resolve = (resolveReturnValue) => {
if (this.resolvePromise) {
this.resolvePromise(resolveReturnValue);
}
else {
console.error(`PromiseController#resolvePromise does not exist`);
}
publish: <Payload>(event: EventPayload<Payload>) => void;
publishAsync: <Payload>(event: EventPayload<Payload>) => Promise<void>;
publishSync: <Payload>(event: EventPayload<Payload>) => void;
subscribe: <Payload>(topic: string, handler: (payload: Payload) => any) => {
unsubscribe: () => void;
};
unsubscribe: (event: EventPayload, handler: any) => void;
}
declare const globalVent: any;
function retryPromise(fn, retryCount = 5, interval = 1000) {
return new Promise((resolve, reject) => {
fn()
.then(resolve)
.catch(error => {
setTimeout(() => {
if (retryCount === 1) {
reject(error);
}
else {
retryPromise(fn, retryCount - 1, interval).then(resolve, reject);
}
}, interval);
});
});
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
exports.PromiseController = PromiseController;
exports.PromiseTimeoutError = PromiseTimeoutError;
exports.Vent = Vent;
exports.b2bComms = b2bComms;
exports.checkDevicePermissions = checkDevicePermissions;
exports.checkIsBrowserVisible = checkIsBrowserVisible;
exports.dateWithinRange = dateWithinRange;
exports.deepClone = deepClone;
exports.deepFreeze = deepFreeze;
exports.deepMerge = deepMerge;
exports.deleteCookie = deleteCookie;
exports.flashBrowserTitle = flashBrowserTitle;
exports.formatAddress = formatAddress;
exports.getColorContrast = getColorContrast;
exports.getCookie = getCookie;
exports.getDevice = getDevice;
exports.getNumberWithOrdinal = getNumberWithOrdinal;
exports.globalVent = globalVent;
exports.humanizeMillis = humanizeMillis;
exports.humanizeMinutes = humanizeMinutes;
exports.isEmail = isEmail;
exports.isHexColor = isHexColor;
exports.isIsoDate = isIsoDate;
exports.isMobileDevice = isMobileDevice;
exports.isPlural = isPlural;
exports.isUrl = isUrl;
exports.onBrowserVisibilityChange = onBrowserVisibilityChange;
exports.pluralize = pluralize;
exports.randomHEXColor = randomHEXColor;
exports.requestCamera = requestCamera;
exports.requestGeolocation = requestGeolocation;
exports.requestMicrophone = requestMicrophone;
exports.requestNotifications = requestNotifications;
exports.requestPush = requestPush;
exports.retryPromise = retryPromise;
exports.roundToNearestMin = roundToNearestMin;
exports.setBrowserTitle = setBrowserTitle;
exports.setCookie = setCookie;
exports.setLocaleFirstDayOfWeek = setLocaleFirstDayOfWeek;
exports.sleep = sleep;
exports.timezones = timezones;
export { Device, PromiseController, PromiseTimeoutError, Timezone, Vent, b2bComms, checkDevicePermissions, checkIsBrowserVisible, dateWithinRange, deepClone, deepFreeze, deepMerge, deleteCookie, flashBrowserTitle, formatAddress, getColorContrast, getCookie, getDevice, getNumberWithOrdinal, globalVent, humanizeMillis, humanizeMinutes, isEmail, isHexColor, isIsoDate, isMobileDevice, isPlural, isUrl, onBrowserVisibilityChange, pluralize, randomHEXColor, requestCamera, requestGeolocation, requestMicrophone, requestNotifications, requestPush, retryPromise, roundToNearestMin, setBrowserTitle, setCookie, setLocaleFirstDayOfWeek, sleep, timezones };
//# sourceMappingURL=cjs.js.map

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

export declare enum Timezone {
declare enum Timezone {
'Pacific/Pago_Pago' = "Pacific/Pago_Pago",

@@ -37,3 +37,3 @@ 'Pacific/Honolulu' = "Pacific/Honolulu",

}
export declare const timezones: {
declare const timezones: {
offset: string;

@@ -43,1 +43,4 @@ label: string;

}[];
export { Timezone, timezones };
//# sourceMappingURL=timezones.d.ts.map

@@ -1,22 +0,23 @@

export * from './constants/timezones';
export * from './services/browser-visibility';
export * from './services/browser-title';
export * from './services/browser-to-browser-communications';
export * from './services/cookies';
export * from './utils/address';
export * from './utils/color';
export * from './utils/date-within-range';
export * from './utils/date';
export * from './utils/deep-clone';
export * from './utils/deep-freeze';
export * from './utils/deep-merge';
export * from './utils/device';
export * from './utils/is-email';
export * from './utils/is-hex-color';
export * from './utils/is-iso-date';
export * from './utils/is-url';
export * from './utils/pluralize';
export * from './utils/promises/promise-controller';
export * from './utils/promises/retry-promise';
export * from './utils/promises/sleep';
export * from './services/vent';
export { Timezone, timezones } from './constants/timezones.js';
export { checkIsBrowserVisible, onBrowserVisibilityChange } from './services/browser-visibility.js';
export { flashBrowserTitle, setBrowserTitle } from './services/browser-title.js';
export { b2bComms } from './services/browser-to-browser-communications.js';
export { deleteCookie, getCookie, setCookie } from './services/cookies.js';
export { formatAddress } from './utils/address.js';
export { getColorContrast, randomHEXColor } from './utils/color.js';
export { dateWithinRange } from './utils/date-within-range.js';
export { getNumberWithOrdinal, humanizeMillis, humanizeMinutes, roundToNearestMin, setLocaleFirstDayOfWeek } from './utils/date.js';
export { deepClone } from './utils/deep-clone.js';
export { deepFreeze } from './utils/deep-freeze.js';
export { deepMerge } from './utils/deep-merge.js';
export { Device, checkDevicePermissions, getDevice, isMobileDevice, requestCamera, requestGeolocation, requestMicrophone, requestNotifications, requestPush } from './utils/device.js';
export { isEmail } from './utils/is-email.js';
export { isHexColor } from './utils/is-hex-color.js';
export { isIsoDate } from './utils/is-iso-date.js';
export { isUrl } from './utils/is-url.js';
export { isPlural, pluralize } from './utils/pluralize.js';
export { PromiseController, PromiseTimeoutError } from './utils/promises/promise-controller.js';
export { retryPromise } from './utils/promises/retry-promise.js';
export { sleep } from './utils/promises/sleep.js';
export { Vent, globalVent } from './services/vent.js';
//# sourceMappingURL=index.d.ts.map

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

export declare function setBrowserTitle(title: string): void;
export declare function flashBrowserTitle(title: string): () => void;
declare function setBrowserTitle(title: string): void;
declare function flashBrowserTitle(title: string): () => void;
export { flashBrowserTitle, setBrowserTitle };
//# sourceMappingURL=browser-title.d.ts.map

@@ -13,3 +13,5 @@ declare class BrowserToBrowserCommunications {

}
export declare const b2bComms: BrowserToBrowserCommunications;
export {};
declare const b2bComms: BrowserToBrowserCommunications;
export { b2bComms };
//# sourceMappingURL=browser-to-browser-communications.d.ts.map

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

export declare const checkIsBrowserVisible: () => boolean;
export declare function onBrowserVisibilityChange(callback: (visible: boolean) => void): () => void;
declare const checkIsBrowserVisible: () => boolean;
declare function onBrowserVisibilityChange(callback: (visible: boolean) => void): () => void;
export { checkIsBrowserVisible, onBrowserVisibilityChange };
//# sourceMappingURL=browser-visibility.d.ts.map
import { CookieAttributes } from 'js-cookie';
export declare const deleteCookie: (name: string, opts?: CookieAttributes) => void;
export declare const getCookie: (name: string) => string | undefined;
export declare const setCookie: (name: string, value: string, opts?: CookieAttributes) => void;
declare const deleteCookie: (name: string, opts?: CookieAttributes) => void;
declare const getCookie: (name: string) => string | undefined;
declare const setCookie: (name: string, value: string, opts?: CookieAttributes) => void;
export { deleteCookie, getCookie, setCookie };
//# sourceMappingURL=cookies.d.ts.map

@@ -5,3 +5,3 @@ interface EventPayload<Payload = any> {

}
export declare class Vent {
declare class Vent {
__version: string;

@@ -19,3 +19,5 @@ topics: {

}
export declare const globalVent: any;
export {};
declare const globalVent: any;
export { Vent, globalVent };
//# sourceMappingURL=vent.d.ts.map

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

export declare const formatAddress: (address?: {
declare const formatAddress: (address?: {
country?: string;

@@ -8,1 +8,4 @@ locality?: string;

}, inline?: boolean) => string;
export { formatAddress };
//# sourceMappingURL=address.d.ts.map

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

export declare function getColorContrast(hex: string, { darkColor, lightColor }?: {
declare function getColorContrast(hex: string, { darkColor, lightColor }?: {
darkColor?: string | undefined;
lightColor?: string | undefined;
}): string;
export declare function randomHEXColor(): string;
declare function randomHEXColor(): string;
export { getColorContrast, randomHEXColor };
//# sourceMappingURL=color.d.ts.map

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

export declare const dateWithinRange: (from: string, to: string, date?: string) => boolean;
declare const dateWithinRange: (from: string, to: string, date?: string) => boolean;
export { dateWithinRange };
//# sourceMappingURL=date-within-range.d.ts.map

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

export declare function getNumberWithOrdinal(n: number): string;
export declare function humanizeMinutes(_min: string | number): string;
export declare const humanizeMillis: (millis: number) => string;
export declare const roundToNearestMin: (date: number | string) => string;
export declare const setLocaleFirstDayOfWeek: (day?: number) => void;
declare function getNumberWithOrdinal(n: number): string;
declare function humanizeMinutes(_min: string | number): string;
declare const humanizeMillis: (millis: number) => string;
declare const roundToNearestMin: (date: number | string) => string;
declare const setLocaleFirstDayOfWeek: (day?: number) => void;
export { getNumberWithOrdinal, humanizeMillis, humanizeMinutes, roundToNearestMin, setLocaleFirstDayOfWeek };
//# sourceMappingURL=date.d.ts.map

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

export declare function deepClone<T>(obj: T): T;
declare function deepClone<T>(obj: T): T;
export { deepClone };
//# sourceMappingURL=deep-clone.d.ts.map

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

export declare function deepFreeze(object: any, clone?: boolean): any;
declare function deepFreeze(object: any, clone?: boolean): any;
export { deepFreeze };
//# sourceMappingURL=deep-freeze.d.ts.map

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

export declare function deepMerge<T = any>(target: T, ...sources: any[]): T;
declare function deepMerge<T = any>(target: T, ...sources: any[]): T;
export { deepMerge };
//# sourceMappingURL=deep-merge.d.ts.map

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

export declare type Device = {
declare type Device = {
name: string;

@@ -18,8 +18,8 @@ mac?: string;

};
export declare function requestGeolocation(): void;
export declare function requestNotifications(): void;
export declare function requestPush(): void;
export declare function requestCamera(): void;
export declare function requestMicrophone(): void;
export declare const checkDevicePermissions: () => Promise<{
declare function requestGeolocation(): void;
declare function requestNotifications(): void;
declare function requestPush(): void;
declare function requestCamera(): void;
declare function requestMicrophone(): void;
declare const checkDevicePermissions: () => Promise<{
backgroundSync: boolean;

@@ -34,3 +34,6 @@ bluetooth: boolean;

}>;
export declare const getDevice: () => Device;
export declare const isMobileDevice: (userAgent: string) => boolean;
declare const getDevice: () => Device;
declare const isMobileDevice: (userAgent: string) => boolean;
export { Device, checkDevicePermissions, getDevice, isMobileDevice, requestCamera, requestGeolocation, requestMicrophone, requestNotifications, requestPush };
//# sourceMappingURL=device.d.ts.map

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

export declare function isEmail(email: string): boolean;
declare function isEmail(email: string): boolean;
export { isEmail };
//# sourceMappingURL=is-email.d.ts.map

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

export declare function isHexColor(str: string): boolean;
declare function isHexColor(str: string): boolean;
export { isHexColor };
//# sourceMappingURL=is-hex-color.d.ts.map

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

export declare const isIsoDate: (dateString: string) => boolean;
declare const isIsoDate: (dateString: string) => boolean;
export { isIsoDate };
//# sourceMappingURL=is-iso-date.d.ts.map

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

export declare function isUrl(str: string): boolean;
declare function isUrl(str: string): boolean;
export { isUrl };
//# sourceMappingURL=is-url.d.ts.map

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

export declare function isPlural(array?: never[], text?: string, postfix?: string): string;
export declare function pluralize(txt: string | string[], count?: number): string;
declare function isPlural(array?: never[], text?: string, postfix?: string): string;
declare function pluralize(txt: string | string[], count?: number): string;
export { isPlural, pluralize };
//# sourceMappingURL=pluralize.d.ts.map

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

export declare class PromiseTimeoutError extends Error {
declare class PromiseTimeoutError extends Error {
}
export declare class PromiseController<T, E> {
declare class PromiseController<T, E> {
private rejectPromise?;

@@ -11,1 +11,4 @@ private resolvePromise?;

}
export { PromiseController, PromiseTimeoutError };
//# sourceMappingURL=promise-controller.d.ts.map

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

export declare function retryPromise(fn: () => Promise<any>, retryCount?: number, interval?: number): Promise<unknown>;
declare function retryPromise(fn: () => Promise<any>, retryCount?: number, interval?: number): Promise<unknown>;
export { retryPromise };
//# sourceMappingURL=retry-promise.d.ts.map

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

export declare const sleep: (ms: number) => Promise<unknown>;
declare const sleep: (ms: number) => Promise<unknown>;
export { sleep };
//# sourceMappingURL=sleep.d.ts.map
{
"license": "UNLICENSED",
"name": "@therms/web-js",
"version": "2.5.1",
"version": "2.5.2",
"description": "Common web/JS tools & utilities",

@@ -15,3 +15,3 @@ "main": "./dist/cjs.js",

"scripts": {
"build": "rm -rf dist && rollup -c && npm run types",
"build": "rm -rf dist && rollup -c",
"prepublishOnly": "npm run build",

@@ -44,2 +44,3 @@ "start": "rm -rf dist && rollup -c --watch",

"rollup-plugin-auto-external": "^2.0.0",
"rollup-plugin-dts": "^4.2.2",
"rollup-plugin-sourcemaps": "^0.6.3",

@@ -46,0 +47,0 @@ "semantic-release": "^19.0.3",

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc