1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180 |
- "use strict";
- var __create = Object.create;
- var __defProp = Object.defineProperty;
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
- var __getOwnPropNames = Object.getOwnPropertyNames;
- var __getProtoOf = Object.getPrototypeOf;
- var __hasOwnProp = Object.prototype.hasOwnProperty;
- var __export = (target, all) => {
- for (var name in all)
- __defProp(target, name, { get: all[name], enumerable: true });
- };
- var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
- }
- return to;
- };
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
- // If the importer is in node compatibility mode or this is not an ESM
- // file that has been converted to a CommonJS file using a Babel-
- // compatible transform (i.e. "__esModule" has not been set), then set
- // "default" to the CommonJS "module.exports" for node compatibility.
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
- mod
- ));
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
- // src/index.ts
- var src_exports = {};
- __export(src_exports, {
- ASYNC_STATUS: () => ASYNC_STATUS,
- DAY: () => DAY,
- HOUR: () => HOUR,
- MINUTE: () => MINUTE,
- MONTH: () => MONTH,
- Types: () => types_exports,
- WEEK: () => WEEK,
- YEAR: () => YEAR,
- capitalize: () => capitalize,
- ceil: () => ceil,
- clamp: () => clamp,
- cleanUpObject: () => cleanUpObject,
- cleanupHTML: () => cleanupHTML,
- cleanupNumericString: () => cleanupNumericString,
- cleanupURI: () => cleanupURI,
- conditional: () => conditional,
- copyToClipboard: () => copyToClipboard,
- cors: () => cors,
- createArray: () => createArray,
- demethodize: () => demethodize,
- floor: () => floor,
- formatBoolean: () => formatBoolean,
- formatCPF: () => formatCPF,
- formatDateLocale: () => formatDateLocale,
- formatMoney: () => formatMoney,
- formatPhoneBR: () => formatPhoneBR,
- formatPhoneUS: () => formatPhoneUS,
- formatPostalCodeBR: () => formatPostalCodeBR,
- getDataType: () => getDataType,
- getInitials: () => getInitials,
- getNestedProperty: () => getNestedProperty,
- getRandomItem: () => getRandomItem,
- invariant: () => invariant,
- invertKeys: () => invertKeys,
- isDarkMode: () => isDarkMode,
- isIsoDate: () => isIsoDate,
- isJSON: () => isJSON,
- isRequired: () => isRequired,
- isTouchDevice: () => isTouchDevice,
- isValidCPF: () => isValidCPF,
- isValidDate: () => isValidDate,
- isValidEmail: () => isValidEmail,
- isoDate: () => isoDate,
- keyMirror: () => keyMirror,
- logger: () => logger,
- mean: () => mean,
- measureExecutionTime: () => measureExecutionTime,
- median: () => median,
- mergeProps: () => mergeProps,
- mode: () => mode,
- noop: () => noop,
- now: () => now,
- nullify: () => nullify,
- objectEntries: () => objectEntries,
- objectKeys: () => objectKeys,
- objectToArray: () => objectToArray,
- omit: () => omit,
- once: () => once,
- pad: () => pad,
- pick: () => pick,
- pipe: () => pipe,
- pluralize: () => pluralize,
- poll: () => poll,
- popupCenter: () => popupCenter,
- prefersReducedMotion: () => prefersReducedMotion,
- px: () => px,
- queryStringFormat: () => queryStringFormat,
- queryStringParse: () => queryStringParse,
- quickSort: () => quickSort,
- randomNumber: () => randomNumber,
- removeAccents: () => removeAccents,
- removeDuplicates: () => removeDuplicates,
- removeEmojis: () => removeEmojis,
- removeEmptyTags: () => removeEmptyTags,
- removeNonPrintableCharacters: () => removeNonPrintableCharacters,
- removeTags: () => removeTags,
- removeWhitespace: () => removeWhitespace,
- request: () => request,
- round: () => round,
- shuffle: () => shuffle,
- sleep: () => sleep,
- slugify: () => slugify,
- sortByLocaleCompare: () => sortByLocaleCompare,
- sortByPrimitive: () => sortByPrimitive,
- sortComparator: () => sortComparator,
- sortObjectKeys: () => sortObjectKeys,
- splitIntoChunks: () => splitIntoChunks,
- timeSince: () => timeSince,
- timestamp: () => timestamp,
- unique: () => unique,
- uuid: () => uuid,
- validatePassword: () => validatePassword
- });
- module.exports = __toCommonJS(src_exports);
- // 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
- var import_is_lite = __toESM(require("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
- } = import_is_lite.default.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 = import_is_lite.default.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
- var import_is_lite2 = __toESM(require("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 = import_is_lite2.default.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
- var import_is_lite3 = __toESM(require("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 = import_is_lite3.default.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 import_is_lite3.default.number(value) || import_is_lite3.default.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
- var import_is_lite4 = __toESM(require("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 (!import_is_lite4.default.plainObject(input) && !import_is_lite4.default.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 === "+" && import_is_lite4.default.array(output) && remainingSegments.length === 1) {
- return output.map((d) => d[remainingSegments.join(".")]);
- }
- try {
- output = output[currentSegment];
- } catch {
- }
- }
- return output;
- }
- function invertKeys(input) {
- if (!import_is_lite4.default.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 (!import_is_lite4.default.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 (!import_is_lite4.default.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 (!import_is_lite4.default.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 (!import_is_lite4.default.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 (!import_is_lite4.default.plainObject(input)) {
- throw new TypeError("input type isn't supported");
- }
- const isValidInput = Object.values(input).every((item) => {
- if (import_is_lite4.default.array(item)) {
- return item.every((d) => import_is_lite4.default.string(d) || import_is_lite4.default.number(d));
- }
- return import_is_lite4.default.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 = import_is_lite4.default.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
- var import_is_lite5 = __toESM(require("is-lite"));
- function mean(input, precision) {
- const output = input.reduce((sum, value) => sum + value, 0) / input.length;
- if (import_is_lite5.default.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 = {};
- // Annotate the CommonJS export names for ESM import in node:
- 0 && (module.exports = {
- ASYNC_STATUS,
- DAY,
- HOUR,
- MINUTE,
- MONTH,
- 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.js.map
|