@techmely/utils
Version:
Collection of helpful JavaScript / TypeScript utils
1,821 lines (1,692 loc) • 81.4 kB
JavaScript
'use strict';
/*!
* @techmely/utils
* Copyright(c) 2021-2024 Techmely <techmely.creation@gmail.com>
* MIT Licensed
*/
// src/RopeSequence/RopeSequence.ts
var RopeSequence = class _RopeSequence {
// Create a rope representing the given array, or return the rope
// itself if a rope was given.
static from(values) {
if (values instanceof _RopeSequence)
return values;
return values?.length ? new Leaf(values) : _RopeSequence.empty;
}
leafAppend(other) {
return void 0;
}
leafPrepend(other) {
return void 0;
}
sliceInner(from, to) {
return new Leaf([]);
}
getInner(index) {
return void 0;
}
forEachInner(f, from, to, start) {
}
forEachInvertedInner(f, from, to, start) {
}
/**
* Append an array or other rope to this one, returning a new rope.
*/
append(other) {
if (!other.length)
return this;
other = _RopeSequence.from(other);
return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other);
}
// :: (union<[T], RopeSequence<T>>) → RopeSequence<T>
// Prepend an array or other rope to this one, returning a new rope.
prepend(other) {
if (!other.length)
return this;
return _RopeSequence.from(other).append(this);
}
appendInner(other) {
return new Append(this, other);
}
/**
* Create a rope representing a sub-sequence of this rope.
*/
slice(from = 0, to = _RopeSequence.length) {
if (from >= to)
return _RopeSequence.empty;
return this.sliceInner(Math.max(0, from), Math.min(this.length, to));
}
// :: (number) → T
// Retrieve the element at the given position from this rope.
get(i) {
if (i < 0 || i >= _RopeSequence.length)
return void 0;
return this.getInner(i);
}
// :: ((element: T, index: number) → ?bool, ?number, ?number)
// Call the given function for each element between the given
// indices. This tends to be more efficient than looping over the
// indices and calling `get`, because it doesn't have to descend the
// tree for every element.
forEach(f, from = 0, to = _RopeSequence.length) {
if (from <= to)
this.forEachInner(f, from, to, 0);
else
this.forEachInvertedInner(f, from, to, 0);
}
// Map the given functions over the elements of the rope, producing
// a flat array.
map(f, from = 0, to = _RopeSequence.length) {
const result = [];
this.forEach((elt, i) => result.push(f(elt, i)), from, to);
return result;
}
set length(v) {
this.length = v;
}
get length() {
return this.values.length;
}
};
var GOOD_LEAF_SIZE = 200;
var Leaf = class _Leaf extends RopeSequence {
constructor(values) {
super();
this.values = values;
}
flatten() {
return this.values;
}
sliceInner(from, to) {
if (from === 0 && to === this.length)
return this;
return new _Leaf(this.values.slice(from, to));
}
getInner(i) {
return this.values[i];
}
forEachInner(f, from, to, start) {
for (let i = from; i < to; i++)
if (f(this.values[i], start + i) === false)
return false;
}
forEachInvertedInner(f, from, to, start) {
for (let i = from - 1; i >= to; i--)
if (f(this.values[i], start + i) === false)
return false;
}
leafAppend(other) {
if (this.length + other.length <= GOOD_LEAF_SIZE)
return new _Leaf(this.values.concat(other.flatten()));
}
leafPrepend(other) {
if (this.length + other.length <= GOOD_LEAF_SIZE)
return new _Leaf(other.flatten().concat(this.values));
}
set length(v) {
this.length = v;
}
get length() {
return this.values.length;
}
get depth() {
return 0;
}
};
RopeSequence.empty = new Leaf([]);
var Append = class _Append extends RopeSequence {
constructor(left, right) {
super();
this.left = left;
this.right = right;
this.length = left.length + right.length;
this.depth = Math.max(left.depth, right.depth) + 1;
}
flatten() {
return this.left.flatten().concat(this.right.flatten());
}
getInner(i) {
return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length);
}
forEachInner(f, from, to, start) {
const leftLen = this.left.length;
if (from < leftLen && this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false)
return false;
if (to > leftLen && this.right.forEachInner(
f,
Math.max(from - leftLen, 0),
Math.min(this.length, to) - leftLen,
start + leftLen
) === false)
return false;
}
forEachInvertedInner(f, from, to, start) {
const leftLen = this.left.length;
if (from > leftLen && this.right.forEachInvertedInner(
f,
from - leftLen,
Math.max(to, leftLen) - leftLen,
start + leftLen
) === false)
return false;
if (to < leftLen && this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false)
return false;
}
sliceInner(from, to) {
if (from === 0 && to === this.length)
return this;
const leftLen = this.left.length;
if (to <= leftLen)
return this.left.slice(from, to);
if (from >= leftLen)
return this.right.slice(from - leftLen, to - leftLen);
return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen));
}
leafAppend(other) {
const inner = this.right.leafAppend(other);
if (inner)
return new _Append(this.left, inner);
}
leafPrepend(other) {
const inner = this.left.leafPrepend(other);
if (inner)
return new _Append(inner, this.right);
}
appendInner(other) {
if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1)
return new _Append(this.left, new _Append(this.right, other));
return new _Append(this, other);
}
};
// src/isBrowser.ts
function isBrowser() {
return typeof window !== "undefined";
}
// src/alias.ts
var $ = (tag) => isBrowser() ? document.querySelector.call(void 0, tag) : null;
var $$ = (tag) => isBrowser() ? document.querySelectorAll.call(void 0, tag) : null;
// src/percentToHex.ts
function percentToHex(percent) {
if (percent < 0 || percent > 100) {
throw new Error("Value must in range [0, 100]");
}
const intValue = Math.round(percent / 100 * 255);
const hexValue = intValue.toString(16);
return hexValue.padStart(2, "0").toUpperCase();
}
// src/alphaHex.ts
var HEX_LENGTH = 6;
var HEX_OPACITY_LENGTH = 8;
function alphaHex(hex, alpha) {
if (!hex) {
throw new Error("Hex value is required");
}
if (hex.length === HEX_OPACITY_LENGTH) {
return `${hex.slice(0, HEX_LENGTH)}${percentToHex(alpha)}`;
}
return `${hex}${percentToHex(alpha)}`;
}
// src/cacheImportModule.ts
var lazyImportCache = /* @__PURE__ */ new Map();
function createCachedImport(name, imp) {
return () => {
const cached = lazyImportCache.get(name);
if (cached)
return cached;
const promise = imp().then((module) => {
lazyImportCache.set(name, module);
return module;
});
lazyImportCache.set(name, promise);
return promise;
};
}
// src/cacheStringFunc.ts
function cacheStringFunction(fn) {
const cache = /* @__PURE__ */ Object.create(null);
return (str) => {
const hit = cache[str];
return hit || (cache[str] = fn(str));
};
}
// src/calculateFrequencies/index.ts
function calculateFrequencies(arr) {
return arr.reduce((acc, curr) => {
acc[curr] = (acc[curr] ?? 0) + 1;
return acc;
}, {});
}
// src/invariant.ts
var prefix = "Invariant failed";
function invariant(condition, message) {
if (condition) {
return;
}
if (typeof message === "string" || typeof message === "function") {
const provided = typeof message === "function" ? message() : message;
const value = provided ? `${prefix}: ${provided}` : prefix;
throw new Error(value);
}
if (message)
throw message;
throw new Error(prefix);
}
// src/calculateScrollPercentage/index.ts
function calculateScrollPercentage() {
invariant(isBrowser());
const scrollPosition = window.scrollY || window.scrollY || document.documentElement.scrollTop;
const totalHeight = document.documentElement.scrollHeight - window.innerHeight;
const scrollPercentage = scrollPosition / totalHeight * 100;
return scrollPercentage;
}
// src/isFunction.ts
function isFunction2(val) {
return typeof val === "function";
}
// src/callOrReturn.ts
function callOrReturn(value, context = void 0, ...props) {
if (isFunction2(value)) {
if (context) {
return value.bind(context)(...props);
}
return value(...props);
}
return value;
}
// src/camel2Snake.ts
var camel2snake = cacheStringFunction((str) => {
return str.replace(/[A-Z0-9]/g, (char) => `_${char.toLocaleLowerCase()}`);
});
// src/camel2SnakeObject.ts
function camel2SnakeObject(obj) {
return Object.entries(obj).reduce(
// biome-ignore lint/performance/noAccumulatingSpread: Ignore here
(acc, cur) => ({ ...acc, [camel2snake(cur[0])]: cur[1] }),
{}
);
}
// src/camelize.ts
var camelizeRE = /-(\w)/g;
var camelize = cacheStringFunction((str) => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : "");
});
// src/cancelIdleCallback.ts
function cancelIdleCallbackShim(id) {
clearTimeout(id);
}
var cancelIdleCallback = typeof window !== "undefined" ? window.cancelIdleCallback || cancelIdleCallbackShim : cancelIdleCallbackShim;
// src/capitalizeFirst.ts
var capitalizeFirst = cacheStringFunction((value) => {
return value.replace(/^./, value[0].toUpperCase());
});
// src/isEdgeBrowser.ts
function isEdgeBrowser() {
return typeof navigator !== "undefined" && navigator.userAgent.indexOf("Edg") > -1;
}
// src/isOpera.ts
function isOpera() {
return typeof window !== "undefined" && typeof window.opr !== "undefined";
}
// src/isChrome.ts
function isChrome() {
if (typeof window === "undefined")
return false;
const isChromium = window.chrome;
const vendor = window.navigator.vendor;
return isChromium !== null && typeof isChromium !== "undefined" && vendor === "Google Inc." && isOpera() === false && isEdgeBrowser() === false;
}
// src/chromeVersion.ts
function chromeVersion() {
if (isChrome()) {
const segments = /Chrome\/(\d+)/.exec(navigator.userAgent) || [0, 0];
return +segments[1];
}
return 0;
}
// src/chunkArray.ts
function chunk(array, size = 1) {
if (!array || array.length === 0) {
return [];
}
const chunkLength = Math.ceil(array.length / size);
return Array.from({ length: chunkLength }, (_v, i) => {
const start = i * size;
return array.slice(start, start + size);
});
}
// src/clamp.ts
function clamp(n, min, max) {
return Math.min(max, Math.max(min, n));
}
// src/convertHrTime.ts
function convertHrTime(hrtime) {
const nanoseconds = hrtime;
const number = Number(nanoseconds);
const milliseconds = number / 1e6;
const seconds = number / 1e9;
return {
seconds,
milliseconds,
nanoseconds
};
}
// src/isDate.ts
function isDate(val) {
return toString.call(val) === "[object Date]";
}
// src/cookie.ts
var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
function parseCookie(str, options) {
if (typeof str !== "string") {
throw new TypeError("argument str must be a string");
}
const obj = {};
const opt = options || {};
const dec = opt.decode || decode;
let index = 0;
while (index < str.length) {
const eqIdx = str.indexOf("=", index);
if (eqIdx === -1) {
break;
}
let endIdx = str.indexOf(";", index);
if (endIdx === -1) {
endIdx = str.length;
} else if (endIdx < eqIdx) {
index = str.lastIndexOf(";", eqIdx - 1) + 1;
continue;
}
const key = str.slice(index, eqIdx).trim();
if (obj[key] === void 0) {
let val = str.slice(eqIdx + 1, endIdx).trim();
if (val.charCodeAt(0) === 34) {
val = val.slice(1, -1);
}
obj[key] = tryDecode(val, dec);
}
index = endIdx + 1;
}
return obj;
}
function serializeCookie(name, value, options) {
const opt = options || {};
const enc = opt.encode || encode;
if (typeof enc !== "function") {
throw new TypeError("option encode is invalid");
}
if (!fieldContentRegExp.test(name)) {
throw new TypeError("argument name is invalid");
}
const encValue = enc(value);
if (value && !fieldContentRegExp.test(value)) {
throw new TypeError("argument val is invalid");
}
let str = `${name}=${encValue}`;
if (null != opt.maxAge) {
const maxAge = opt.maxAge - 0;
if (Number.isNaN(maxAge) || !Number.isFinite(maxAge)) {
throw new TypeError("option maxAge is invalid");
}
str += `; Max-Age=${Math.floor(maxAge)}`;
}
if (opt.domain) {
if (!fieldContentRegExp.test(opt.domain)) {
throw new TypeError("option domain is invalid");
}
str += `; Domain=${opt.domain}`;
}
if (opt.path) {
if (!fieldContentRegExp.test(opt.path)) {
throw new TypeError("option path is invalid");
}
str += `; Path=${opt.path}`;
}
if (opt.expires) {
const expires = opt.expires;
if (!isDate(expires) || Number.isNaN(expires.valueOf())) {
throw new TypeError("option expires is invalid");
}
str += `; Expires=${expires.toUTCString()}`;
}
if (opt.httpOnly) {
str += "; HttpOnly";
}
if (opt.secure) {
str += "; Secure";
}
if (opt.priority) {
const priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority;
switch (priority) {
case "low":
str += "; Priority=Low";
break;
case "medium":
str += "; Priority=Medium";
break;
case "high":
str += "; Priority=High";
break;
default:
throw new TypeError("option priority is invalid");
}
}
if (opt.sameSite) {
const sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
switch (sameSite) {
case true:
str += "; SameSite=Strict";
break;
case "lax":
str += "; SameSite=Lax";
break;
case "strict":
str += "; SameSite=Strict";
break;
case "none":
str += "; SameSite=None";
break;
default:
throw new TypeError("option sameSite is invalid");
}
}
return str;
}
function decode(str) {
return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str;
}
function encode(val) {
return encodeURIComponent(val);
}
function tryDecode(str, decode2) {
try {
return decode2(str);
} catch (e) {
return str;
}
}
var listenCookieChange = (callback, interval = 500) => {
let lastCookie = document.cookie;
setInterval(() => {
const { cookie } = document;
if (cookie !== lastCookie) {
try {
callback({
oldCookie: parseCookie(lastCookie),
newCookie: parseCookie(cookie)
});
} finally {
lastCookie = cookie;
}
}
}, interval);
};
var CookieService = class {
constructor(nodeEnv, env, cookieDomain) {
this.nodeEnv = nodeEnv;
this.env = env;
this.domain = cookieDomain;
this.tokenName = `token_${this.env}`;
}
get(name, options) {
if (typeof window === "undefined")
return void 0;
try {
const cookies = parseCookie(document.cookie, options);
return cookies[name];
} catch (error) {
console.error({ error });
return void 0;
}
}
set(key, value, options) {
const defaultOptions = {
secure: true,
path: "/",
domain: this.domain,
priority: "Medium",
httpOnly: false,
...options
};
try {
document.cookie = serializeCookie(key, value, defaultOptions);
} catch (error) {
console.error({ error });
}
}
setToken(token) {
document.cookie = this.env === "development" ? `${this.tokenName}=${token}; path=/; Secure` : `${this.tokenName}=${token}; path=/; Domain=${this.domain}; Secure`;
}
getToken() {
const token = this.get(this.tokenName);
return token;
}
clearToken() {
document.cookie = this.env === "development" ? `${this.tokenName}=; path=/; Secure` : `${this.tokenName}=; path=/; Domain=${this.domain}; Secure`;
}
};
// src/createElement/createElement.ts
function createElement(tag, ...children) {
invariant(isBrowser(), "Not in browser environment");
let element = tag;
if (typeof element === "string")
element = document.createElement(element);
let i = 1;
const next = arguments[1];
if (next && typeof next === "object" && !next.nodeType && !Array.isArray(next)) {
for (const name in next) {
const value = next?.[name];
if (typeof value === "string")
element.setAttribute(name, value);
if (value)
element[name] = value;
}
i++;
}
for (; i < arguments.length; i++)
add(element, arguments[i]);
return element;
}
function add(element, child) {
if (!child)
return;
if (typeof child === "string") {
element.appendChild(document.createTextNode(child));
} else if (child.nodeType !== null) {
element.appendChild(child);
} else if (Array.isArray(child)) {
for (const c of child) {
add(element, c);
}
}
}
// src/createStyleTag/index.ts
function createStyleTag(style, options) {
invariant(isBrowser());
const { id, ...rest } = options;
const styleTag = document.querySelector(`style[#${id}]`);
if (styleTag)
return styleTag;
const styleNode = document.createElement("style");
const values = Object.entries(rest);
for (const [k, v] of values) {
styleNode.setAttribute(k, v);
}
styleNode.setAttribute("id", id);
styleNode.innerHTML = style;
document.getElementsByTagName("head")[0].appendChild(styleNode);
return styleNode;
}
// src/cutString.ts
function cutString(value, limit) {
if (!value && typeof value !== "string")
return void 0;
if (value.length === 0)
return value;
return value.split("").slice(0, limit).join("");
}
// src/debounce/index.ts
function debounce(func, delay2, immediate = false) {
let timeoutId;
return function(...args) {
const callNow = immediate && !timeoutId;
if (timeoutId)
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
timeoutId = null;
if (!immediate) {
func.apply(this, args);
}
}, delay2);
if (callNow) {
func.apply(this, args);
}
};
}
// src/deleteProps.ts
function deleteProps(obj, propOrProps) {
const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps;
return Object.keys(obj).reduce((newObj, prop) => {
if (!props.includes(prop)) {
newObj[prop] = obj[prop];
}
return newObj;
}, {});
}
// src/downloadByData.ts
function downloadByData(data, filename, mime, bom) {
const blobData = typeof bom !== "undefined" ? [bom, data] : [data];
const blob = new Blob(blobData, { type: mime || "application/octet-stream" });
const blobURL = window.URL.createObjectURL(blob);
const tempLink = document.createElement("a");
tempLink.style.display = "none";
tempLink.href = blobURL;
tempLink.setAttribute("download", filename);
tempLink.dataset.testid = "link-download-blob-file";
if (typeof tempLink.download === "undefined") {
tempLink.setAttribute("target", "_blank");
}
document.body.append(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
window.URL.revokeObjectURL(blobURL);
}
// src/emitter.ts
function emitter(all) {
const events = all || /* @__PURE__ */ new Map();
const getHandlers = (type) => events.get(type);
function on(type, handler) {
const handlers = getHandlers(type);
if (handlers) {
handlers.push(handler);
} else {
events.set(type, [handler]);
}
}
function off(type, handler) {
const handlers = getHandlers(type);
if (handlers) {
if (handler) {
const indexHandler = handlers.indexOf(handler) >>> 0;
handlers.splice(indexHandler, 1);
} else {
events.set(type, []);
}
}
}
function emit(type, event) {
let handlers = getHandlers(type);
if (handlers) {
for (const handler of handlers) {
if (event)
handler(event);
}
}
handlers = events.get("*");
if (handlers) {
for (const handler of handlers) {
if (event)
handler(type, event);
}
}
}
return {
events,
on,
off,
emit
};
}
// src/env.ts
var _envShim = /* @__PURE__ */ Object.create(null);
var _getEnv = (useShim) => globalThis.process?.env || // Node.js/Bun
undefined || // Vite env
globalThis.Deno?.env.toObject() || // Deno env
globalThis.__env__ || // Custom env
(useShim ? _envShim : globalThis);
function envShims() {
return new Proxy(_envShim, {
get(_, prop) {
const env = _getEnv();
return env[prop] ?? _envShim[prop];
},
has(_, prop) {
const env = _getEnv();
return prop in env || prop in _envShim;
},
set(_, prop, value) {
const env = _getEnv(true);
env[prop] = value;
return true;
},
deleteProperty(_, prop) {
if (!prop) {
return false;
}
const env = _getEnv(true);
delete env[prop];
return true;
},
ownKeys() {
const env = _getEnv();
return Object.keys(env);
}
});
}
// src/escapeRegex.ts
function escapeRegExp(val) {
return val.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// src/findDuplicates.ts
function findDuplicates(items) {
const filtered = items.filter((el, index) => items.indexOf(el) !== index);
return [...new Set(filtered)];
}
// src/findFirstDefined.ts
function findFirstDefined(...args) {
return args.find((arg) => arg !== void 0);
}
// src/findLastIndex.ts
function findLastIndex(array, predicate) {
let l = array.length;
while (l--) {
if (predicate(array[l], l, array)) {
return l;
}
}
return -1;
}
// src/firstUniqueArray.ts
function firstUniqueArr(array) {
if (!array || array?.length === 0)
return void 0;
const arrLength = array.length;
if (array.length === 1)
return array[0];
for (let i = 0; i < arrLength; i++) {
const element = array[i];
if (array.indexOf(element) === array.lastIndexOf(element))
return element;
}
return void 0;
}
// src/firstUniqueChar.ts
function firstUniqueChar(value) {
if (!value)
return void 0;
const charLength = value.length;
for (let i = 0; i < charLength; i++) {
const letter = value[i];
if (value.indexOf(letter) === value.lastIndexOf(letter))
return letter;
}
return void 0;
}
// src/formatBytes.ts
var formatBytes = (bytes, options) => {
const sizes = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const { numberOfDecimals = 0 } = options ?? {};
if (!bytes || bytes <= 0) {
return "0 bytes";
}
if (bytes === 1) {
return "1 byte";
}
const base = 1e3;
const exponent = Math.trunc(Math.log(bytes) / Math.log(base));
const rawValue = bytes / base ** exponent;
let [whole, partial = ""] = rawValue.toString().split(".");
if (numberOfDecimals > 0) {
const count = numberOfDecimals - partial.length;
if (count > 0) {
partial += "0".repeat(count);
}
whole += `.${partial.slice(0, numberOfDecimals)}`;
}
const abbreviationSuffix = sizes[exponent];
return `${whole} ${abbreviationSuffix}`;
};
// src/isNumber.ts
function isNumber(val) {
return toString.call(val) === "[object Number]";
}
// src/formatLot10Volume.ts
function formatLot10Volume(volume, precision = 0, defaultValue = "-") {
if (!isNumber(volume)) {
return defaultValue;
}
return (volume * 10)?.toLocaleString("en", { minimumFractionDigits: precision }).slice(0, -1);
}
// src/formatNumber.ts
function formatNumber(num, precision = 0, defaultValue = "-") {
if (!isNumber(num)) {
return defaultValue;
}
return num.toLocaleString("en", {
minimumFractionDigits: precision,
maximumFractionDigits: precision
});
}
// src/fromString2Primitive.ts
function fromStringToPrimitives(value) {
if (typeof value !== "string") {
return value;
}
if (value.match(/^[+-]?(?:\d*\.)?\d+$/)) {
return Number(value);
}
if (value === "true") {
return true;
}
if (value === "false") {
return false;
}
return value;
}
// src/isServer.ts
function isServer() {
return typeof window === "undefined";
}
// src/fullScreen.ts
function requestFullscreen(mode = true, el = "body") {
if (isServer())
return;
if (mode)
document.querySelector(el)?.requestFullscreen();
else
document.exitFullscreen();
}
// src/generateSampleArray.ts
function generateSample(arr, count) {
return Array.from({ length: count }, (_) => arr[Math.round(Math.random() * (arr.length - 1))]);
}
// src/get/index.ts
function get(from, selector) {
return selector.replace(/\[([^\[\]]*)\]/g, ".$1.").split(".").filter((t) => t !== "").reduce((acc, curr) => acc?.[curr], from);
}
// src/getMineTypeFromExtension.ts
var MimeType = /* @__PURE__ */ ((MimeType2) => {
MimeType2["JPG"] = "image/jpeg";
MimeType2["GIF"] = "image/gif";
MimeType2["PNG"] = "image/png";
MimeType2["MP4"] = "video/mp4";
MimeType2["QuickTime"] = "video/quicktime";
MimeType2["AVI"] = "video/x-msvideo";
MimeType2["WMV"] = "video/x-ms-wmv";
MimeType2["HEIC"] = "image/heic";
return MimeType2;
})(MimeType || {});
var mimeTable = [
{ ext: ["gif"], type: "image/gif" /* GIF */ },
{ ext: ["jpe", "jpeg", "jpg"], type: "image/jpeg" /* JPG */ },
{ ext: ["png"], type: "image/png" /* PNG */ },
{ ext: ["qt", "mov"], type: "video/quicktime" /* QuickTime */ },
{ ext: ["mp4", "mp4v", "mpg4", "m4v"], type: "video/mp4" /* MP4 */ },
{ ext: ["avi"], type: "video/x-msvideo" /* AVI */ },
{ ext: ["wmv"], type: "video/x-ms-wmv" /* WMV */ },
{ ext: ["heic"], type: "image/heic" /* HEIC */ }
];
var getMimeTypeFromExtension = (extension) => {
const result = mimeTable.find(({ ext }) => ext.includes(extension));
if (!result) {
throw new Error(`'${extension}' is not a valid extension`);
}
return result.type;
};
// src/getQuarter.ts
function getQuarter(d = /* @__PURE__ */ new Date()) {
return Math.ceil((d.getMonth() + 1) / 3);
}
// src/getRandomInt.ts
function getRandomInt(min, max) {
const _min = Math.ceil(min);
const _max = Math.floor(max);
return Math.floor(Math.random() * (_max - _min) + _min);
}
// src/getRandomIntInclusive.ts
function getRandomIntInclusive(min, max) {
const _min = Math.ceil(min);
const _max = Math.floor(max);
return Math.floor(Math.random() * (_max - _min + 1) + _min);
}
// src/getRandomString.ts
function getRandomString(length, alphanumeric) {
let str = "";
let i = 0;
const min = alphanumeric === "a" ? 10 : 0;
const max = alphanumeric === "n" ? 10 : 62;
while (i++ < length) {
let r = Math.trunc(Math.random() * (max - min) + min);
str += String.fromCodePoint(r += r > 9 ? r < 36 ? 55 : 61 : 48);
}
return str;
}
// src/lerp.ts
function lerp(y1, y2, mu) {
return y1 * (1 - mu) + y2 * mu;
}
// src/getStrokeRadius.ts
function getStrokeRadius(size, thinning, easing, pressure = 0.5) {
if (!thinning) {
return size / 2;
}
const newPressure = clamp(easing(pressure), 0, 1);
return (thinning < 0 ? lerp(size, size + size * clamp(thinning, -0.95, -0.05), newPressure) : lerp(size - size * clamp(thinning, 0.05, 0.95), size, newPressure)) / 2;
}
// src/groupBy.ts
function groupBy(list, keyGetter) {
const map = /* @__PURE__ */ new Map();
for (const item of list) {
const key = keyGetter(item);
const collection = map.get(key);
if (collection) {
collection.push(item);
} else {
map.set(key, [item]);
}
}
return map;
}
// src/hasDuplicates/index.ts
function hasDuplicates(arr) {
return arr.length !== new Set(arr).size;
}
// src/http.ts
var HTTP_CONTINUE = 100;
var HTTP_SWITCHING_PROTOCOLS = 101;
var HTTP_PROCESSING = 102;
var HTTP_EARLY_HINTS = 103;
var HTTP_OK = 200;
var HTTP_CREATED = 201;
var HTTP_ACCEPTED = 202;
var HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
var HTTP_NO_CONTENT = 204;
var HTTP_RESET_CONTENT = 205;
var HTTP_PARTIAL_CONTENT = 206;
var HTTP_MULTI_STATUS = 207;
var HTTP_ALREADY_REPORTED = 208;
var HTTP_IM_USED = 226;
var HTTP_MULTIPLE_CHOICES = 300;
var HTTP_MOVED_PERMANENTLY = 301;
var HTTP_FOUND = 302;
var HTTP_SEE_OTHER = 303;
var HTTP_NOT_MODIFIED = 304;
var HTTP_USE_PROXY = 305;
var HTTP_RESERVED = 306;
var HTTP_TEMPORARY_REDIRECT = 307;
var HTTP_PERMANENTLY_REDIRECT = 308;
var HTTP_BAD_REQUEST = 400;
var HTTP_UNAUTHORIZED = 401;
var HTTP_PAYMENT_REQUIRED = 402;
var HTTP_FORBIDDEN = 403;
var HTTP_NOT_FOUND = 404;
var HTTP_METHOD_NOT_ALLOWED = 405;
var HTTP_NOT_ACCEPTABLE = 406;
var HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
var HTTP_REQUEST_TIMEOUT = 408;
var HTTP_CONFLICT = 409;
var HTTP_GONE = 410;
var HTTP_LENGTH_REQUIRED = 411;
var HTTP_PRECONDITION_FAILED = 412;
var HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
var HTTP_REQUEST_URI_TOO_LONG = 414;
var HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
var HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
var HTTP_EXPECTATION_FAILED = 417;
var HTTP_I_AM_A_TEAPOT = 418;
var HTTP_MISDIRECTED_REQUEST = 421;
var HTTP_UNPROCESSABLE_ENTITY = 422;
var HTTP_LOCKED = 423;
var HTTP_FAILED_DEPENDENCY = 424;
var HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425;
var HTTP_UPGRADE_REQUIRED = 426;
var HTTP_PRECONDITION_REQUIRED = 428;
var HTTP_TOO_MANY_REQUESTS = 429;
var HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
var HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451;
var HTTP_INTERNAL_SERVER_ERROR = 500;
var HTTP_NOT_IMPLEMENTED = 501;
var HTTP_BAD_GATEWAY = 502;
var HTTP_SERVICE_UNAVAILABLE = 503;
var HTTP_GATEWAY_TIMEOUT = 504;
var HTTP_VERSION_NOT_SUPPORTED = 505;
var HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506;
var HTTP_INSUFFICIENT_STORAGE = 507;
var HTTP_LOOP_DETECTED = 508;
var HTTP_NOT_EXTENDED = 510;
var HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511;
var HTTP_CF_UNKNOWN = 520;
var HTTP_CF_WEB_SERVER_IS_DOWN = 521;
var HTTP_CF_CONNECTION_TIMED_OUT = 522;
var HTTP_CF_ORIGIN_IS_UNREACHABLE = 523;
var HTTP_CF_A_TIMEOUT_OCCURRED = 524;
var HTTP_CF_SSL_HANDSHAKE_FAILED = 525;
var HTTP_CF_INVALID_SSL_CERTIFICATE = 526;
var HTTP_CF_RAILGUN_ERROR = 527;
// src/hyphenate.ts
var hyphenateRE = /\B([A-Z])/g;
var hyphenate = cacheStringFunction(
(str) => str.replace(hyphenateRE, "-$1").toLowerCase()
);
// src/intHex.ts
function intToHex(integer) {
if (integer < 0) {
throw new Error("Invalid integer as argument, must be unsigned!");
}
const hex = integer.toString(16);
return hex.length % 2 ? `0${hex}` : hex;
}
// src/intBuffer.ts
function intToBuffer(integer) {
const hex = intToHex(integer);
return Buffer.from(hex, "hex");
}
// src/isAndroid.ts
function isAndroid() {
return typeof navigator !== "undefined" ? /(android)/i.test(navigator.userAgent) : false;
}
// src/isArray.ts
function isArray(val) {
return val && Array.isArray(val);
}
// src/isBase64.ts
function isBase64(base) {
return /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/.test(base);
}
// src/isBoolean.ts
function isBoolean(val) {
return typeof val === "boolean";
}
// src/isBot.ts
var botPatterns = [
" daum[ /]",
" deusu/",
" yadirectfetcher",
"(?:^| )site",
"(?:^|[^g])news",
"(?<! (?:channel/|google/))google(?!(app|/google| pixel))",
"(?<! cu)bot(?:[^\\w]|_|$)",
"(?<! ya(?:yandex)?)search",
"(?<!(?:lib))http",
"(?<![hg]m)score",
"@[a-z]",
"\\(at\\)[a-z]",
"\\[at\\][a-z]",
"^12345",
"^<",
"^[\\w \\.\\-\\(?:\\):]+(?:/v?\\d+(\\.\\d+)?(?:\\.\\d{1,10})?)?(?:,|$)",
"^[^ ]{50,}$",
"^active",
"^ad muncher",
"^amaya",
"^anglesharp/",
"^avsdevicesdk/",
"^bidtellect/",
"^biglotron",
"^bot",
"^btwebclient/",
"^clamav[ /]",
"^client/",
"^cobweb/",
"^coccoc",
"^custom",
"^ddg[_-]android",
"^discourse",
"^dispatch/\\d",
"^downcast/",
"^duckduckgo",
"^facebook",
"^fdm[ /]\\d",
"^getright/",
"^gozilla/",
"^hatena",
"^hobbit",
"^hotzonu",
"^hwcdn/",
"^jeode/",
"^jetty/",
"^jigsaw",
"^linkdex",
"^metauri",
"^microsoft bits",
"^movabletype",
"^mozilla/\\d\\.\\d \\(compatible;?\\)$",
"^mozilla/\\d\\.\\d \\w*$",
"^navermailapp",
"^netsurf",
"^nuclei",
"^offline explorer",
"^php",
"^postman",
"^postrank",
"^python",
"^rank",
"^read",
"^reed",
"^rest",
"^serf",
"^snapchat",
"^space bison",
"^svn",
"^swcd ",
"^taringa",
"^thumbor/",
"^tumblr/",
"^user-agent:",
"^valid",
"^venus/fedoraplanet",
"^w3c",
"^webbandit/",
"^webcopier",
"^wget",
"^whatsapp",
"^xenu link sleuth",
"^yahoo",
"^yandex",
"^zdm/\\d",
"^zoom marketplace/",
"^{{.*}}$",
"adbeat\\.com",
"appinsights",
"archive",
"ask jeeves/teoma",
"bit\\.ly/",
"bluecoat drtr",
"browsex",
"burpcollaborator",
"capture",
"catch",
"check",
"chrome-lighthouse",
"chromeframe",
"classifier",
"cloud",
"crawl",
"cryptoapi",
"dareboost",
"datanyze",
"dataprovider",
"dejaclick",
"dmbrowser",
"download",
"evc-batch/",
"feed",
"firephp",
"freesafeip",
"gomezagent",
"headless",
"httrack",
"hubspot marketing grader",
"hydra",
"ibisbrowser",
"images",
"inspect",
"iplabel",
"ips-agent",
"java(?!;)",
"library",
"mail\\.ru/",
"manager",
"monitor",
"neustar wpm",
"nutch",
"offbyone",
"optimize",
"pageburst",
"parser",
"perl",
"phantom",
"pingdom",
"powermarks",
"preview",
"proxy",
"ptst[ /]\\d",
"reader",
"reputation",
"resolver",
"retriever",
"rexx;",
"rigor",
"robot",
"rss",
"scan",
"scrape",
"server",
"sogou",
"sparkler/",
"speedcurve",
"spider",
"splash",
"statuscake",
"stumbleupon\\.com",
"supercleaner",
"synapse",
"synthetic",
"torrent",
"trace",
"transcoder",
"twingly recon",
"url",
"virtuoso",
"wappalyzer",
"webglance",
"webkit2png",
"whatcms/",
"wordpress",
"zgrab"
];
var botFullPattern = " daum[ /]| deusu/| yadirectfetcher|(?:^| )site|(?:^|[^g])news|(?<! (?:channel/|google/))google(?!(app|/google| pixel))|(?<! cu)bot(?:[^\\w]|_|$)|(?<! ya(?:yandex)?)search|(?<!(?:lib))http|(?<![hg]m)score|@[a-z]|\\(at\\)[a-z]|\\[at\\][a-z]|^12345|^<|^[\\w \\.\\-\\(?:\\):]+(?:/v?\\d+(\\.\\d+)?(?:\\.\\d{1,10})?)?(?:,|$)|^[^ ]{50,}$|^active|^ad muncher|^amaya|^anglesharp/|^avsdevicesdk/|^bidtellect/|^biglotron|^bot|^btwebclient/|^clamav[ /]|^client/|^cobweb/|^coccoc|^custom|^ddg[_-]android|^discourse|^dispatch/\\d|^downcast/|^duckduckgo|^facebook|^fdm[ /]\\d|^getright/|^gozilla/|^hatena|^hobbit|^hotzonu|^hwcdn/|^jeode/|^jetty/|^jigsaw|^linkdex|^metauri|^microsoft bits|^movabletype|^mozilla/\\d\\.\\d \\(compatible;?\\)$|^mozilla/\\d\\.\\d \\w*$|^navermailapp|^netsurf|^nuclei|^offline explorer|^php|^postman|^postrank|^python|^rank|^read|^reed|^rest|^serf|^snapchat|^space bison|^svn|^swcd |^taringa|^thumbor/|^tumblr/|^user-agent:|^valid|^venus/fedoraplanet|^w3c|^webbandit/|^webcopier|^wget|^whatsapp|^xenu link sleuth|^yahoo|^yandex|^zdm/\\d|^zoom marketplace/|^{{.*}}$|adbeat\\.com|appinsights|archive|ask jeeves/teoma|bit\\.ly/|bluecoat drtr|browsex|burpcollaborator|capture|catch|check|chrome-lighthouse|chromeframe|classifier|cloud|crawl|cryptoapi|dareboost|datanyze|dataprovider|dejaclick|dmbrowser|download|evc-batch/|feed|firephp|freesafeip|gomezagent|headless|httrack|hubspot marketing grader|hydra|ibisbrowser|images|inspect|iplabel|ips-agent|java(?!;)|library|mail\\.ru/|manager|monitor|neustar wpm|nutch|offbyone|optimize|pageburst|parser|perl|phantom|pingdom|powermarks|preview|proxy|ptst[ /]\\d|reader|reputation|resolver|retriever|rexx;|rigor|robot|rss|scan|scrape|server|sogou|sparkler/|speedcurve|spider|splash|statuscake|stumbleupon\\.com|supercleaner|synapse|synthetic|torrent|trace|transcoder|twingly recon|url|virtuoso|wappalyzer|webglance|webkit2png|whatcms/|wordpress|zgrab";
var regularExpression = / daum[ /]| deusu\/| yadirectfetcher|(?:^| )site|(?:^|[^g])news|(?<! (?:channel\/|google\/))google(?!(app|\/google| pixel))|(?<! cu)bot(?:[^\w]|_|$)|(?<! ya(?:yandex)?)search|(?<!(?:lib))http|(?<![hg]m)score|@[a-z]|\(at\)[a-z]|\[at\][a-z]|^12345|^<|^[\w \.\-\(?:\):]+(?:\/v?\d+(\.\d+)?(?:\.\d{1,10})?)?(?:,|$)|^[^ ]{50,}$|^active|^ad muncher|^amaya|^anglesharp\/|^avsdevicesdk\/|^bidtellect\/|^biglotron|^bot|^btwebclient\/|^clamav[ /]|^client\/|^cobweb\/|^coccoc|^custom|^ddg[_-]android|^discourse|^dispatch\/\d|^downcast\/|^duckduckgo|^facebook|^fdm[ /]\d|^getright\/|^gozilla\/|^hatena|^hobbit|^hotzonu|^hwcdn\/|^jeode\/|^jetty\/|^jigsaw|^linkdex|^metauri|^microsoft bits|^movabletype|^mozilla\/\d\.\d \(compatible;?\)$|^mozilla\/\d\.\d \w*$|^navermailapp|^netsurf|^nuclei|^offline explorer|^php|^postman|^postrank|^python|^rank|^read|^reed|^rest|^serf|^snapchat|^space bison|^svn|^swcd |^taringa|^thumbor\/|^tumblr\/|^user-agent:|^valid|^venus\/fedoraplanet|^w3c|^webbandit\/|^webcopier|^wget|^whatsapp|^xenu link sleuth|^yahoo|^yandex|^zdm\/\d|^zoom marketplace\/|^{{.*}}$|adbeat\.com|appinsights|archive|ask jeeves\/teoma|bit\.ly\/|bluecoat drtr|browsex|burpcollaborator|capture|catch|check|chrome-lighthouse|chromeframe|classifier|cloud|crawl|cryptoapi|dareboost|datanyze|dataprovider|dejaclick|dmbrowser|download|evc-batch\/|feed|firephp|freesafeip|gomezagent|headless|httrack|hubspot marketing grader|hydra|ibisbrowser|images|inspect|iplabel|ips-agent|java(?!;)|library|mail\.ru\/|manager|monitor|neustar wpm|nutch|offbyone|optimize|pageburst|parser|perl|phantom|pingdom|powermarks|preview|proxy|ptst[ /]\d|reader|reputation|resolver|retriever|rexx;|rigor|robot|rss|scan|scrape|server|sogou|sparkler\/|speedcurve|spider|splash|statuscake|stumbleupon\.com|supercleaner|synapse|synthetic|torrent|trace|transcoder|twingly recon|url|virtuoso|wappalyzer|webglance|webkit2png|whatcms\/|wordpress|zgrab/i;
var naivePattern = /bot|spider|crawl|http|lighthouse/i;
var botRegPattern = regularExpression;
function isBotNaive(userAgent) {
return naivePattern.test(userAgent || "");
}
var usedPattern;
function isBot(userAgent) {
if (typeof usedPattern === "undefined") {
try {
usedPattern = new RegExp(botFullPattern, "i");
} catch (error) {
usedPattern = naivePattern;
}
}
return usedPattern.test(userAgent || "");
}
function createIsBot(customPattern) {
return (userAgent) => {
return customPattern.test(userAgent || "");
};
}
function createIsBotFromList(list) {
const pattern = new RegExp(list.join("|"), "i");
return (userAgent) => {
return pattern.test(userAgent || "");
};
}
function isBotMatch(userAgent) {
return userAgent?.match(botRegPattern)?.[0] ?? null;
}
function isBotMatches(userAgent) {
return botPatterns.map((part) => userAgent?.match(new RegExp(part, "i"))?.[0]).filter(Boolean);
}
function isBotPattern(userAgent) {
return userAgent ? botPatterns.find((pattern) => new RegExp(pattern, "i").test(userAgent)) ?? null : null;
}
function isBotPatterns(userAgent) {
return userAgent ? botPatterns.filter((pattern) => new RegExp(pattern, "i").test(userAgent)) : [];
}
// src/isChromeIOS.ts
function isIOSChrome() {
return typeof navigator !== "undefined" && navigator.userAgent.match("CriOS");
}
// src/isCrawler.ts
function isCrawler() {
return typeof window !== "undefined" && (!("onscroll" in window) || /(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent));
}
// src/isDefined.ts
function isDefined(val) {
return typeof val !== "undefined";
}
// src/isDistinctArray/index.ts
function isDistinctArray(arr) {
return arr.length === new Set(arr).size;
}
// src/isEmptyArray.ts
function isEmptyArr(array) {
return array?.length === 0;
}
// src/isObject.ts
function isObject2(val) {
return toString.call(val) === "[object Object]";
}
// src/isString.ts
function isString(val) {
return typeof val === "string";
}
// src/isEmpty.ts
function isEmpty(val) {
if (!val) {
return true;
}
if (isArray(val)) {
return isEmptyArr(val);
}
if (isString(val)) {
return val.trim().length === 0;
}
if (val instanceof Map || val instanceof Set) {
return val.size === 0;
}
if (isObject2(val)) {
return Object.keys(val).length === 0;
}
return false;
}
// src/isEmpties.ts
function isEmpties(...args) {
if (args.length > 1) {
return args.reduce((a, b) => a && isEmpty(b), true);
}
return false;
}
// src/isGecko.ts
function isGecko() {
return typeof navigator !== "undefined" && /gecko\/(\d+)/i.test(navigator.userAgent);
}
// src/isHexColor.ts
var hexColor = /^#(([\da-f]{2}){3,4})$/;
function isHex(hex) {
return hexColor.test(hex);
}
// src/isIOS.ts
function isIOS() {
return typeof navigator !== "undefined" ? ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"].includes(
navigator.platform
) || // iPad on iOS 13 detection
navigator.userAgent.includes("Mac") && "ontouchend" in document : false;
}
// src/isISOString/index.ts
function isISOString(val) {
const d = new Date(val);
return !Number.isNaN(d.valueOf()) && d.toISOString() === val;
}
// src/toISOStringTimezone/index.ts
var pad = (n) => `${Math.floor(Math.abs(n))}`.padStart(2, "0");
var getTimezoneOffset = (date) => {
const tzOffset = -date.getTimezoneOffset();
const diff = tzOffset >= 0 ? "+" : "-";
return `${diff + pad(tzOffset / 60)}:${pad(tzOffset % 60)}`;
};
function toISOStringTimezone(date) {
return `${date.getFullYear()}
-${pad(date.getMonth() + 1)}
-${pad(date.getDate())}
T${pad(date.getHours())}
:${pad(date.getMinutes())}
:${pad(date.getSeconds())}
${getTimezoneOffset(date)}`;
}
// src/isISOStringTimeZone/index.ts
function isISOStringWithTimezone(val) {
const d = new Date(val);
return !Number.isNaN(d.valueOf()) && toISOStringTimezone(d) === val;
}
// src/isKeyof.ts
function isKeyOf(obj, k) {
return k in obj;
}
// src/process.ts
var _process = globalThis.process || /* @__PURE__ */ Object.create(null);
var processShims = {
versions: {}
};
var globProcess = new Proxy(_process, {
get(target, prop) {
if (prop === "env") {
return envShims();
}
if (prop in target) {
return target[prop];
}
if (prop in processShims) {
return processShims[prop];
}
}
});
// src/isLinux.ts
function isLinux() {
return /^linux/i.test(globProcess.platform || "");
}
// src/isMacOs.ts
function isMacOS() {
return /^darwin/i.test(globProcess.platform || "");
}
// src/matchMedia.ts
function windowMatchMedia() {
return typeof window !== "undefined" ? window.matchMedia || window.msMatchMedia : void 0;
}
// src/isMobile.ts
function isMobile() {
return typeof window !== "undefined" ? windowMatchMedia()?.("(pointer:coarse)")?.matches : false;
}
// src/toBoolean.ts
function toBoolean(val) {
return val ? val !== "false" : false;
}
// src/isNodeProd.ts
function isNodeProd() {
return globProcess.env.NODE_ENV === "production" || toBoolean(envShims().PRODUCTION);
}
// src/isNodeTest.ts
function isNodeTest() {
return globProcess.env.NODE_ENV === "test" || toBoolean(envShims().TEST);
}
// src/isNotEmpty.ts
function isNotEmpty(val) {
return !isEmpty(val);
}
// src/isNotEmpties.ts
function isNotEmpties(...args) {
if (args.length > 1) {
return args.reduce((a, b) => a && isNotEmpty(b), true);
}
return false;
}
// src/isNotNull.ts
function isNotNull(v) {
return v !== null;
}
// src/isNotNullish.ts
function isNotNullish(v) {
return v != null;
}
// src/isPngImage.ts
function isPngImage(buffer) {
if (!buffer || buffer.length < 8) {
return false;
}
return buffer[0] === 137 && buffer[1] === 80 && buffer[2] === 78 && buffer[3] === 71 && buffer[4] === 13 && buffer[5] === 10 && buffer[6] === 26 && buffer[7] === 10;
}
// src/isPrefersReducedMotion.ts
function isPrefersReducedMotion() {
const mediaQuery = windowMatchMedia()?.("(prefers-reduced-motion: reduce)");
return typeof window !== "undefined" ? mediaQuery?.matches : false;
}
// src/isPrimitive.ts
function isPrimitive(value) {
if (value === null) {
return true;
}
return !["array", "function", "object"].includes(typeof value);
}
// src/isPromise.ts
function isPromise(val) {
return isObject(val) && isFunction(val.then) && isFunction(val.catch);
}
// src/isRegexp.ts
function isRegExp(value) {
return Object.prototype.toString.call(value) === "[object RegExp]";
}
// src/isSafari.ts
function isSafari() {
return typeof navigator !== "undefined" && navigator.vendor.indexOf("Apple") > -1 && navigator.userAgent.indexOf("CriOS") === -1 && navigator.userAgent.indexOf("FxiOS") === -1;
}
// src/isSameDay.ts
function isSameDay(date1, date2) {
if (!(date1 && date2)) {
return false;
}
return date1.getDate() === date2.getDate() && date1.getMonth() === date2.getMonth() && date1.getFullYear() === date2.getFullYear();
}
// src/isSameMonth.ts
function isSameMonth(date1, date2) {
if (!(date1 && date2)) {
return false;
}
return date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth();
}
// src/isSet.ts
function isSet(val) {
return toString.call(val) === "[object Set]";
}
// src/isSlowConnection.ts
function isSlowConnection() {
if (isServer()) {
return;
}
const cn = navigator.connection;
if (cn && (cn.saveData || /2g/.test(cn.effectiveType))) {
return true;
}
return false;
}
// src/isStream.ts
function isStream(val) {
return val !== null && typeof val === "object" && typeof val.pipe === "function";
}
// src/isSymbol.ts
function isSymbol(val) {
return typeof val === "symbol";
}
// src/isToday.ts
function isToday(date) {
return isSameDay(date, /* @__PURE__ */ new Date());
}
// src/isUndefined.ts
function isUndefined(val) {
return typeof val === "undefined";
}
// src/isWebkit.ts
function isWebkit() {
return typeof document !== "undefined" && "webkitFontSmoothing" in document.documentElement.style;
}
// src/isWindow.ts
function isWindows() {
return /^win/i.test(globProcess.platform || "");
}
// src/listify/index.ts
function listify(obj, mapFn) {
return Object.entries(obj).reduce((acc, [key, value]) => {
acc.push(mapFn(key, value));
return acc;
}, []);
}
// src/mapObject.ts
function mapObject(obj, fn) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => fn(k, v)).filter(isNotNullish)
);
}
// src/mask/index.ts
function mask(cc, num = 4, mask2 = "*") {
invariant(cc);
return `${cc}`.slice(-num).padStart(`${cc}`.length, mask2);
}
// src/mergeDeep.ts
function mergeDeep(target, ...sources) {
if (sources.length === 0) {
return target;
}
const source = sources.shift();
if (source === void 0) {
return target;
}
if (isMergeableObject(target) && isMergeableObject(source)) {
const sourceKeys = Object.keys(source);
for (const key of sourceKeys) {
if (isMergeableObject(source[key])) {
if (!target[key]) {
target[key] = {};
}
if (isMergeableObject(target[key])) {
mergeDeep(target[key], source[key]);
} else {
target[key] = source[key];
}
} else {
target[key] = source[key];
}
}
}
return mergeDeep(target, ...sources);
}
function isMergeableObject(item) {
return isObject2(item) && !isArray(item);
}
// src/minMax.ts
function minMax(value = 0, min = 0, max = 0) {
return Math.min(Math.max(value, min), max);
}
// src/mutexLock.ts
var MutexLock = class {
#mutex = Promise.resolve();
lock() {
let begin = () => {
};
this.#mutex = this.#mutex.then(() => new Promise(begin));
return new Promise((res) => {
begin = res;
});
}
async dispatch(fn) {
const unlock = await this.lock();
try {
return await Promise.resolve(fn());
} catch (error) {
throw new Error("Dispatch failed!");
} finally {
unlock();
}
}
};
// src/nextEvent.ts
function nextEvent(element, eventName) {
return new Promise(
(resolve) => element.addEventListener(eventName, (event) => resolve(event), { once: true })
);
}
// src/nextFrame.ts
function nextFrame() {
return new Promise(requestAnimationFrame);
}
// src/nextIdle.ts
function nextIdle() {
return window !== void 0 ? new Promise(window.requestIdleCallback || setTimeout) : setTimeout;
}
// src/noop.ts
var noop = () => {
};
// src/normalizeArray.ts
function normalize(array, key) {
if (!array || array.length === 0)
return {};
return array.reduce(
(acc, cur) => {
const keyValue = cur[key];
if (keyValue) {
return Object.assign(acc, { [keyValue]: cur });
}
return acc;
},
{}
);
}
// src/numberBoundaryStatePrecision.ts
var _boundaryCheckingState = true;
function checkBoundaryPrecision(num) {
if (_boundaryCheckingState) {
if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {
console.warn(
`${num} is beyond boundary when transfer to integer, the results may not be accurate`
);
}
}
}
function enableBoundaryCheckingPrecision(flag = true) {
_boundaryCheckingState = flag;
}
// src/numberCreateOperationPrecision.ts
function createOperationPrecision(operation) {
return (...nums) => {
const [first, ...others] = nums;
return others.reduce((prev, next) => operation(prev, next), first);
};
}
// src/numberDigitLengthPrecision.ts
function digitLengthPrecision(num) {
const eSplit = num.toString().split(/[eE]/);
const len = (eSplit[0].split(".")[1] || "").length - +(eSplit[1] || 0);
return len > 0 ? len : 0;
}
// src/numberStripPrecision.ts
function stripPrecision(num, precision = 15) {
return +parseFloat(Number(num).toPrecision(precision));
}
// src/numberFloat2FixedPrecision.ts
function float2FixedPrecision(num) {
if (num.toString().indexOf("e") === -1) {
return Number(num.toString().replace(".", ""));
}
const dLen = digitLengthPrecision(num);
const powDLen = 10 ** dLen;
return dLen > 0 ? stripPre