12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052 |
- // src/arrays.ts
- function createArray(size, start = 1) {
- return Array.from({ length: size }, (_, index) => index + start);
- }
- function getRandomItem(input) {
- return input[Math.floor(Math.random() * input.length)];
- }
- function quickSort(input, comparator = sortComparator) {
- const output = [...input];
- const recursiveSort = (start, end) => {
- if (end - start < 1) {
- return;
- }
- const pivotValue = output[end];
- let splitIndex = start;
- for (let index = start; index < end; index++) {
- const sort = comparator(output[index], pivotValue);
- if (sort === -1) {
- if (splitIndex !== index) {
- const temp = output[splitIndex];
- output[splitIndex] = output[index];
- output[index] = temp;
- }
- splitIndex++;
- }
- }
- output[end] = output[splitIndex];
- output[splitIndex] = pivotValue;
- recursiveSort(start, splitIndex - 1);
- recursiveSort(splitIndex + 1, end);
- };
- recursiveSort(0, input.length - 1);
- return output;
- }
- function removeDuplicates(input) {
- return [...new Set(input)];
- }
- function shuffle(input) {
- let currentIndex = input.length;
- let randomIndex;
- let temporaryValue;
- const output = [...input];
- while (currentIndex) {
- randomIndex = Math.floor(Math.random() * currentIndex--);
- temporaryValue = output[currentIndex];
- output[currentIndex] = output[randomIndex];
- output[randomIndex] = temporaryValue;
- }
- return output;
- }
- function sortByLocaleCompare(key, options = {}) {
- const { descending, ...compareOptions } = options;
- if (key) {
- if (descending) {
- return (left, right) => right[key].toLowerCase().localeCompare(left[key].toLowerCase(), void 0, compareOptions);
- }
- return (left, right) => left[key].toLowerCase().localeCompare(right[key].toLowerCase(), void 0, compareOptions);
- }
- if (descending) {
- return (left, right) => right.toLowerCase().localeCompare(left.toLowerCase(), void 0, compareOptions);
- }
- return (left, right) => left.toLowerCase().localeCompare(right.toLowerCase(), void 0, compareOptions);
- }
- function sortByPrimitive(key, descending = false) {
- const firstComparator = descending ? 1 : -1;
- const secondComparator = descending ? -1 : 1;
- if (key) {
- return (left, right) => {
- if (left[key] === right[key]) {
- return 0;
- }
- return left[key] < right[key] ? firstComparator : secondComparator;
- };
- }
- return (left, right) => {
- if (left === right) {
- return 0;
- }
- return left < right ? firstComparator : secondComparator;
- };
- }
- function sortComparator(left, right) {
- if (left < right) {
- return -1;
- }
- if (left > right) {
- return 1;
- }
- return 0;
- }
- function splitIntoChunks(input, chunkSize = 25) {
- if (!Array.isArray(input)) {
- throw new TypeError("expected an array for the first argument");
- }
- const chunks = [];
- for (let index = 0; index < Math.ceil(input.length / chunkSize); index++) {
- chunks.push(input.slice(index * chunkSize, (index + 1) * chunkSize));
- }
- return chunks;
- }
- // src/async.ts
- import is from "is-lite";
- var ASYNC_STATUS = {
- IDLE: "IDLE",
- PENDING: "PENDING",
- SUCCESS: "SUCCESS",
- ERROR: "ERROR"
- };
- function cors(data, statusCodeOrOptions = 200) {
- const {
- allowCredentials = true,
- allowedHeaders = [],
- methods = ["GET"],
- origin = "*",
- responseHeaders = void 0,
- statusCode = 200
- } = is.number(statusCodeOrOptions) ? { statusCode: statusCodeOrOptions } : statusCodeOrOptions;
- const allowMethods = [...methods, "OPTIONS"];
- const allowHeaders = [
- .../* @__PURE__ */ new Set([
- "Accept-Version",
- "Accept",
- "Authorization",
- "Content-Length",
- "Content-MD5",
- "Content-Type",
- "Date",
- "x-amz-date",
- "x-amz-security-token",
- "X-Api-Version",
- "X-CSRF-Token",
- "X-Requested-With",
- ...allowedHeaders
- ])
- ];
- let exposedHeaders;
- if (responseHeaders) {
- exposedHeaders = {
- "Access-Control-Expose-Headers": Object.keys(responseHeaders).join(","),
- ...responseHeaders
- };
- }
- return {
- body: JSON.stringify(data),
- headers: {
- "Access-Control-Allow-Origin": origin,
- "Access-Control-Allow-Credentials": allowCredentials,
- "Access-Control-Allow-Methods": allowMethods.join(","),
- "Access-Control-Allow-Headers": allowHeaders.join(","),
- ...exposedHeaders
- },
- statusCode
- };
- }
- async function poll(condition, options = {}) {
- const { delay = 1, maxRetries = 5 } = options;
- let retries = 0;
- while (!condition() && retries <= maxRetries) {
- await sleep(delay);
- retries++;
- }
- if (retries >= maxRetries) {
- throw new Error("Timeout");
- }
- }
- async function request(url, options = {}) {
- const { body, headers, method = "GET" } = options;
- if (!url) {
- throw new Error("URL is required");
- }
- const params = {
- headers: {
- Accept: "application/json",
- "Content-Type": "application/json",
- ...headers
- },
- method
- };
- if (body) {
- params.body = is.plainObject(body) ? JSON.stringify(body) : body;
- }
- return fetch(url, params).then(async (response) => {
- const text = await response.text();
- let content;
- try {
- content = JSON.parse(text);
- } catch {
- content = text;
- }
- if (response.status > 299) {
- const error = new Error(response.statusText);
- error.status = response.status;
- error.response = content;
- throw error;
- } else {
- return content;
- }
- });
- }
- function sleep(seconds = 1) {
- return new Promise((resolve) => {
- setTimeout(resolve, seconds * 1e3);
- });
- }
- // src/date.ts
- import is2 from "is-lite";
- // src/strings.ts
- function capitalize(input) {
- return input.charAt(0).toLocaleUpperCase() + input.slice(1).toLocaleLowerCase();
- }
- function cleanupHTML(input) {
- return removeWhitespace(removeEmptyTags(input));
- }
- function cleanupNumericString(value = "") {
- return value.replace(/\D+/g, "");
- }
- function cleanupURI(input) {
- return input.replace(/[$&+,/:;=?@]/g, "");
- }
- function getInitials(input) {
- if (!input) {
- return "";
- }
- const names = input.trim().split(" ");
- if (names.length === 1) {
- return `${names[0].charAt(0)}`;
- }
- return `${names[0].charAt(0)}${names[names.length - 1].charAt(0)}`;
- }
- function pluralize(quantity, singular, plural) {
- if (quantity === 1) {
- return singular;
- }
- return plural || `${singular}s`;
- }
- function removeAccents(input) {
- const removalMap = {
- A: /[AÀÁÂÃÄÅĀĂĄǍǞǠǺȀȂȦḀẠẢẤẦẨẪẬẮẰẲẴẶⒶA]/g,
- AA: /Ꜳ/g,
- AE: /[ÆǢǼ]/g,
- AO: /Ꜵ/g,
- AU: /Ꜷ/g,
- AV: /[ꜸꜺ]/g,
- AY: /Ꜽ/g,
- B: /[BƁƂɃḂḄḆⒷB]/g,
- C: /[CÇĆĈĊČƇȻḈⒸꜾC]/g,
- D: /[DĎĐƉƊƋḊḌḎḐḒⒹꝹD]/g,
- DZ: /[DŽDZ]/g,
- Dz: /[DžDz]/g,
- E: /[EÈÉÊËĒĔĖĘĚƎƐȄȆȨḔḖḘḚḜẸẺẼẾỀỂỄỆⒺE]/g,
- F: /[FƑḞⒻꝻF]/g,
- G: /[GĜĞĠĢƓǤǦǴḠⒼꝽꝾꞠG]/g,
- H: /[HĤĦȞḢḤḦḨḪⒽⱧⱵꞍH]/g,
- I: /[IÌÍÎÏĨĪĬĮİƗǏȈȊḬḮỈỊⒾI]/g,
- J: /[JĴɈⒿJ]/g,
- K: /[KĶƘǨḰḲḴⓀⱩꝀꝂꝄꞢK]/g,
- L: /[LĹĻĽĿŁȽḶḸḺḼⓁⱠⱢꝆꝈꞀL]/g,
- LJ: /LJ/g,
- Lj: /Lj/g,
- M: /[MƜḾṀṂⓂⱮM]/g,
- N: /[NÑŃŅŇƝǸȠṄṆṈṊⓃꞐꞤN]/g,
- NJ: /NJ/g,
- Nj: /Nj/g,
- O: /[OÒÓÔÕÖØŌŎŐƆƟƠǑǪǬǾȌȎȪȬȮȰṌṎṐṒỌỎỐỒỔỖỘỚỜỞỠỢⓄꝊꝌO]/g,
- OI: /Ƣ/g,
- OO: /Ꝏ/g,
- OU: /Ȣ/g,
- P: /[PƤṔṖⓅⱣꝐꝒꝔP]/g,
- Q: /[QɊⓆꝖꝘQ]/g,
- R: /[RŔŖŘȐȒɌṘṚṜṞⓇⱤꝚꞂꞦR]/g,
- S: /[SŚŜŞŠȘṠṢṤṦṨẞⓈⱾꞄꞨS]/g,
- T: /[TŢŤŦƬƮȚȾṪṬṮṰⓉꞆT]/g,
- TZ: /Ꜩ/g,
- U: /[UÙÚÛÜŨŪŬŮŰŲƯǓǕǗǙǛȔȖɄṲṴṶṸṺỤỦỨỪỬỮỰⓊU]/g,
- V: /[VƲɅṼṾⓋꝞV]/g,
- VY: /Ꝡ/g,
- W: /[WŴẀẂẄẆẈⓌⱲW]/g,
- X: /[XẊẌⓍX]/g,
- Y: /[YÝŶŸƳȲɎẎỲỴỶỸỾⓎY]/g,
- Z: /[ZŹŻŽƵȤẐẒẔⓏⱫⱿꝢZ]/g,
- a: /[aàáâãäåāăąǎǟǡǻȁȃȧɐḁẚạảấầẩẫậắằẳẵặⓐⱥa]/g,
- aa: /ꜳ/g,
- ae: /[æǣǽ]/g,
- ao: /ꜵ/g,
- au: /ꜷ/g,
- av: /[ꜹꜻ]/g,
- ay: /ꜽ/g,
- b: /[bƀƃɓḃḅḇⓑb]/g,
- c: /[cçćĉċčƈȼḉↄⓒꜿc]/g,
- d: /[dďđƌɖɗḋḍḏḑḓⓓꝺd]/g,
- dz: /[dždz]/g,
- e: /[eèéêëēĕėęěǝȅȇȩɇɛḕḗḙḛḝẹẻẽếềểễệⓔe]/g,
- f: /[fƒḟⓕꝼf]/g,
- g: /[gĝğġģǥǧǵɠᵹḡⓖꝿꞡg]/g,
- h: /[hĥħȟɥḣḥḧḩḫẖⓗⱨⱶh]/g,
- hv: /ƕ/g,
- i: /[iìíîïĩīĭįıǐȉȋɨḭḯỉịⓘi]/g,
- j: /[jĵǰɉⓙj]/g,
- k: /[kķƙǩḱḳḵⓚⱪꝁꝃꝅꞣk]/g,
- l: /[lĺļľŀłſƚɫḷḹḻḽⓛⱡꝇꝉꞁl]/g,
- lj: /lj/g,
- m: /[mɯɱḿṁṃⓜm]/g,
- n: /[nñńņňʼnƞǹɲṅṇṉṋⓝꞑꞥn]/g,
- nj: /nj/g,
- o: /[oòóôõöøōŏőơǒǫǭǿȍȏȫȭȯȱɔɵṍṏṑṓọỏốồổỗộớờởỡợⓞꝋꝍo]/g,
- oi: /ƣ/g,
- ou: /ȣ/g,
- oo: /ꝏ/g,
- p: /[pƥᵽṕṗⓟꝑꝓꝕp]/g,
- q: /[qɋⓠꝗꝙq]/g,
- r: /[rŕŗřȑȓɍɽṙṛṝṟⓡꝛꞃꞧr]/g,
- s: /[sßśŝşšșȿṡṣṥṧṩẛⓢꞅꞩs]/g,
- t: /[tţťŧƭțʈṫṭṯṱẗⓣⱦꞇt]/g,
- tz: /ꜩ/g,
- u: /[uùúûüũūŭůűųưǔǖǘǚǜȕȗʉṳṵṷṹṻụủứừửữựⓤu]/g,
- v: /[vʋʌṽṿⓥꝟv]/g,
- vy: /ꝡ/g,
- w: /[wŵẁẃẅẇẉẘⓦⱳw]/g,
- x: /[xẋẍⓧx]/g,
- y: /[yýÿŷƴȳɏẏẙỳỵỷỹỿⓨy]/g,
- z: /[zźżžƶȥɀẑẓẕⓩⱬꝣz]/g
- };
- let parsedString = input;
- Object.entries(removalMap).forEach(([key, value]) => {
- parsedString = parsedString.replace(value, key);
- });
- return parsedString;
- }
- function removeEmojis(input) {
- const baseEmojiRegex = /[\u2700-\u27bf]|\ud83c[\udde6-\uddff]{2}|[\ud800-\udbff][\udc00-\udfff]/;
- const variationSelectorRegex = /[\ufe0e\ufe0f]?/;
- const modifierRegex = /[\u0300-\u036f\u20d0-\u20f0\ufe20-\ufe23]|\ud83c[\udffb-\udfff]/;
- const zeroWidthJoinerRegex = /\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\u20d0-\u20f0\ufe20-\ufe23]|\ud83c[\udffb-\udfff])?/;
- const emojiRegex = new RegExp(
- `(?:${baseEmojiRegex.source})${variationSelectorRegex.source}(?:${modifierRegex.source})?(?:${zeroWidthJoinerRegex.source})*`,
- "g"
- );
- return input.replace(emojiRegex, "").trim();
- }
- function removeEmptyTags(input) {
- return input.replace(/<[^/>][^>]*>\s*<\/[^>]+>/gi, "");
- }
- function removeNonPrintableCharacters(input) {
- return input.replace(/[^\x20-\x7E´\u00C0-\u00FFˆ˜]+/g, "");
- }
- function removeTags(input) {
- return input.replace(/(<([^>]+)>)/gi, "");
- }
- function removeWhitespace(input) {
- return input.replace(/\r\n|\r|\n|\t/g, "").replace(/ +/g, " ");
- }
- function slugify(input) {
- return removeAccents(input).replace(/[\u0300-\u036f]/g, "").replace(/[()]/g, "").replace(/ /g, "-").replace(/["%<>\\^`{|}]/g, "").toLowerCase();
- }
- // src/date.ts
- var MINUTE = 60;
- var HOUR = MINUTE * 60;
- var DAY = HOUR * 24;
- var WEEK = DAY * 7;
- var MONTH = DAY * 30;
- var YEAR = 365 * DAY;
- function isIsoDate(input) {
- if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(input)) {
- return false;
- }
- const date = new Date(input);
- return date.toISOString() === input;
- }
- function isoDate(input) {
- if (typeof input !== "undefined") {
- return new Date(input).toISOString();
- }
- return (/* @__PURE__ */ new Date()).toISOString();
- }
- function isValidDate(input) {
- const date = is2.date(input) ? input : new Date(input);
- return !Number.isNaN(date.getTime());
- }
- function now() {
- return Math.floor(Date.now() / 1e3);
- }
- function timeSince(input, options) {
- const {
- day = "day",
- days,
- hour = "hour",
- hours,
- minute = "minute",
- minutes,
- month = "month",
- months,
- prefix,
- second = "second",
- seconds,
- skipWeeks = false,
- suffix = "ago",
- week = "week",
- weeks,
- year = "year",
- years
- } = options || {};
- const date = typeof input === "number" ? input : timestamp(input);
- const diff = now() - date;
- let quantity = Math.floor(diff / YEAR);
- const output = (value, caption) => {
- let result = `${value} ${caption}`;
- if (prefix) {
- result = `${prefix} ${result}`;
- }
- if (suffix) {
- result = `${result} ${suffix}`;
- }
- return result;
- };
- if (quantity >= 1) {
- return output(quantity, pluralize(quantity, year, years));
- }
- quantity = Math.floor(diff / MONTH);
- if (quantity > 1) {
- return output(quantity, pluralize(quantity, month, months));
- }
- if (!skipWeeks) {
- quantity = Math.floor(diff / WEEK);
- if (quantity > 1) {
- return output(quantity, pluralize(quantity, week, weeks));
- }
- }
- quantity = Math.floor(diff / DAY);
- if (quantity >= 1) {
- return output(quantity, pluralize(quantity, day, days));
- }
- quantity = Math.floor(diff / HOUR);
- if (quantity >= 1) {
- return output(quantity, pluralize(quantity, hour, hours));
- }
- quantity = Math.floor(diff / MINUTE);
- if (quantity > 1) {
- return output(quantity, pluralize(quantity, minute, minutes));
- }
- return output(Math.floor(diff), pluralize(diff, second, seconds));
- }
- function timestamp(input) {
- if (!input) {
- return now();
- }
- const date = typeof input === "string" ? new Date(input) : input;
- return Math.floor(date.getTime() / 1e3);
- }
- // src/devices.ts
- function isDarkMode() {
- return !!window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
- }
- function isTouchDevice() {
- return !!window.matchMedia && window.matchMedia("(pointer: coarse)").matches;
- }
- function prefersReducedMotion() {
- return !!window.matchMedia && window.matchMedia("prefers-reduced-motion").matches;
- }
- // src/formatters.ts
- function formatBoolean(input) {
- return input ? "Yes" : "No";
- }
- function formatCPF(value) {
- const clearValue = cleanupNumericString(value);
- if (clearValue.length >= 10) {
- return `${clearValue.slice(0, 3)}.${clearValue.slice(3, 6)}.${clearValue.slice(
- 6,
- 9
- )}-${clearValue.slice(9, 11)}`;
- } else if (clearValue.length >= 7) {
- return `${clearValue.slice(0, 3)}.${clearValue.slice(3, 6)}.${clearValue.slice(6, 9)}`;
- } else if (clearValue.length >= 4) {
- return `${clearValue.slice(0, 3)}.${clearValue.slice(3, 6)}`;
- }
- return clearValue;
- }
- function formatDateLocale(input, options = {}) {
- const { locale = "en-GB", showTime = false } = options;
- const formatOptions = {
- year: "2-digit",
- month: "2-digit",
- day: "2-digit"
- };
- if (showTime) {
- formatOptions.hour = "2-digit";
- formatOptions.minute = "2-digit";
- }
- return new Date(input).toLocaleDateString(locale, formatOptions);
- }
- function formatMoney(input, options = {}) {
- const { decimalChar = ".", showCents = false, symbol = "$", thousandsChar = "," } = options;
- const isNegative = input < 0;
- const value = Math.abs(input);
- const [amount, cents] = value.toFixed(2).split(".");
- const padStart = amount.length > 3 ? amount.length % 3 : 0;
- const initial = amount.slice(0, padStart);
- const remain = amount.slice(padStart).replace(/(\d{3})(?=\d)/g, `$1${thousandsChar}`);
- let formatted = `${remain}`;
- if (initial) {
- formatted = `${initial}${thousandsChar}${remain}`;
- }
- if (cents !== "00" || showCents) {
- formatted += `${decimalChar}${cents}`;
- }
- return `${isNegative ? "-" : ""}${symbol}${formatted}`;
- }
- function formatPhoneBR(input) {
- const phone = input.replace(/\D/g, "");
- if (phone.length === 8) {
- return phone.replace(/^(\d{4})(\d{4}).*/, "$1-$2");
- }
- if (phone.length === 9) {
- return phone.replace(/^(\d{5})(\d{4}).*/, "$1-$2");
- }
- if (phone.length === 10 || phone.length === 11) {
- return phone.replace(/^(\d{2})(\d{4,5})(\d{4}).*/, "($1) $2-$3");
- }
- return phone;
- }
- function formatPhoneUS(input) {
- const phone = input.replace(/\D/g, "");
- if (phone.length === 10) {
- return phone.replace(/^(\d{3})(\d{3})(\d{4}).*/, "($1) $2-$3");
- }
- if (phone.length === 11 && phone.startsWith("1")) {
- return phone.replace(/^1(\d{3})(\d{3})(\d{4}).*/, "+1 ($1) $2-$3");
- }
- return phone;
- }
- function formatPostalCodeBR(value) {
- const clearValue = cleanupNumericString(value);
- if (clearValue.length >= 6) {
- return `${clearValue.slice(0, 5)}-${clearValue.slice(5, 8)}`;
- }
- return clearValue;
- }
- // src/functions.ts
- function demethodize(fn) {
- return (parameter, ...rest) => fn.apply(parameter, rest);
- }
- async function measureExecutionTime(callback) {
- const start = performance.now();
- const result = await callback();
- const end = performance.now();
- const total = end - start;
- console.log(`Completed in ${Math.ceil(total)} milliseconds`);
- return result;
- }
- function noop() {
- return void 0;
- }
- function once(fn) {
- let done = false;
- let result;
- return function Fn(...arguments_) {
- if (!done) {
- done = true;
- result = fn(...arguments_);
- }
- return result;
- };
- }
- function pipe(...fns) {
- return (input) => fns.reduce((previousValue, fn) => fn(previousValue), input);
- }
- // src/misc.ts
- import is3 from "is-lite";
- // src/numbers.ts
- function ceil(input, digits = 2) {
- const factor = 10 ** digits;
- return Math.ceil(input * factor) / factor;
- }
- function clamp(value, min = 0, max = 100) {
- return Math.min(Math.max(value, min), max);
- }
- function floor(input, digits = 2) {
- const factor = 10 ** digits;
- return Math.floor(input * factor) / factor;
- }
- function pad(input, length = 2) {
- return `${input}`.padStart(length, "0");
- }
- function randomNumber(min = 0, max = 10) {
- if (min >= max) {
- return max;
- }
- return Math.floor(Math.random() * (max - min + 1) + min);
- }
- function round(input, digits = 2) {
- const factor = 10 ** digits;
- return Math.round(input * factor) / factor;
- }
- // src/misc.ts
- function conditional(cases, defaultCase) {
- for (const [expression, callback] of cases) {
- if (expression) {
- return callback();
- }
- }
- return defaultCase?.();
- }
- async function copyToClipboard(input) {
- try {
- await navigator.clipboard.writeText(input);
- } catch {
- return false;
- }
- return true;
- }
- function getDataType(input, toLowerCase = false) {
- const dataTypeName = Object.prototype.toString.call(input).slice(8, -1);
- let output = dataTypeName;
- if (/HTML\w+Element/.test(dataTypeName)) {
- output = "HTMLElement";
- }
- return toLowerCase ? output.toLowerCase() : output;
- }
- function invariant(condition, message) {
- if (condition) {
- return;
- }
- const value = is3.function(message) ? message() : message;
- throw new Error(value);
- }
- function isJSON(input) {
- try {
- JSON.parse(input);
- } catch {
- return false;
- }
- return true;
- }
- function isRequired(input = "parameter", Constructable = TypeError) {
- throw new Constructable(`"${input}" is required`);
- }
- function logger(type, title, data, options = {}) {
- const { collapsed = true, hideTimestamp = false, skip = false, typeColor = "gray" } = options;
- const groupMethod = collapsed ? console.groupCollapsed : console.group;
- const date = /* @__PURE__ */ new Date();
- const parts = [`%c ${type}`];
- const styles = [`color: ${typeColor}; font-weight: lighter;`, "color: inherit;"];
- if (!hideTimestamp) {
- styles.push("color: gray; font-weight: lighter;");
- }
- const time = `${pad(date.getHours(), 2)}:${pad(date.getMinutes(), 2)}:${pad(
- date.getSeconds(),
- 2
- )}`;
- parts.push(`%c${title}`);
- if (!hideTimestamp) {
- parts.push(`%c@ ${time}`);
- }
- if (!skip) {
- groupMethod(parts.join(" "), ...styles);
- console.log(data);
- console.groupEnd();
- }
- }
- function nullify(value) {
- return value ?? null;
- }
- function popupCenter(url, title, width, height) {
- const { screen, screenLeft, screenTop } = window;
- let screenWidth = window.innerWidth;
- let screenHeight = window.innerHeight;
- if (!screenWidth) {
- screenWidth = document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
- }
- if (!screenHeight) {
- screenHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
- }
- const left = screenWidth / 2 - width / 2 + screenLeft;
- const top = screenHeight / 2 - height / 2 + screenTop;
- const popup = window.open(
- url,
- title,
- `menubar=no,location=no,resizable=no,scrollbars=yees,status=no,width=${width},height=${height},top=${top}, left=${left}`
- );
- if (popup) {
- popup.focus();
- }
- return popup;
- }
- function px(value) {
- return is3.number(value) || is3.numericString(value) ? `${value}px` : value;
- }
- function unique(length = 8, options = {}) {
- const {
- includeLowercase = true,
- includeNumbers = true,
- includeSymbols = false,
- includeUppercase = true
- } = options;
- const lowercase = "abcdefghijklmnopqrstuvwxyz";
- const uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- const numbers = "0123456789";
- const symbols = "!?@#$%^&*+_-=:.~";
- let characters = "";
- if (includeLowercase) {
- characters += lowercase;
- }
- if (includeUppercase) {
- characters += uppercase;
- }
- if (includeNumbers) {
- characters += numbers;
- }
- if (includeSymbols) {
- characters += symbols;
- }
- let result = "";
- for (let index = length; index > 0; --index) {
- result += characters[Math.round(Math.random() * (characters.length - 1))];
- }
- return result;
- }
- function uuid() {
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
- const r = Math.random() * 16 | 0;
- const v = c === "x" ? r : r & 3 | 8;
- return v.toString(16);
- });
- }
- // src/objects.ts
- import is4 from "is-lite";
- function cleanUpObject(input) {
- const output = {};
- for (const key in input) {
- if (input[key] !== void 0) {
- output[key] = input[key];
- }
- }
- return output;
- }
- function getNestedProperty(input, path) {
- if (!is4.plainObject(input) && !is4.array(input) || !path) {
- return input;
- }
- const segments = path.split(".");
- const { length } = segments;
- let output = input;
- for (let index = 0; index < length; index++) {
- const currentSegment = segments[index];
- const remainingSegments = segments.slice(index + 1);
- if (currentSegment === "+" && is4.array(output) && remainingSegments.length === 1) {
- return output.map((d) => d[remainingSegments.join(".")]);
- }
- try {
- output = output[currentSegment];
- } catch {
- }
- }
- return output;
- }
- function invertKeys(input) {
- if (!is4.plainObject(input)) {
- throw new TypeError("Expected an object");
- }
- const result = {};
- for (const [key, value] of Object.entries(input)) {
- result[value] = key;
- }
- return result;
- }
- function keyMirror(input) {
- if (!is4.plainObject(input)) {
- throw new TypeError("Expected an object");
- }
- const output = {};
- for (const key in input) {
- if (!Object.prototype.hasOwnProperty.call(output, key)) {
- output[key] = key;
- }
- }
- return output;
- }
- function mergeProps(defaultProps, props) {
- const cleanProps = cleanUpObject(props);
- return { ...defaultProps, ...cleanProps };
- }
- function objectEntries(input) {
- return Object.entries(input);
- }
- function objectKeys(input) {
- return Object.keys(input);
- }
- function objectToArray(input, includeOnly) {
- if (!is4.plainObject(input)) {
- throw new TypeError("Expected an object");
- }
- return Object.entries(input).filter(([, value]) => includeOnly ? typeof value === `${includeOnly}` : true).map(([key, value]) => ({ [key]: value }));
- }
- function omit(input, ...filter) {
- if (!is4.plainObject(input)) {
- throw new TypeError("Expected an object");
- }
- const output = {};
- for (const key in input) {
- if ({}.hasOwnProperty.call(input, key)) {
- if (!filter.includes(key)) {
- output[key] = input[key];
- }
- }
- }
- return output;
- }
- function pick(input, ...filter) {
- if (!is4.plainObject(input)) {
- throw new TypeError("Expected an object");
- }
- if (!filter.length) {
- return input;
- }
- const output = {};
- for (const key in input) {
- if ({}.hasOwnProperty.call(input, key)) {
- if (filter.includes(key)) {
- output[key] = input[key];
- }
- }
- }
- return output;
- }
- function queryStringFormat(input, options = {}) {
- const { addPrefix = false, encoder = encodeURIComponent, encodeValuesOnly = true } = options;
- if (!is4.plainObject(input)) {
- throw new TypeError("input type isn't supported");
- }
- const isValidInput = Object.values(input).every((item) => {
- if (is4.array(item)) {
- return item.every((d) => is4.string(d) || is4.number(d));
- }
- return is4.string(item);
- });
- if (!isValidInput) {
- throw new TypeError("input format isn't supported");
- }
- const output = Object.entries(input).map(([key, value]) => {
- const nextKey = encodeValuesOnly ? key : encoder(key);
- const nextValue = is4.array(value) ? value.map(encoder).join(",") : encoder(`${value}`);
- return `${nextKey}=${nextValue}`;
- }).join("&");
- return `${addPrefix ? "?" : ""}${output}`;
- }
- function queryStringParse(input) {
- let search = input;
- if (input.slice(0, 1) === "?") {
- search = input.slice(1);
- }
- return search.split("&").reduce((acc, d) => {
- const [key, value] = d.split("=");
- acc[decodeURIComponent(key)] = decodeURIComponent(value);
- return acc;
- }, {});
- }
- function sortObjectKeys(input) {
- return objectKeys(input).sort().reduce((acc, key) => {
- acc[key] = input[key];
- return acc;
- }, {});
- }
- // src/statistics.ts
- import is5 from "is-lite";
- function mean(input, precision) {
- const output = input.reduce((sum, value) => sum + value, 0) / input.length;
- if (is5.number(precision)) {
- return round(output, precision);
- }
- return output;
- }
- function median(input) {
- const sorted = [...input].sort((a, b) => a - b);
- const middle = Math.floor(sorted.length / 2);
- if (sorted.length % 2 === 0) {
- return (sorted[middle - 1] + sorted[middle]) / 2;
- }
- return sorted[middle];
- }
- function mode(input) {
- const count = /* @__PURE__ */ new Map();
- for (const value of input) {
- const current = count.get(value) ?? 0;
- count.set(value, current + 1);
- }
- const sorted = [...count.entries()].sort((a, b) => b[1] - a[1]);
- return sorted[0][0];
- }
- // src/validators.ts
- function isValidCPF(value) {
- if (!value) {
- return false;
- }
- const newValue = value.replace(/[.-]/g, "");
- let sum = 0;
- let rest;
- if (/^(\d)\1+$/.test(newValue)) {
- return false;
- }
- for (let index = 1; index <= 9; index++) {
- sum += parseInt(newValue.substring(index - 1, index), 10) * (11 - index);
- }
- rest = sum * 10 % 11;
- if (rest === 10 || rest === 11) {
- rest = 0;
- }
- if (rest !== parseInt(newValue.substring(9, 10), 10)) {
- return false;
- }
- sum = 0;
- for (let index = 1; index <= 10; index++) {
- sum += parseInt(newValue.substring(index - 1, index), 10) * (12 - index);
- }
- rest = sum * 10 % 11;
- if (rest === 10 || rest === 11) {
- rest = 0;
- }
- return rest === parseInt(newValue.substring(10, 11), 10);
- }
- function isValidEmail(value) {
- return /^[\w%+.-]+@[\d.a-z-]+\.[a-z]{2,}$/i.test(value);
- }
- function validatePassword(password, options) {
- const {
- maxLength = 64,
- maxLengthMessage = "Password must be a maximum of 64 characters",
- minLength = 6,
- minLengthMessage = "Password must be at least 6 characters long",
- regex = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!#$%&*?@^]).*$/,
- requiredCharactersMessage = "Password must have at least 1 number, 1 lowercase, 1 uppercase and 1 special character"
- } = options || {};
- if (password.length < minLength) {
- throw new Error(minLengthMessage);
- }
- if (password.length > maxLength) {
- throw new Error(maxLengthMessage);
- }
- if (!regex.test(password)) {
- throw new Error(requiredCharactersMessage);
- }
- return true;
- }
- // src/types.ts
- var types_exports = {};
- export {
- ASYNC_STATUS,
- DAY,
- HOUR,
- MINUTE,
- MONTH,
- types_exports as Types,
- WEEK,
- YEAR,
- capitalize,
- ceil,
- clamp,
- cleanUpObject,
- cleanupHTML,
- cleanupNumericString,
- cleanupURI,
- conditional,
- copyToClipboard,
- cors,
- createArray,
- demethodize,
- floor,
- formatBoolean,
- formatCPF,
- formatDateLocale,
- formatMoney,
- formatPhoneBR,
- formatPhoneUS,
- formatPostalCodeBR,
- getDataType,
- getInitials,
- getNestedProperty,
- getRandomItem,
- invariant,
- invertKeys,
- isDarkMode,
- isIsoDate,
- isJSON,
- isRequired,
- isTouchDevice,
- isValidCPF,
- isValidDate,
- isValidEmail,
- isoDate,
- keyMirror,
- logger,
- mean,
- measureExecutionTime,
- median,
- mergeProps,
- mode,
- noop,
- now,
- nullify,
- objectEntries,
- objectKeys,
- objectToArray,
- omit,
- once,
- pad,
- pick,
- pipe,
- pluralize,
- poll,
- popupCenter,
- prefersReducedMotion,
- px,
- queryStringFormat,
- queryStringParse,
- quickSort,
- randomNumber,
- removeAccents,
- removeDuplicates,
- removeEmojis,
- removeEmptyTags,
- removeNonPrintableCharacters,
- removeTags,
- removeWhitespace,
- request,
- round,
- shuffle,
- sleep,
- slugify,
- sortByLocaleCompare,
- sortByPrimitive,
- sortComparator,
- sortObjectKeys,
- splitIntoChunks,
- timeSince,
- timestamp,
- unique,
- uuid,
- validatePassword
- };
- //# sourceMappingURL=index.mjs.map
|