index.mjs 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. // src/arrays.ts
  2. function createArray(size, start = 1) {
  3. return Array.from({ length: size }, (_, index) => index + start);
  4. }
  5. function getRandomItem(input) {
  6. return input[Math.floor(Math.random() * input.length)];
  7. }
  8. function quickSort(input, comparator = sortComparator) {
  9. const output = [...input];
  10. const recursiveSort = (start, end) => {
  11. if (end - start < 1) {
  12. return;
  13. }
  14. const pivotValue = output[end];
  15. let splitIndex = start;
  16. for (let index = start; index < end; index++) {
  17. const sort = comparator(output[index], pivotValue);
  18. if (sort === -1) {
  19. if (splitIndex !== index) {
  20. const temp = output[splitIndex];
  21. output[splitIndex] = output[index];
  22. output[index] = temp;
  23. }
  24. splitIndex++;
  25. }
  26. }
  27. output[end] = output[splitIndex];
  28. output[splitIndex] = pivotValue;
  29. recursiveSort(start, splitIndex - 1);
  30. recursiveSort(splitIndex + 1, end);
  31. };
  32. recursiveSort(0, input.length - 1);
  33. return output;
  34. }
  35. function removeDuplicates(input) {
  36. return [...new Set(input)];
  37. }
  38. function shuffle(input) {
  39. let currentIndex = input.length;
  40. let randomIndex;
  41. let temporaryValue;
  42. const output = [...input];
  43. while (currentIndex) {
  44. randomIndex = Math.floor(Math.random() * currentIndex--);
  45. temporaryValue = output[currentIndex];
  46. output[currentIndex] = output[randomIndex];
  47. output[randomIndex] = temporaryValue;
  48. }
  49. return output;
  50. }
  51. function sortByLocaleCompare(key, options = {}) {
  52. const { descending, ...compareOptions } = options;
  53. if (key) {
  54. if (descending) {
  55. return (left, right) => right[key].toLowerCase().localeCompare(left[key].toLowerCase(), void 0, compareOptions);
  56. }
  57. return (left, right) => left[key].toLowerCase().localeCompare(right[key].toLowerCase(), void 0, compareOptions);
  58. }
  59. if (descending) {
  60. return (left, right) => right.toLowerCase().localeCompare(left.toLowerCase(), void 0, compareOptions);
  61. }
  62. return (left, right) => left.toLowerCase().localeCompare(right.toLowerCase(), void 0, compareOptions);
  63. }
  64. function sortByPrimitive(key, descending = false) {
  65. const firstComparator = descending ? 1 : -1;
  66. const secondComparator = descending ? -1 : 1;
  67. if (key) {
  68. return (left, right) => {
  69. if (left[key] === right[key]) {
  70. return 0;
  71. }
  72. return left[key] < right[key] ? firstComparator : secondComparator;
  73. };
  74. }
  75. return (left, right) => {
  76. if (left === right) {
  77. return 0;
  78. }
  79. return left < right ? firstComparator : secondComparator;
  80. };
  81. }
  82. function sortComparator(left, right) {
  83. if (left < right) {
  84. return -1;
  85. }
  86. if (left > right) {
  87. return 1;
  88. }
  89. return 0;
  90. }
  91. function splitIntoChunks(input, chunkSize = 25) {
  92. if (!Array.isArray(input)) {
  93. throw new TypeError("expected an array for the first argument");
  94. }
  95. const chunks = [];
  96. for (let index = 0; index < Math.ceil(input.length / chunkSize); index++) {
  97. chunks.push(input.slice(index * chunkSize, (index + 1) * chunkSize));
  98. }
  99. return chunks;
  100. }
  101. // src/async.ts
  102. import is from "is-lite";
  103. var ASYNC_STATUS = {
  104. IDLE: "IDLE",
  105. PENDING: "PENDING",
  106. SUCCESS: "SUCCESS",
  107. ERROR: "ERROR"
  108. };
  109. function cors(data, statusCodeOrOptions = 200) {
  110. const {
  111. allowCredentials = true,
  112. allowedHeaders = [],
  113. methods = ["GET"],
  114. origin = "*",
  115. responseHeaders = void 0,
  116. statusCode = 200
  117. } = is.number(statusCodeOrOptions) ? { statusCode: statusCodeOrOptions } : statusCodeOrOptions;
  118. const allowMethods = [...methods, "OPTIONS"];
  119. const allowHeaders = [
  120. .../* @__PURE__ */ new Set([
  121. "Accept-Version",
  122. "Accept",
  123. "Authorization",
  124. "Content-Length",
  125. "Content-MD5",
  126. "Content-Type",
  127. "Date",
  128. "x-amz-date",
  129. "x-amz-security-token",
  130. "X-Api-Version",
  131. "X-CSRF-Token",
  132. "X-Requested-With",
  133. ...allowedHeaders
  134. ])
  135. ];
  136. let exposedHeaders;
  137. if (responseHeaders) {
  138. exposedHeaders = {
  139. "Access-Control-Expose-Headers": Object.keys(responseHeaders).join(","),
  140. ...responseHeaders
  141. };
  142. }
  143. return {
  144. body: JSON.stringify(data),
  145. headers: {
  146. "Access-Control-Allow-Origin": origin,
  147. "Access-Control-Allow-Credentials": allowCredentials,
  148. "Access-Control-Allow-Methods": allowMethods.join(","),
  149. "Access-Control-Allow-Headers": allowHeaders.join(","),
  150. ...exposedHeaders
  151. },
  152. statusCode
  153. };
  154. }
  155. async function poll(condition, options = {}) {
  156. const { delay = 1, maxRetries = 5 } = options;
  157. let retries = 0;
  158. while (!condition() && retries <= maxRetries) {
  159. await sleep(delay);
  160. retries++;
  161. }
  162. if (retries >= maxRetries) {
  163. throw new Error("Timeout");
  164. }
  165. }
  166. async function request(url, options = {}) {
  167. const { body, headers, method = "GET" } = options;
  168. if (!url) {
  169. throw new Error("URL is required");
  170. }
  171. const params = {
  172. headers: {
  173. Accept: "application/json",
  174. "Content-Type": "application/json",
  175. ...headers
  176. },
  177. method
  178. };
  179. if (body) {
  180. params.body = is.plainObject(body) ? JSON.stringify(body) : body;
  181. }
  182. return fetch(url, params).then(async (response) => {
  183. const text = await response.text();
  184. let content;
  185. try {
  186. content = JSON.parse(text);
  187. } catch {
  188. content = text;
  189. }
  190. if (response.status > 299) {
  191. const error = new Error(response.statusText);
  192. error.status = response.status;
  193. error.response = content;
  194. throw error;
  195. } else {
  196. return content;
  197. }
  198. });
  199. }
  200. function sleep(seconds = 1) {
  201. return new Promise((resolve) => {
  202. setTimeout(resolve, seconds * 1e3);
  203. });
  204. }
  205. // src/date.ts
  206. import is2 from "is-lite";
  207. // src/strings.ts
  208. function capitalize(input) {
  209. return input.charAt(0).toLocaleUpperCase() + input.slice(1).toLocaleLowerCase();
  210. }
  211. function cleanupHTML(input) {
  212. return removeWhitespace(removeEmptyTags(input));
  213. }
  214. function cleanupNumericString(value = "") {
  215. return value.replace(/\D+/g, "");
  216. }
  217. function cleanupURI(input) {
  218. return input.replace(/[$&+,/:;=?@]/g, "");
  219. }
  220. function getInitials(input) {
  221. if (!input) {
  222. return "";
  223. }
  224. const names = input.trim().split(" ");
  225. if (names.length === 1) {
  226. return `${names[0].charAt(0)}`;
  227. }
  228. return `${names[0].charAt(0)}${names[names.length - 1].charAt(0)}`;
  229. }
  230. function pluralize(quantity, singular, plural) {
  231. if (quantity === 1) {
  232. return singular;
  233. }
  234. return plural || `${singular}s`;
  235. }
  236. function removeAccents(input) {
  237. const removalMap = {
  238. A: /[AÀÁÂÃÄÅĀĂĄǍǞǠǺȀȂȦḀẠẢẤẦẨẪẬẮẰẲẴẶⒶA]/g,
  239. AA: /Ꜳ/g,
  240. AE: /[ÆǢǼ]/g,
  241. AO: /Ꜵ/g,
  242. AU: /Ꜷ/g,
  243. AV: /[ꜸꜺ]/g,
  244. AY: /Ꜽ/g,
  245. B: /[BƁƂɃḂḄḆⒷB]/g,
  246. C: /[CÇĆĈĊČƇȻḈⒸꜾC]/g,
  247. D: /[DĎĐƉƊƋḊḌḎḐḒⒹꝹD]/g,
  248. DZ: /[DŽDZ]/g,
  249. Dz: /[DžDz]/g,
  250. E: /[EÈÉÊËĒĔĖĘĚƎƐȄȆȨḔḖḘḚḜẸẺẼẾỀỂỄỆⒺE]/g,
  251. F: /[FƑḞⒻꝻF]/g,
  252. G: /[GĜĞĠĢƓǤǦǴḠⒼꝽꝾꞠG]/g,
  253. H: /[HĤĦȞḢḤḦḨḪⒽⱧⱵꞍH]/g,
  254. I: /[IÌÍÎÏĨĪĬĮİƗǏȈȊḬḮỈỊⒾI]/g,
  255. J: /[JĴɈⒿJ]/g,
  256. K: /[KĶƘǨḰḲḴⓀⱩꝀꝂꝄꞢK]/g,
  257. L: /[LĹĻĽĿŁȽḶḸḺḼⓁⱠⱢꝆꝈꞀL]/g,
  258. LJ: /LJ/g,
  259. Lj: /Lj/g,
  260. M: /[MƜḾṀṂⓂⱮM]/g,
  261. N: /[NÑŃŅŇƝǸȠṄṆṈṊⓃꞐꞤN]/g,
  262. NJ: /NJ/g,
  263. Nj: /Nj/g,
  264. O: /[OÒÓÔÕÖØŌŎŐƆƟƠǑǪǬǾȌȎȪȬȮȰṌṎṐṒỌỎỐỒỔỖỘỚỜỞỠỢⓄꝊꝌO]/g,
  265. OI: /Ƣ/g,
  266. OO: /Ꝏ/g,
  267. OU: /Ȣ/g,
  268. P: /[PƤṔṖⓅⱣꝐꝒꝔP]/g,
  269. Q: /[QɊⓆꝖꝘQ]/g,
  270. R: /[RŔŖŘȐȒɌṘṚṜṞⓇⱤꝚꞂꞦR]/g,
  271. S: /[SŚŜŞŠȘṠṢṤṦṨẞⓈⱾꞄꞨS]/g,
  272. T: /[TŢŤŦƬƮȚȾṪṬṮṰⓉꞆT]/g,
  273. TZ: /Ꜩ/g,
  274. U: /[UÙÚÛÜŨŪŬŮŰŲƯǓǕǗǙǛȔȖɄṲṴṶṸṺỤỦỨỪỬỮỰⓊU]/g,
  275. V: /[VƲɅṼṾⓋꝞV]/g,
  276. VY: /Ꝡ/g,
  277. W: /[WŴẀẂẄẆẈⓌⱲW]/g,
  278. X: /[XẊẌⓍX]/g,
  279. Y: /[YÝŶŸƳȲɎẎỲỴỶỸỾⓎY]/g,
  280. Z: /[ZŹŻŽƵȤẐẒẔⓏⱫⱿꝢZ]/g,
  281. a: /[aàáâãäåāăąǎǟǡǻȁȃȧɐḁẚạảấầẩẫậắằẳẵặⓐⱥa]/g,
  282. aa: /ꜳ/g,
  283. ae: /[æǣǽ]/g,
  284. ao: /ꜵ/g,
  285. au: /ꜷ/g,
  286. av: /[ꜹꜻ]/g,
  287. ay: /ꜽ/g,
  288. b: /[bƀƃɓḃḅḇⓑb]/g,
  289. c: /[cçćĉċčƈȼḉↄⓒꜿc]/g,
  290. d: /[dďđƌɖɗḋḍḏḑḓⓓꝺd]/g,
  291. dz: /[dždz]/g,
  292. e: /[eèéêëēĕėęěǝȅȇȩɇɛḕḗḙḛḝẹẻẽếềểễệⓔe]/g,
  293. f: /[fƒḟⓕꝼf]/g,
  294. g: /[gĝğġģǥǧǵɠᵹḡⓖꝿꞡg]/g,
  295. h: /[hĥħȟɥḣḥḧḩḫẖⓗⱨⱶh]/g,
  296. hv: /ƕ/g,
  297. i: /[iìíîïĩīĭįıǐȉȋɨḭḯỉịⓘi]/g,
  298. j: /[jĵǰɉⓙj]/g,
  299. k: /[kķƙǩḱḳḵⓚⱪꝁꝃꝅꞣk]/g,
  300. l: /[lĺļľŀłſƚɫḷḹḻḽⓛⱡꝇꝉꞁl]/g,
  301. lj: /lj/g,
  302. m: /[mɯɱḿṁṃⓜm]/g,
  303. n: /[nñńņňʼnƞǹɲṅṇṉṋⓝꞑꞥn]/g,
  304. nj: /nj/g,
  305. o: /[oòóôõöøōŏőơǒǫǭǿȍȏȫȭȯȱɔɵṍṏṑṓọỏốồổỗộớờởỡợⓞꝋꝍo]/g,
  306. oi: /ƣ/g,
  307. ou: /ȣ/g,
  308. oo: /ꝏ/g,
  309. p: /[pƥᵽṕṗⓟꝑꝓꝕp]/g,
  310. q: /[qɋⓠꝗꝙq]/g,
  311. r: /[rŕŗřȑȓɍɽṙṛṝṟⓡꝛꞃꞧr]/g,
  312. s: /[sßśŝşšșȿṡṣṥṧṩẛⓢꞅꞩs]/g,
  313. t: /[tţťŧƭțʈṫṭṯṱẗⓣⱦꞇt]/g,
  314. tz: /ꜩ/g,
  315. u: /[uùúûüũūŭůűųưǔǖǘǚǜȕȗʉṳṵṷṹṻụủứừửữựⓤu]/g,
  316. v: /[vʋʌṽṿⓥꝟv]/g,
  317. vy: /ꝡ/g,
  318. w: /[wŵẁẃẅẇẉẘⓦⱳw]/g,
  319. x: /[xẋẍⓧx]/g,
  320. y: /[yýÿŷƴȳɏẏẙỳỵỷỹỿⓨy]/g,
  321. z: /[zźżžƶȥɀẑẓẕⓩⱬꝣz]/g
  322. };
  323. let parsedString = input;
  324. Object.entries(removalMap).forEach(([key, value]) => {
  325. parsedString = parsedString.replace(value, key);
  326. });
  327. return parsedString;
  328. }
  329. function removeEmojis(input) {
  330. const baseEmojiRegex = /[\u2700-\u27bf]|\ud83c[\udde6-\uddff]{2}|[\ud800-\udbff][\udc00-\udfff]/;
  331. const variationSelectorRegex = /[\ufe0e\ufe0f]?/;
  332. const modifierRegex = /[\u0300-\u036f\u20d0-\u20f0\ufe20-\ufe23]|\ud83c[\udffb-\udfff]/;
  333. const zeroWidthJoinerRegex = /\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\u20d0-\u20f0\ufe20-\ufe23]|\ud83c[\udffb-\udfff])?/;
  334. const emojiRegex = new RegExp(
  335. `(?:${baseEmojiRegex.source})${variationSelectorRegex.source}(?:${modifierRegex.source})?(?:${zeroWidthJoinerRegex.source})*`,
  336. "g"
  337. );
  338. return input.replace(emojiRegex, "").trim();
  339. }
  340. function removeEmptyTags(input) {
  341. return input.replace(/<[^/>][^>]*>\s*<\/[^>]+>/gi, "");
  342. }
  343. function removeNonPrintableCharacters(input) {
  344. return input.replace(/[^\x20-\x7E´\u00C0-\u00FFˆ˜]+/g, "");
  345. }
  346. function removeTags(input) {
  347. return input.replace(/(<([^>]+)>)/gi, "");
  348. }
  349. function removeWhitespace(input) {
  350. return input.replace(/\r\n|\r|\n|\t/g, "").replace(/ +/g, " ");
  351. }
  352. function slugify(input) {
  353. return removeAccents(input).replace(/[\u0300-\u036f]/g, "").replace(/[()]/g, "").replace(/ /g, "-").replace(/["%<>\\^`{|}]/g, "").toLowerCase();
  354. }
  355. // src/date.ts
  356. var MINUTE = 60;
  357. var HOUR = MINUTE * 60;
  358. var DAY = HOUR * 24;
  359. var WEEK = DAY * 7;
  360. var MONTH = DAY * 30;
  361. var YEAR = 365 * DAY;
  362. function isIsoDate(input) {
  363. if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(input)) {
  364. return false;
  365. }
  366. const date = new Date(input);
  367. return date.toISOString() === input;
  368. }
  369. function isoDate(input) {
  370. if (typeof input !== "undefined") {
  371. return new Date(input).toISOString();
  372. }
  373. return (/* @__PURE__ */ new Date()).toISOString();
  374. }
  375. function isValidDate(input) {
  376. const date = is2.date(input) ? input : new Date(input);
  377. return !Number.isNaN(date.getTime());
  378. }
  379. function now() {
  380. return Math.floor(Date.now() / 1e3);
  381. }
  382. function timeSince(input, options) {
  383. const {
  384. day = "day",
  385. days,
  386. hour = "hour",
  387. hours,
  388. minute = "minute",
  389. minutes,
  390. month = "month",
  391. months,
  392. prefix,
  393. second = "second",
  394. seconds,
  395. skipWeeks = false,
  396. suffix = "ago",
  397. week = "week",
  398. weeks,
  399. year = "year",
  400. years
  401. } = options || {};
  402. const date = typeof input === "number" ? input : timestamp(input);
  403. const diff = now() - date;
  404. let quantity = Math.floor(diff / YEAR);
  405. const output = (value, caption) => {
  406. let result = `${value} ${caption}`;
  407. if (prefix) {
  408. result = `${prefix} ${result}`;
  409. }
  410. if (suffix) {
  411. result = `${result} ${suffix}`;
  412. }
  413. return result;
  414. };
  415. if (quantity >= 1) {
  416. return output(quantity, pluralize(quantity, year, years));
  417. }
  418. quantity = Math.floor(diff / MONTH);
  419. if (quantity > 1) {
  420. return output(quantity, pluralize(quantity, month, months));
  421. }
  422. if (!skipWeeks) {
  423. quantity = Math.floor(diff / WEEK);
  424. if (quantity > 1) {
  425. return output(quantity, pluralize(quantity, week, weeks));
  426. }
  427. }
  428. quantity = Math.floor(diff / DAY);
  429. if (quantity >= 1) {
  430. return output(quantity, pluralize(quantity, day, days));
  431. }
  432. quantity = Math.floor(diff / HOUR);
  433. if (quantity >= 1) {
  434. return output(quantity, pluralize(quantity, hour, hours));
  435. }
  436. quantity = Math.floor(diff / MINUTE);
  437. if (quantity > 1) {
  438. return output(quantity, pluralize(quantity, minute, minutes));
  439. }
  440. return output(Math.floor(diff), pluralize(diff, second, seconds));
  441. }
  442. function timestamp(input) {
  443. if (!input) {
  444. return now();
  445. }
  446. const date = typeof input === "string" ? new Date(input) : input;
  447. return Math.floor(date.getTime() / 1e3);
  448. }
  449. // src/devices.ts
  450. function isDarkMode() {
  451. return !!window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
  452. }
  453. function isTouchDevice() {
  454. return !!window.matchMedia && window.matchMedia("(pointer: coarse)").matches;
  455. }
  456. function prefersReducedMotion() {
  457. return !!window.matchMedia && window.matchMedia("prefers-reduced-motion").matches;
  458. }
  459. // src/formatters.ts
  460. function formatBoolean(input) {
  461. return input ? "Yes" : "No";
  462. }
  463. function formatCPF(value) {
  464. const clearValue = cleanupNumericString(value);
  465. if (clearValue.length >= 10) {
  466. return `${clearValue.slice(0, 3)}.${clearValue.slice(3, 6)}.${clearValue.slice(
  467. 6,
  468. 9
  469. )}-${clearValue.slice(9, 11)}`;
  470. } else if (clearValue.length >= 7) {
  471. return `${clearValue.slice(0, 3)}.${clearValue.slice(3, 6)}.${clearValue.slice(6, 9)}`;
  472. } else if (clearValue.length >= 4) {
  473. return `${clearValue.slice(0, 3)}.${clearValue.slice(3, 6)}`;
  474. }
  475. return clearValue;
  476. }
  477. function formatDateLocale(input, options = {}) {
  478. const { locale = "en-GB", showTime = false } = options;
  479. const formatOptions = {
  480. year: "2-digit",
  481. month: "2-digit",
  482. day: "2-digit"
  483. };
  484. if (showTime) {
  485. formatOptions.hour = "2-digit";
  486. formatOptions.minute = "2-digit";
  487. }
  488. return new Date(input).toLocaleDateString(locale, formatOptions);
  489. }
  490. function formatMoney(input, options = {}) {
  491. const { decimalChar = ".", showCents = false, symbol = "$", thousandsChar = "," } = options;
  492. const isNegative = input < 0;
  493. const value = Math.abs(input);
  494. const [amount, cents] = value.toFixed(2).split(".");
  495. const padStart = amount.length > 3 ? amount.length % 3 : 0;
  496. const initial = amount.slice(0, padStart);
  497. const remain = amount.slice(padStart).replace(/(\d{3})(?=\d)/g, `$1${thousandsChar}`);
  498. let formatted = `${remain}`;
  499. if (initial) {
  500. formatted = `${initial}${thousandsChar}${remain}`;
  501. }
  502. if (cents !== "00" || showCents) {
  503. formatted += `${decimalChar}${cents}`;
  504. }
  505. return `${isNegative ? "-" : ""}${symbol}${formatted}`;
  506. }
  507. function formatPhoneBR(input) {
  508. const phone = input.replace(/\D/g, "");
  509. if (phone.length === 8) {
  510. return phone.replace(/^(\d{4})(\d{4}).*/, "$1-$2");
  511. }
  512. if (phone.length === 9) {
  513. return phone.replace(/^(\d{5})(\d{4}).*/, "$1-$2");
  514. }
  515. if (phone.length === 10 || phone.length === 11) {
  516. return phone.replace(/^(\d{2})(\d{4,5})(\d{4}).*/, "($1) $2-$3");
  517. }
  518. return phone;
  519. }
  520. function formatPhoneUS(input) {
  521. const phone = input.replace(/\D/g, "");
  522. if (phone.length === 10) {
  523. return phone.replace(/^(\d{3})(\d{3})(\d{4}).*/, "($1) $2-$3");
  524. }
  525. if (phone.length === 11 && phone.startsWith("1")) {
  526. return phone.replace(/^1(\d{3})(\d{3})(\d{4}).*/, "+1 ($1) $2-$3");
  527. }
  528. return phone;
  529. }
  530. function formatPostalCodeBR(value) {
  531. const clearValue = cleanupNumericString(value);
  532. if (clearValue.length >= 6) {
  533. return `${clearValue.slice(0, 5)}-${clearValue.slice(5, 8)}`;
  534. }
  535. return clearValue;
  536. }
  537. // src/functions.ts
  538. function demethodize(fn) {
  539. return (parameter, ...rest) => fn.apply(parameter, rest);
  540. }
  541. async function measureExecutionTime(callback) {
  542. const start = performance.now();
  543. const result = await callback();
  544. const end = performance.now();
  545. const total = end - start;
  546. console.log(`Completed in ${Math.ceil(total)} milliseconds`);
  547. return result;
  548. }
  549. function noop() {
  550. return void 0;
  551. }
  552. function once(fn) {
  553. let done = false;
  554. let result;
  555. return function Fn(...arguments_) {
  556. if (!done) {
  557. done = true;
  558. result = fn(...arguments_);
  559. }
  560. return result;
  561. };
  562. }
  563. function pipe(...fns) {
  564. return (input) => fns.reduce((previousValue, fn) => fn(previousValue), input);
  565. }
  566. // src/misc.ts
  567. import is3 from "is-lite";
  568. // src/numbers.ts
  569. function ceil(input, digits = 2) {
  570. const factor = 10 ** digits;
  571. return Math.ceil(input * factor) / factor;
  572. }
  573. function clamp(value, min = 0, max = 100) {
  574. return Math.min(Math.max(value, min), max);
  575. }
  576. function floor(input, digits = 2) {
  577. const factor = 10 ** digits;
  578. return Math.floor(input * factor) / factor;
  579. }
  580. function pad(input, length = 2) {
  581. return `${input}`.padStart(length, "0");
  582. }
  583. function randomNumber(min = 0, max = 10) {
  584. if (min >= max) {
  585. return max;
  586. }
  587. return Math.floor(Math.random() * (max - min + 1) + min);
  588. }
  589. function round(input, digits = 2) {
  590. const factor = 10 ** digits;
  591. return Math.round(input * factor) / factor;
  592. }
  593. // src/misc.ts
  594. function conditional(cases, defaultCase) {
  595. for (const [expression, callback] of cases) {
  596. if (expression) {
  597. return callback();
  598. }
  599. }
  600. return defaultCase?.();
  601. }
  602. async function copyToClipboard(input) {
  603. try {
  604. await navigator.clipboard.writeText(input);
  605. } catch {
  606. return false;
  607. }
  608. return true;
  609. }
  610. function getDataType(input, toLowerCase = false) {
  611. const dataTypeName = Object.prototype.toString.call(input).slice(8, -1);
  612. let output = dataTypeName;
  613. if (/HTML\w+Element/.test(dataTypeName)) {
  614. output = "HTMLElement";
  615. }
  616. return toLowerCase ? output.toLowerCase() : output;
  617. }
  618. function invariant(condition, message) {
  619. if (condition) {
  620. return;
  621. }
  622. const value = is3.function(message) ? message() : message;
  623. throw new Error(value);
  624. }
  625. function isJSON(input) {
  626. try {
  627. JSON.parse(input);
  628. } catch {
  629. return false;
  630. }
  631. return true;
  632. }
  633. function isRequired(input = "parameter", Constructable = TypeError) {
  634. throw new Constructable(`"${input}" is required`);
  635. }
  636. function logger(type, title, data, options = {}) {
  637. const { collapsed = true, hideTimestamp = false, skip = false, typeColor = "gray" } = options;
  638. const groupMethod = collapsed ? console.groupCollapsed : console.group;
  639. const date = /* @__PURE__ */ new Date();
  640. const parts = [`%c ${type}`];
  641. const styles = [`color: ${typeColor}; font-weight: lighter;`, "color: inherit;"];
  642. if (!hideTimestamp) {
  643. styles.push("color: gray; font-weight: lighter;");
  644. }
  645. const time = `${pad(date.getHours(), 2)}:${pad(date.getMinutes(), 2)}:${pad(
  646. date.getSeconds(),
  647. 2
  648. )}`;
  649. parts.push(`%c${title}`);
  650. if (!hideTimestamp) {
  651. parts.push(`%c@ ${time}`);
  652. }
  653. if (!skip) {
  654. groupMethod(parts.join(" "), ...styles);
  655. console.log(data);
  656. console.groupEnd();
  657. }
  658. }
  659. function nullify(value) {
  660. return value ?? null;
  661. }
  662. function popupCenter(url, title, width, height) {
  663. const { screen, screenLeft, screenTop } = window;
  664. let screenWidth = window.innerWidth;
  665. let screenHeight = window.innerHeight;
  666. if (!screenWidth) {
  667. screenWidth = document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
  668. }
  669. if (!screenHeight) {
  670. screenHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
  671. }
  672. const left = screenWidth / 2 - width / 2 + screenLeft;
  673. const top = screenHeight / 2 - height / 2 + screenTop;
  674. const popup = window.open(
  675. url,
  676. title,
  677. `menubar=no,location=no,resizable=no,scrollbars=yees,status=no,width=${width},height=${height},top=${top}, left=${left}`
  678. );
  679. if (popup) {
  680. popup.focus();
  681. }
  682. return popup;
  683. }
  684. function px(value) {
  685. return is3.number(value) || is3.numericString(value) ? `${value}px` : value;
  686. }
  687. function unique(length = 8, options = {}) {
  688. const {
  689. includeLowercase = true,
  690. includeNumbers = true,
  691. includeSymbols = false,
  692. includeUppercase = true
  693. } = options;
  694. const lowercase = "abcdefghijklmnopqrstuvwxyz";
  695. const uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  696. const numbers = "0123456789";
  697. const symbols = "!?@#$%^&*+_-=:.~";
  698. let characters = "";
  699. if (includeLowercase) {
  700. characters += lowercase;
  701. }
  702. if (includeUppercase) {
  703. characters += uppercase;
  704. }
  705. if (includeNumbers) {
  706. characters += numbers;
  707. }
  708. if (includeSymbols) {
  709. characters += symbols;
  710. }
  711. let result = "";
  712. for (let index = length; index > 0; --index) {
  713. result += characters[Math.round(Math.random() * (characters.length - 1))];
  714. }
  715. return result;
  716. }
  717. function uuid() {
  718. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
  719. const r = Math.random() * 16 | 0;
  720. const v = c === "x" ? r : r & 3 | 8;
  721. return v.toString(16);
  722. });
  723. }
  724. // src/objects.ts
  725. import is4 from "is-lite";
  726. function cleanUpObject(input) {
  727. const output = {};
  728. for (const key in input) {
  729. if (input[key] !== void 0) {
  730. output[key] = input[key];
  731. }
  732. }
  733. return output;
  734. }
  735. function getNestedProperty(input, path) {
  736. if (!is4.plainObject(input) && !is4.array(input) || !path) {
  737. return input;
  738. }
  739. const segments = path.split(".");
  740. const { length } = segments;
  741. let output = input;
  742. for (let index = 0; index < length; index++) {
  743. const currentSegment = segments[index];
  744. const remainingSegments = segments.slice(index + 1);
  745. if (currentSegment === "+" && is4.array(output) && remainingSegments.length === 1) {
  746. return output.map((d) => d[remainingSegments.join(".")]);
  747. }
  748. try {
  749. output = output[currentSegment];
  750. } catch {
  751. }
  752. }
  753. return output;
  754. }
  755. function invertKeys(input) {
  756. if (!is4.plainObject(input)) {
  757. throw new TypeError("Expected an object");
  758. }
  759. const result = {};
  760. for (const [key, value] of Object.entries(input)) {
  761. result[value] = key;
  762. }
  763. return result;
  764. }
  765. function keyMirror(input) {
  766. if (!is4.plainObject(input)) {
  767. throw new TypeError("Expected an object");
  768. }
  769. const output = {};
  770. for (const key in input) {
  771. if (!Object.prototype.hasOwnProperty.call(output, key)) {
  772. output[key] = key;
  773. }
  774. }
  775. return output;
  776. }
  777. function mergeProps(defaultProps, props) {
  778. const cleanProps = cleanUpObject(props);
  779. return { ...defaultProps, ...cleanProps };
  780. }
  781. function objectEntries(input) {
  782. return Object.entries(input);
  783. }
  784. function objectKeys(input) {
  785. return Object.keys(input);
  786. }
  787. function objectToArray(input, includeOnly) {
  788. if (!is4.plainObject(input)) {
  789. throw new TypeError("Expected an object");
  790. }
  791. return Object.entries(input).filter(([, value]) => includeOnly ? typeof value === `${includeOnly}` : true).map(([key, value]) => ({ [key]: value }));
  792. }
  793. function omit(input, ...filter) {
  794. if (!is4.plainObject(input)) {
  795. throw new TypeError("Expected an object");
  796. }
  797. const output = {};
  798. for (const key in input) {
  799. if ({}.hasOwnProperty.call(input, key)) {
  800. if (!filter.includes(key)) {
  801. output[key] = input[key];
  802. }
  803. }
  804. }
  805. return output;
  806. }
  807. function pick(input, ...filter) {
  808. if (!is4.plainObject(input)) {
  809. throw new TypeError("Expected an object");
  810. }
  811. if (!filter.length) {
  812. return input;
  813. }
  814. const output = {};
  815. for (const key in input) {
  816. if ({}.hasOwnProperty.call(input, key)) {
  817. if (filter.includes(key)) {
  818. output[key] = input[key];
  819. }
  820. }
  821. }
  822. return output;
  823. }
  824. function queryStringFormat(input, options = {}) {
  825. const { addPrefix = false, encoder = encodeURIComponent, encodeValuesOnly = true } = options;
  826. if (!is4.plainObject(input)) {
  827. throw new TypeError("input type isn't supported");
  828. }
  829. const isValidInput = Object.values(input).every((item) => {
  830. if (is4.array(item)) {
  831. return item.every((d) => is4.string(d) || is4.number(d));
  832. }
  833. return is4.string(item);
  834. });
  835. if (!isValidInput) {
  836. throw new TypeError("input format isn't supported");
  837. }
  838. const output = Object.entries(input).map(([key, value]) => {
  839. const nextKey = encodeValuesOnly ? key : encoder(key);
  840. const nextValue = is4.array(value) ? value.map(encoder).join(",") : encoder(`${value}`);
  841. return `${nextKey}=${nextValue}`;
  842. }).join("&");
  843. return `${addPrefix ? "?" : ""}${output}`;
  844. }
  845. function queryStringParse(input) {
  846. let search = input;
  847. if (input.slice(0, 1) === "?") {
  848. search = input.slice(1);
  849. }
  850. return search.split("&").reduce((acc, d) => {
  851. const [key, value] = d.split("=");
  852. acc[decodeURIComponent(key)] = decodeURIComponent(value);
  853. return acc;
  854. }, {});
  855. }
  856. function sortObjectKeys(input) {
  857. return objectKeys(input).sort().reduce((acc, key) => {
  858. acc[key] = input[key];
  859. return acc;
  860. }, {});
  861. }
  862. // src/statistics.ts
  863. import is5 from "is-lite";
  864. function mean(input, precision) {
  865. const output = input.reduce((sum, value) => sum + value, 0) / input.length;
  866. if (is5.number(precision)) {
  867. return round(output, precision);
  868. }
  869. return output;
  870. }
  871. function median(input) {
  872. const sorted = [...input].sort((a, b) => a - b);
  873. const middle = Math.floor(sorted.length / 2);
  874. if (sorted.length % 2 === 0) {
  875. return (sorted[middle - 1] + sorted[middle]) / 2;
  876. }
  877. return sorted[middle];
  878. }
  879. function mode(input) {
  880. const count = /* @__PURE__ */ new Map();
  881. for (const value of input) {
  882. const current = count.get(value) ?? 0;
  883. count.set(value, current + 1);
  884. }
  885. const sorted = [...count.entries()].sort((a, b) => b[1] - a[1]);
  886. return sorted[0][0];
  887. }
  888. // src/validators.ts
  889. function isValidCPF(value) {
  890. if (!value) {
  891. return false;
  892. }
  893. const newValue = value.replace(/[.-]/g, "");
  894. let sum = 0;
  895. let rest;
  896. if (/^(\d)\1+$/.test(newValue)) {
  897. return false;
  898. }
  899. for (let index = 1; index <= 9; index++) {
  900. sum += parseInt(newValue.substring(index - 1, index), 10) * (11 - index);
  901. }
  902. rest = sum * 10 % 11;
  903. if (rest === 10 || rest === 11) {
  904. rest = 0;
  905. }
  906. if (rest !== parseInt(newValue.substring(9, 10), 10)) {
  907. return false;
  908. }
  909. sum = 0;
  910. for (let index = 1; index <= 10; index++) {
  911. sum += parseInt(newValue.substring(index - 1, index), 10) * (12 - index);
  912. }
  913. rest = sum * 10 % 11;
  914. if (rest === 10 || rest === 11) {
  915. rest = 0;
  916. }
  917. return rest === parseInt(newValue.substring(10, 11), 10);
  918. }
  919. function isValidEmail(value) {
  920. return /^[\w%+.-]+@[\d.a-z-]+\.[a-z]{2,}$/i.test(value);
  921. }
  922. function validatePassword(password, options) {
  923. const {
  924. maxLength = 64,
  925. maxLengthMessage = "Password must be a maximum of 64 characters",
  926. minLength = 6,
  927. minLengthMessage = "Password must be at least 6 characters long",
  928. regex = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!#$%&*?@^]).*$/,
  929. requiredCharactersMessage = "Password must have at least 1 number, 1 lowercase, 1 uppercase and 1 special character"
  930. } = options || {};
  931. if (password.length < minLength) {
  932. throw new Error(minLengthMessage);
  933. }
  934. if (password.length > maxLength) {
  935. throw new Error(maxLengthMessage);
  936. }
  937. if (!regex.test(password)) {
  938. throw new Error(requiredCharactersMessage);
  939. }
  940. return true;
  941. }
  942. // src/types.ts
  943. var types_exports = {};
  944. export {
  945. ASYNC_STATUS,
  946. DAY,
  947. HOUR,
  948. MINUTE,
  949. MONTH,
  950. types_exports as Types,
  951. WEEK,
  952. YEAR,
  953. capitalize,
  954. ceil,
  955. clamp,
  956. cleanUpObject,
  957. cleanupHTML,
  958. cleanupNumericString,
  959. cleanupURI,
  960. conditional,
  961. copyToClipboard,
  962. cors,
  963. createArray,
  964. demethodize,
  965. floor,
  966. formatBoolean,
  967. formatCPF,
  968. formatDateLocale,
  969. formatMoney,
  970. formatPhoneBR,
  971. formatPhoneUS,
  972. formatPostalCodeBR,
  973. getDataType,
  974. getInitials,
  975. getNestedProperty,
  976. getRandomItem,
  977. invariant,
  978. invertKeys,
  979. isDarkMode,
  980. isIsoDate,
  981. isJSON,
  982. isRequired,
  983. isTouchDevice,
  984. isValidCPF,
  985. isValidDate,
  986. isValidEmail,
  987. isoDate,
  988. keyMirror,
  989. logger,
  990. mean,
  991. measureExecutionTime,
  992. median,
  993. mergeProps,
  994. mode,
  995. noop,
  996. now,
  997. nullify,
  998. objectEntries,
  999. objectKeys,
  1000. objectToArray,
  1001. omit,
  1002. once,
  1003. pad,
  1004. pick,
  1005. pipe,
  1006. pluralize,
  1007. poll,
  1008. popupCenter,
  1009. prefersReducedMotion,
  1010. px,
  1011. queryStringFormat,
  1012. queryStringParse,
  1013. quickSort,
  1014. randomNumber,
  1015. removeAccents,
  1016. removeDuplicates,
  1017. removeEmojis,
  1018. removeEmptyTags,
  1019. removeNonPrintableCharacters,
  1020. removeTags,
  1021. removeWhitespace,
  1022. request,
  1023. round,
  1024. shuffle,
  1025. sleep,
  1026. slugify,
  1027. sortByLocaleCompare,
  1028. sortByPrimitive,
  1029. sortComparator,
  1030. sortObjectKeys,
  1031. splitIntoChunks,
  1032. timeSince,
  1033. timestamp,
  1034. unique,
  1035. uuid,
  1036. validatePassword
  1037. };
  1038. //# sourceMappingURL=index.mjs.map