index.d.mts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. import { HttpMethods, PlainObject, StringOrNumber, RemoveType, NarrowPlainObject } from '@gilbarbara/types';
  2. interface CorsOptions {
  3. /** @default true */
  4. allowCredentials?: boolean;
  5. /** @default [] */
  6. allowedHeaders?: string[];
  7. /** @default ['GET'] */
  8. methods?: HttpMethods[];
  9. /** @default * */
  10. origin?: string;
  11. responseHeaders?: PlainObject<string>;
  12. /** @default 200 */
  13. statusCode?: number;
  14. }
  15. interface FormatDateLocaleOptions {
  16. locale?: string;
  17. showTime?: boolean;
  18. }
  19. interface FormatMoneyOptions {
  20. decimalChar?: ',' | '.';
  21. showCents?: boolean;
  22. symbol?: string;
  23. thousandsChar?: ',' | '.';
  24. }
  25. type InvertKeyValue<T extends Record<PropertyKey, PropertyKey>> = {
  26. [K in T[keyof T]]: {
  27. [P in keyof T]: T[P] extends K ? P : never;
  28. }[keyof T];
  29. };
  30. interface LoggerOptions {
  31. collapsed?: boolean;
  32. hideTimestamp?: boolean;
  33. skip?: boolean;
  34. typeColor?: string;
  35. }
  36. interface PollOptions {
  37. delay?: number;
  38. maxRetries?: number;
  39. }
  40. interface QueryStringFormatOptions {
  41. addPrefix?: boolean;
  42. encodeValuesOnly?: boolean;
  43. encoder?: (uri: string) => string;
  44. }
  45. interface RequestOptions {
  46. body?: any;
  47. headers?: PlainObject<string>;
  48. method?: HttpMethods;
  49. }
  50. interface RequestError extends Error {
  51. response: any;
  52. status: number;
  53. }
  54. interface SortFunction {
  55. <T extends PlainObject = PlainObject>(left: PlainObject<T>, right: PlainObject<T>): number;
  56. <T = string>(left: T, right: T): number;
  57. }
  58. interface TimeSinceOptions {
  59. /**
  60. * @default "day"
  61. */
  62. day?: string;
  63. /**
  64. * @default "days"
  65. */
  66. days?: string;
  67. /**
  68. * @default "hour"
  69. */
  70. hour?: string;
  71. /**
  72. * @default "hours"
  73. */
  74. hours?: string;
  75. /**
  76. * @default "minute"
  77. */
  78. minute?: string;
  79. /**
  80. * @default "minutes"
  81. */
  82. minutes?: string;
  83. /**
  84. * @default "month"
  85. */
  86. month?: string;
  87. /**
  88. * @default "months"
  89. */
  90. months?: string;
  91. prefix?: string;
  92. /**
  93. * @default "second"
  94. */
  95. second?: string;
  96. /**
  97. * @default "seconds"
  98. */
  99. seconds?: string;
  100. /**
  101. * @default false
  102. */
  103. skipWeeks?: boolean;
  104. /**
  105. * @default "ago"
  106. */
  107. suffix?: string;
  108. /**
  109. * @default "week"
  110. */
  111. week?: string;
  112. /**
  113. * @default "weeks"
  114. */
  115. weeks?: string;
  116. /**
  117. * @default "year"
  118. */
  119. year?: string;
  120. /**
  121. * @default "years"
  122. */
  123. years?: string;
  124. }
  125. interface UniqueOptions {
  126. includeLowercase?: boolean;
  127. includeNumbers?: boolean;
  128. includeSymbols?: boolean;
  129. includeUppercase?: boolean;
  130. }
  131. interface ValidatePasswordOptions {
  132. maxLength?: number;
  133. maxLengthMessage?: string;
  134. minLength?: number;
  135. minLengthMessage?: string;
  136. regex?: RegExp;
  137. requiredCharactersMessage?: string;
  138. }
  139. type types_CorsOptions = CorsOptions;
  140. type types_FormatDateLocaleOptions = FormatDateLocaleOptions;
  141. type types_FormatMoneyOptions = FormatMoneyOptions;
  142. type types_InvertKeyValue<T extends Record<PropertyKey, PropertyKey>> = InvertKeyValue<T>;
  143. type types_LoggerOptions = LoggerOptions;
  144. type types_PollOptions = PollOptions;
  145. type types_QueryStringFormatOptions = QueryStringFormatOptions;
  146. type types_RequestError = RequestError;
  147. type types_RequestOptions = RequestOptions;
  148. type types_SortFunction = SortFunction;
  149. type types_TimeSinceOptions = TimeSinceOptions;
  150. type types_UniqueOptions = UniqueOptions;
  151. type types_ValidatePasswordOptions = ValidatePasswordOptions;
  152. declare namespace types {
  153. export type { types_CorsOptions as CorsOptions, types_FormatDateLocaleOptions as FormatDateLocaleOptions, types_FormatMoneyOptions as FormatMoneyOptions, types_InvertKeyValue as InvertKeyValue, types_LoggerOptions as LoggerOptions, types_PollOptions as PollOptions, types_QueryStringFormatOptions as QueryStringFormatOptions, types_RequestError as RequestError, types_RequestOptions as RequestOptions, types_SortFunction as SortFunction, types_TimeSinceOptions as TimeSinceOptions, types_UniqueOptions as UniqueOptions, types_ValidatePasswordOptions as ValidatePasswordOptions };
  154. }
  155. /**
  156. * Create a sequential array of numbers
  157. */
  158. declare function createArray(size: number, start?: number): number[];
  159. /**
  160. * Get a random item from an array
  161. */
  162. declare function getRandomItem<T>(input: T[]): T;
  163. /**
  164. * Sort an array of numbers using a quick sort algorithm
  165. */
  166. declare function quickSort<T extends string | number>(input: T[], comparator?: typeof sortComparator): T[];
  167. /**
  168. * Remove duplicates from the array
  169. */
  170. declare function removeDuplicates<T = unknown>(input: T[]): T[];
  171. /**
  172. * Shuffle an array using the Fisher-Yates algorithm
  173. */
  174. declare function shuffle<T = unknown>(input: T[]): T[];
  175. /**
  176. * Sort an array with localeCompare
  177. */
  178. declare function sortByLocaleCompare(key?: string, options?: Intl.CollatorOptions & {
  179. descending?: boolean;
  180. }): SortFunction;
  181. /**
  182. * Sort an array by primitive values
  183. */
  184. declare function sortByPrimitive<T extends number | boolean>(key?: string, descending?: boolean): SortFunction;
  185. /**
  186. * Basic sort comparator
  187. */
  188. declare function sortComparator(left: string | number, right: string | number): 1 | 0 | -1;
  189. declare function splitIntoChunks<T>(input: T[], chunkSize?: number): T[][];
  190. declare const ASYNC_STATUS: {
  191. readonly IDLE: "IDLE";
  192. readonly PENDING: "PENDING";
  193. readonly SUCCESS: "SUCCESS";
  194. readonly ERROR: "ERROR";
  195. };
  196. /**
  197. * Format a CORS response
  198. */
  199. declare function cors(data: any, statusCodeOrOptions?: number | CorsOptions): {
  200. body: string;
  201. headers: {
  202. 'Access-Control-Expose-Headers'?: string | undefined;
  203. 'Access-Control-Allow-Origin': string;
  204. 'Access-Control-Allow-Credentials': boolean;
  205. 'Access-Control-Allow-Methods': string;
  206. 'Access-Control-Allow-Headers': string;
  207. };
  208. statusCode: number;
  209. };
  210. /**
  211. *
  212. * @param condition
  213. * @param options
  214. */
  215. declare function poll(condition: () => boolean, options?: PollOptions): Promise<void>;
  216. /**
  217. * Make async requests
  218. */
  219. declare function request<D = any>(url: string, options?: RequestOptions): Promise<D>;
  220. /**
  221. * Block execution
  222. */
  223. declare function sleep(seconds?: number): Promise<unknown>;
  224. declare const MINUTE = 60;
  225. declare const HOUR: number;
  226. declare const DAY: number;
  227. declare const WEEK: number;
  228. declare const MONTH: number;
  229. declare const YEAR: number;
  230. declare function isIsoDate(input: string): boolean;
  231. /**
  232. * Check if the input is a valid date.
  233. */
  234. declare function isoDate(input?: string | number): string;
  235. /**
  236. * Check if the input is a valid date.
  237. */
  238. declare function isValidDate(input: string | number | Date): boolean;
  239. /**
  240. * Returns the unixtime (in seconds).
  241. */
  242. declare function now(): number;
  243. /**
  244. * Returns how much time has passed since the input.
  245. */
  246. declare function timeSince(input: Date | string | number, options?: TimeSinceOptions): string;
  247. /**
  248. * Get the timestamp (in seconds) for a date.
  249. */
  250. declare function timestamp(input?: Date | string): number;
  251. /**
  252. * Detect if the device is in dark mode
  253. */
  254. declare function isDarkMode(): boolean;
  255. /**
  256. * Detect if the device supports touch events
  257. */
  258. declare function isTouchDevice(): boolean;
  259. /**
  260. * Detect if the user prefers reduced motion
  261. */
  262. declare function prefersReducedMotion(): boolean;
  263. /**
  264. * Format boolean into a Yes/No string
  265. */
  266. declare function formatBoolean(input: boolean): "Yes" | "No";
  267. /**
  268. * Format string into a CPF
  269. */
  270. declare function formatCPF(value: string): string;
  271. /**
  272. * Format date ISO string using locale
  273. */
  274. declare function formatDateLocale(input: string, options?: FormatDateLocaleOptions): string;
  275. /**
  276. * Format number into money string
  277. */
  278. declare function formatMoney(input: number, options?: FormatMoneyOptions): string;
  279. /**
  280. * Format string into a brazilian phone
  281. */
  282. declare function formatPhoneBR(input: string): string;
  283. /**
  284. * Format string into a US phone
  285. */
  286. declare function formatPhoneUS(input: string): string;
  287. /**
  288. * Format string into a zip code
  289. */
  290. declare function formatPostalCodeBR(value: string): string;
  291. /**
  292. * Decouple methods from objects
  293. */
  294. declare function demethodize(fn: Function): (parameter: any, ...rest: any[]) => any;
  295. /**
  296. * Measure function execution time
  297. */
  298. declare function measureExecutionTime<T = any>(callback: Function): Promise<T>;
  299. /**
  300. * A function that does nothing.
  301. */
  302. declare function noop(): undefined;
  303. /**
  304. * Creates a function that will only be called once.
  305. * Repeat calls return the value of the first invocation.
  306. */
  307. declare function once<T extends (...arguments_: Array<any>) => any>(fn: T): T;
  308. /**
  309. * Combine multiple functions into one.
  310. * The output of each function is passed as the input to the next.
  311. */
  312. declare function pipe<T>(...fns: Array<(argument: T) => T>): (input: T) => T;
  313. type Case<T = void> = [boolean, () => T];
  314. declare function conditional<TReturn = void>(cases: Array<Case<TReturn>>, defaultCase?: () => TReturn): TReturn | undefined;
  315. /**
  316. * Copy a string to the clipboard
  317. */
  318. declare function copyToClipboard(input: string): Promise<boolean>;
  319. /**
  320. * Get the data type of variable.
  321. */
  322. declare function getDataType(input: unknown, toLowerCase?: boolean): string;
  323. declare function invariant(condition: any, message: string | (() => string)): asserts condition;
  324. /**
  325. * Check if a string is a valid JSON
  326. */
  327. declare function isJSON(input: string): boolean;
  328. /**
  329. * Throw an error if the parameter isn't provided
  330. */
  331. declare function isRequired(input?: string, Constructable?: TypeErrorConstructor): void;
  332. /**
  333. * Log grouped messages to the console
  334. */
  335. declare function logger(type: string, title: string, data: any, options?: LoggerOptions): void;
  336. /**
  337. * Returns the value or null
  338. */
  339. declare function nullify<T>(value: T): NonNullable<T> | null;
  340. declare function popupCenter(url: string, title: string, width: number, height: number): Window | null;
  341. declare function px(value: undefined): undefined;
  342. declare function px(value: StringOrNumber): string;
  343. declare function px(value: StringOrNumber | undefined): string | undefined;
  344. /**
  345. * Return a unique string
  346. */
  347. declare function unique(length?: number, options?: UniqueOptions): string;
  348. /**
  349. * Returns an UUID v4 string.
  350. */
  351. declare function uuid(): string;
  352. /**
  353. * Ceil decimal numbers
  354. */
  355. declare function ceil(input: number, digits?: number): number;
  356. /**
  357. * Limit number between range
  358. */
  359. declare function clamp(value: number, min?: number, max?: number): number;
  360. /**
  361. * Floor decimal numbers
  362. */
  363. declare function floor(input: number, digits?: number): number;
  364. /**
  365. * Pad a number with zeros
  366. */
  367. declare function pad(input: number, length?: number): string;
  368. /**
  369. * Returns a random number
  370. */
  371. declare function randomNumber(min?: number, max?: number): number;
  372. /**
  373. * Round decimal numbers
  374. */
  375. declare function round(input: number, digits?: number): number;
  376. /**
  377. * Remove properties with undefined value from an object
  378. */
  379. declare function cleanUpObject<T extends PlainObject>(input: T): RemoveType<T, undefined>;
  380. /**
  381. * Get a nested property inside an object or array
  382. */
  383. declare function getNestedProperty<T extends PlainObject<any>>(input: T, path: string): any;
  384. /**
  385. * Invert object key and value
  386. */
  387. declare function invertKeys<const T extends PlainObject<PropertyKey>>(input: T): InvertKeyValue<T>;
  388. /**
  389. * Set the key as the value
  390. */
  391. declare function keyMirror<T extends PlainObject>(input: T): {
  392. [K in keyof T]: K;
  393. };
  394. /**
  395. * Merges the defaultProps with literal values with the incoming props, removing undefined values from it that would override the defaultProps.
  396. * The result is a type-safe object with the defaultProps as required properties.
  397. */
  398. declare function mergeProps<TDefaultProps extends PlainObject<any>, TProps extends PlainObject<any>>(defaultProps: TDefaultProps, props: TProps): TProps & Required<Pick<TProps, keyof TDefaultProps & string>> extends infer T ? { [KeyType_1 in keyof T]: (TProps & Required<Pick<TProps, keyof TDefaultProps & string>>)[KeyType_1]; } : never;
  399. /**
  400. * Type-safe Object.entries()
  401. */
  402. declare function objectEntries<T extends PlainObject<any>>(input: T): { [K in keyof T]-?: [K, T[K]]; }[keyof T][];
  403. /**
  404. * Type-safe Object.keys()
  405. */
  406. declare function objectKeys<T extends PlainObject<any>>(input: T): (keyof T)[];
  407. /**
  408. * Convert an object to an array of objects
  409. */
  410. declare function objectToArray<T extends PlainObject>(input: T, includeOnly?: string): {
  411. [x: string]: unknown;
  412. }[];
  413. /**
  414. * Remove properties from an object
  415. */
  416. declare function omit<T extends Record<string, any>, K extends keyof T>(input: NarrowPlainObject<T>, ...filter: K[]): Omit<T, K>;
  417. /**
  418. * Select properties from an object
  419. */
  420. declare function pick<T extends Record<string, any>, K extends keyof T>(input: NarrowPlainObject<T>, ...filter: K[]): Pick<T, K>;
  421. /**
  422. * Stringify a shallow object into a query string
  423. */
  424. declare function queryStringFormat<T extends PlainObject>(input: T, options?: QueryStringFormatOptions): string;
  425. /**
  426. * Parse a query string
  427. */
  428. declare function queryStringParse(input: string): PlainObject<string>;
  429. /**
  430. * Sort object keys
  431. */
  432. declare function sortObjectKeys<T extends PlainObject>(input: T): T;
  433. /**
  434. * Returns the average of two or more numbers
  435. */
  436. declare function mean(input: number[], precision?: number): number;
  437. /**
  438. * Returns the median of two or more numbers
  439. */
  440. declare function median(input: number[]): number;
  441. /**
  442. * Returns the mode of two or more numbers
  443. */
  444. declare function mode(input: number[]): number;
  445. /**
  446. * Capitalize the first letter
  447. */
  448. declare function capitalize(input: string): string;
  449. /**
  450. * Cleanup HTML content
  451. */
  452. declare function cleanupHTML(input: string): string;
  453. /**
  454. * Cleanup a numeric string
  455. */
  456. declare function cleanupNumericString(value?: string): string;
  457. /**
  458. * Cleanup URI characters
  459. */
  460. declare function cleanupURI(input: string): string;
  461. /**
  462. * Get initials from name
  463. */
  464. declare function getInitials(input: string): string;
  465. /**
  466. * Pluralize strings.
  467. *
  468. * If the plural form just adds an `s` to the end, you don't need to pass it.
  469. */
  470. declare function pluralize(quantity: number, singular: string, plural?: string): string;
  471. /**
  472. * Remove accents
  473. */
  474. declare function removeAccents(input: string): string;
  475. /**
  476. * Remove emojis
  477. */
  478. declare function removeEmojis(input: string): string;
  479. /**
  480. * Remove empty HTML Tags (including whitespace)
  481. */
  482. declare function removeEmptyTags(input: string): string;
  483. /**
  484. * Remove non-printable ASCII characters
  485. */
  486. declare function removeNonPrintableCharacters(input: string): string;
  487. /**
  488. * Remove HTML tags
  489. */
  490. declare function removeTags(input: string): string;
  491. /**
  492. * Remove whitespace
  493. */
  494. declare function removeWhitespace(input: string): string;
  495. /**
  496. * Format string to slug
  497. */
  498. declare function slugify(input: string): string;
  499. /**
  500. * Check if CPF is valid
  501. */
  502. declare function isValidCPF(value: string): boolean;
  503. /**
  504. * Check if email is valid
  505. */
  506. declare function isValidEmail(value: string): boolean;
  507. /**
  508. * Validate password length and required characters
  509. * @throws
  510. */
  511. declare function validatePassword(password: string, options?: ValidatePasswordOptions): boolean;
  512. export { ASYNC_STATUS, DAY, HOUR, MINUTE, MONTH, types 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 };