topkat-utils 1.3.24 → 1.3.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +1 -1
  2. package/backend.ts +3 -4
  3. package/dist/backend.js +3 -4
  4. package/dist/backend.js.map +1 -1
  5. package/dist/src/array-utils.d.ts +1 -1
  6. package/dist/src/array-utils.js +2 -2
  7. package/dist/src/array-utils.js.map +1 -1
  8. package/dist/src/clean-stack-trace.js.map +1 -1
  9. package/dist/src/date-utils.d.ts +25 -20
  10. package/dist/src/date-utils.js +1 -0
  11. package/dist/src/date-utils.js.map +1 -1
  12. package/dist/src/env-utils.d.ts +1 -1
  13. package/dist/src/env-utils.js.map +1 -1
  14. package/dist/src/error-utils.d.ts +6 -6
  15. package/dist/src/error-utils.js.map +1 -1
  16. package/dist/src/isset.js.map +1 -1
  17. package/dist/src/logger-utils.d.ts +33 -30
  18. package/dist/src/logger-utils.js +10 -29
  19. package/dist/src/logger-utils.js.map +1 -1
  20. package/dist/src/loop-utils.d.ts +4 -4
  21. package/dist/src/loop-utils.js.map +1 -1
  22. package/dist/src/mongo-utils.js.map +1 -1
  23. package/dist/src/object-utils.d.ts +4 -4
  24. package/dist/src/object-utils.js +1 -1
  25. package/dist/src/object-utils.js.map +1 -1
  26. package/dist/src/regexp-utils.d.ts +1 -1
  27. package/dist/src/regexp-utils.js.map +1 -1
  28. package/dist/src/remove-circular-json-stringify.js.map +1 -1
  29. package/dist/src/string-utils.d.ts +4 -4
  30. package/dist/src/string-utils.js +1 -1
  31. package/dist/src/string-utils.js.map +1 -1
  32. package/dist/src/tests-utils.js.map +1 -1
  33. package/dist/src/timer-utils.d.ts +4 -4
  34. package/dist/src/timer-utils.js +1 -1
  35. package/dist/src/timer-utils.js.map +1 -1
  36. package/dist/src/transaction-utils.d.ts +3 -3
  37. package/dist/src/transaction-utils.js.map +1 -1
  38. package/dist/src/transaction-utils.spec.js +1 -1
  39. package/dist/src/transaction-utils.spec.js.map +1 -1
  40. package/dist/src/validation-utils.d.ts +3 -3
  41. package/dist/src/validation-utils.js +17 -16
  42. package/dist/src/validation-utils.js.map +1 -1
  43. package/dist/src/wtf-utils.d.ts +3 -3
  44. package/dist/src/wtf-utils.js +1 -1
  45. package/dist/src/wtf-utils.js.map +1 -1
  46. package/package.json +1 -1
  47. package/src/array-utils.ts +3 -3
  48. package/src/clean-stack-trace.ts +1 -1
  49. package/src/date-utils.ts +45 -41
  50. package/src/env-utils.ts +1 -1
  51. package/src/error-utils.ts +8 -8
  52. package/src/isset.ts +1 -1
  53. package/src/logger-utils.ts +40 -52
  54. package/src/loop-utils.ts +5 -5
  55. package/src/mongo-utils.ts +1 -1
  56. package/src/object-utils.ts +22 -22
  57. package/src/regexp-utils.ts +3 -3
  58. package/src/remove-circular-json-stringify.ts +2 -2
  59. package/src/string-utils.ts +3 -3
  60. package/src/tests-utils.ts +1 -1
  61. package/src/timer-utils.ts +4 -4
  62. package/src/transaction-utils.spec.ts +1 -1
  63. package/src/transaction-utils.ts +5 -5
  64. package/src/validation-utils.ts +28 -26
  65. package/src/wtf-utils.ts +6 -6
  66. package/tsconfig.json +1 -1
package/src/loop-utils.ts CHANGED
@@ -31,7 +31,7 @@ export function forI<T extends any[] | any>(
31
31
  /** Current iteration index (0-based) */
32
32
  number: number,
33
33
  /** Result from previous iteration */
34
- previousValue,
34
+ previousValue: any,
35
35
  /** Array of all previous results */
36
36
  arrayOfPreviousValues: any[]
37
37
  ) => T
@@ -58,7 +58,7 @@ export function forI<T extends any[] | any>(
58
58
  * ```
59
59
  * // Returns: [1, 1, 2, 3, 5, 8, 13, 21]
60
60
  */
61
- export async function forIasync<T extends any[] | any>(nbIterations: number, callback: (number) => T): Promise<T[]> {
61
+ export async function forIasync<T extends any[] | any>(nbIterations: number, callback: (number: number) => T): Promise<T[]> {
62
62
  const results: any[] = []
63
63
  for (let i = 0; i < nbIterations; i++) {
64
64
  results.push(await callback(i))
@@ -67,7 +67,7 @@ export async function forIasync<T extends any[] | any>(nbIterations: number, cal
67
67
  }
68
68
 
69
69
 
70
- export type RecursiveCallback = (item: any, addr: string, lastElementKey: string | number, parent: ObjectGeneric | any[]) => false | any
70
+ export type RecursiveCallback = (item: any, addr: string, lastElementKey: string | number, parent?: ObjectGeneric | any[]) => false | any
71
71
  export type RecursiveConfig = {
72
72
  disableCircularDependencyRemoval?: boolean
73
73
  isObjectTestFunction?: (item: any) => boolean
@@ -98,7 +98,7 @@ export async function recursiveGenericFunction(
98
98
  addr$ = '',
99
99
  /** Technical field */
100
100
  lastElementKey: string | number = '',
101
- parent?,
101
+ parent?: Record<string, any>,
102
102
  techFieldToAvoidCircularDependency: any[] = []
103
103
  ) {
104
104
  err500IfNotSet({ callback })
@@ -141,7 +141,7 @@ export async function recursiveGenericFunction(
141
141
  * NOTE: will remove circular references
142
142
  * /!\ check return values
143
143
  */
144
- export function recursiveGenericFunctionSync(item: ObjectGeneric | any[], callback: RecursiveCallback, config: RecursiveConfig = {}, addr$ = '', lastElementKey: string | number = '', parent?, techFieldToAvoidCircularDependency: any[] = []) {
144
+ export function recursiveGenericFunctionSync(item: ObjectGeneric | any[], callback: RecursiveCallback, config: RecursiveConfig = {}, addr$ = '', lastElementKey: string | number = '', parent?: Record<string, any>, techFieldToAvoidCircularDependency: any[] = []) {
145
145
  err500IfNotSet({ callback })
146
146
 
147
147
  if (!config.isObjectTestFunction) config.isObjectTestFunction = isObject
@@ -17,7 +17,7 @@ export function getId(obj: any): string | undefined {
17
17
  * @param {Object} filterB
18
18
  * @param {Boolean} assignToFilterA defualt false: if true, it will modify filterA, else it will return merged filters as a new object
19
19
  */
20
- export function mongoFilterMerger(filterA, filterB, assignToFilterA = false) {
20
+ export function mongoFilterMerger(filterA: any, filterB: any, assignToFilterA = false) {
21
21
  if (isset(filterA.$and) && isset(filterB.$and)) {
22
22
  filterA.$and.push(...filterB.$and)
23
23
  delete filterB.$and
@@ -29,7 +29,7 @@ export function simpleObjectMaskOrSelect<Obj extends ObjectGeneric>(
29
29
  keysToMask.forEach(keyNameToDelete => delete object[keyNameToDelete])
30
30
  return object
31
31
  } else {
32
- return allKeys.reduce((newObject, key) => {
32
+ return allKeys.reduce((newObject: Record<string, any>, key) => {
33
33
  if (!keysToMask.includes(key)) newObject[key] = object[key]
34
34
  return newObject
35
35
  }, {}) as Obj
@@ -93,7 +93,7 @@ export function findByAddressAll<ReturnAddresses extends boolean = false>(
93
93
  /** Enforce writing subItems. Eg: user.name.blah will ensure all are set until the writing of the last item
94
94
  * NOTE: doesn't work when parent is array
95
95
  */
96
- export function objForceWrite<MainObj extends Record<string, any>>(obj: MainObj, addr: string, item, options: { doNotWriteFinalValue?: boolean } = {}): MainObj {
96
+ export function objForceWrite<MainObj extends Record<string, any>>(obj: MainObj, addr: string, item: any, options: { doNotWriteFinalValue?: boolean } = {}): MainObj {
97
97
  const { doNotWriteFinalValue = false } = options
98
98
  const writeFinalValue = !doNotWriteFinalValue
99
99
 
@@ -129,13 +129,13 @@ export const objForceWritePath = forcePathInObject
129
129
  * if user.name.blah has a value it will not change it.
130
130
  * NOTE: doesn't work when parent is array
131
131
  */
132
- export function objForceWriteIfNotSet<MainObj extends Record<string, any>>(obj: MainObj, addr: string, item): MainObj {
132
+ export function objForceWriteIfNotSet<MainObj extends Record<string, any>>(obj: MainObj, addr: string, item: any): MainObj {
133
133
  if (!isset(findByAddress(obj, addr))) return objForceWrite(obj, addr, item)
134
134
  else return obj
135
135
  }
136
136
 
137
137
  /** Merge mixins into class. Use it in the constructor like: mergeMixins(this, {myMixin: true}) */
138
- export function mergeMixins(that, ...mixins) {
138
+ export function mergeMixins(that: any, ...mixins: any[]) {
139
139
  mixins.forEach(mixin => {
140
140
  for (const method in mixin) {
141
141
  that[method] = mixin[method]
@@ -187,7 +187,7 @@ export function deepClone<MainObj extends Record<string, any>>(obj: MainObj, cac
187
187
  * @param {Object} obj the object on which we want to filter the keys
188
188
  * @param {function} filterFunc function that returns true if the key match the wanted criteria
189
189
  */
190
- export function filterKeys<MainObj extends Record<string, any>>(obj: MainObj, filter): MainObj {
190
+ export function filterKeys<MainObj extends Record<string, any>>(obj: MainObj, filter: any): MainObj {
191
191
  const clone = cloneObject(obj)
192
192
  recursiveGenericFunctionSync(obj, (_, addr, lastElementKey) => {
193
193
  if (!filter(lastElementKey)) deleteByAddress(clone, addr.split('.'))
@@ -199,7 +199,7 @@ export function filterKeys<MainObj extends Record<string, any>>(obj: MainObj, fi
199
199
  * @param {Array} addrArr addressArray on which to delete the property
200
200
  */
201
201
  export function deleteByAddress(obj: object, addr: string | string[]) {
202
- let current = obj
202
+ let current = obj as Record<string, any>
203
203
  const addrArr = Array.isArray(addr) ? addr : addr.split('.')
204
204
  for (let i = 0; i < addrArr.length; i++) {
205
205
  const currentAddr = addrArr[i].replace(/(\[|\])/g, '')
@@ -227,9 +227,9 @@ export function readOnly<MainObj extends Record<string, any>>(o: MainObj): { rea
227
227
  }
228
228
 
229
229
  /** Fields of the object can be created BUT NOT reassignated */
230
- export function reassignForbidden(o) {
230
+ export function reassignForbidden(o: Record<string, any>) {
231
231
  return new Proxy(o, {
232
- defineProperty: function (that, key, value) {
232
+ defineProperty: function (that: Record<string, any>, key: string, value) {
233
233
  if (key in that) throw new DescriptiveError(`Cannot reassign the property ${key.toString()} of this object`, { code: 500 })
234
234
  else {
235
235
  that[key] = value
@@ -243,9 +243,9 @@ export function reassignForbidden(o) {
243
243
  }
244
244
 
245
245
  /** All fileds and subFields of the object will become readOnly */
246
- export function readOnlyRecursive(object) {
246
+ export function readOnlyRecursive(object: Record<string, any>) {
247
247
  recursiveGenericFunctionSync(object, (item, _, lastElementKey, parent) => {
248
- if (typeof item === 'object') parent[lastElementKey] = readOnly(item)
248
+ if (typeof item === 'object' && parent) (parent as any)[lastElementKey] = readOnly(item)
249
249
  })
250
250
  return object
251
251
  }
@@ -253,7 +253,7 @@ export function readOnlyRecursive(object) {
253
253
  /** @deprecated use readOnlyRecursive instead */
254
254
  export const readOnlyForAll = readOnlyRecursive
255
255
 
256
- export function objFilterUndefinedRecursive(obj) {
256
+ export function objFilterUndefinedRecursive(obj: Record<string, any>) {
257
257
  if (obj) {
258
258
  const flattenedObj = flattenObject(obj)
259
259
  Object.keys(flattenedObj).forEach(key => {
@@ -265,8 +265,8 @@ export function objFilterUndefinedRecursive(obj) {
265
265
  } else return obj
266
266
  }
267
267
 
268
- export function sortObjKeyAccordingToValue(unorderedObj, ascending = true) {
269
- const orderedObj = {}
268
+ export function sortObjKeyAccordingToValue(unorderedObj: Record<string, any>, ascending = true) {
269
+ const orderedObj = {} as Record<string, any>
270
270
  const sortingConst = ascending ? 1 : -1
271
271
  Object.keys(unorderedObj)
272
272
  .sort((keyA, keyB) => unorderedObj[keyA] < unorderedObj[keyB] ? sortingConst : -sortingConst)
@@ -285,7 +285,7 @@ export function sortObjKeyAccordingToValue(unorderedObj, ascending = true) {
285
285
  export function ensureObjectProp<MainObj extends Record<string, any>, Addr extends string>(
286
286
  obj: MainObj,
287
287
  addr: Addr,
288
- defaultValue,
288
+ defaultValue: any,
289
289
  callback: (o: any) => any
290
290
  ): MainObj[Addr] {
291
291
  err500IfNotSet({ obj, addr, defaultValue, callback })
@@ -309,7 +309,7 @@ export function mergeDeep<
309
309
  >(...objects: [O1, O2?, O3?, O4?, O5?, O6?]): O1 & O2 & O3 & O4 & O5 & O6 {
310
310
  return mergeDeepConfigurable(
311
311
  (previousVal, currentVal) => [...previousVal, ...currentVal].filter((elm, i, arr) => arr.indexOf(elm) === i),
312
- (previousVal, currentVal) => mergeDeep(previousVal, currentVal),
312
+ (previousVal: any, currentVal: any) => mergeDeep(previousVal, currentVal),
313
313
  undefined,
314
314
  ...objects
315
315
  )
@@ -329,7 +329,7 @@ export function mergeDeepOverrideArrays<
329
329
  >(...objects: [O1, O2?, O3?, O4?, O5?, O6?]): O1 & O2 & O3 & O4 & O5 & O6 {
330
330
  return mergeDeepConfigurable(
331
331
  undefined,
332
- (previousVal, currentVal) => mergeDeepOverrideArrays(previousVal, currentVal),
332
+ (previousVal: any, currentVal: any) => mergeDeepOverrideArrays(previousVal, currentVal),
333
333
  undefined,
334
334
  ...objects
335
335
  )
@@ -351,11 +351,11 @@ export function mergeDeepConfigurable<
351
351
  O5 extends Record<string, any> = Record<string, any>,
352
352
  O6 extends Record<string, any> = Record<string, any>,
353
353
  >(
354
- replacerForArrays = (_, curr) => curr, replacerForObjects,
355
- replacerDefault = (_, curr) => curr,
354
+ replacerForArrays = (_: any, curr: any) => curr, replacerForObjects: any,
355
+ replacerDefault = (_: any, curr: any) => curr,
356
356
  ...objects: [O1, O2?, O3?, O4?, O5?, O6?]
357
357
  ): O1 & O2 & O3 & O4 & O5 & O6 {
358
- return objects.reduce((actuallyMerged, obj) => {
358
+ return objects.reduce((actuallyMerged: Record<string, any>, obj) => {
359
359
  if (obj && typeof obj === 'object') Object.keys(obj).forEach(key => {
360
360
  const previousVal = actuallyMerged[key]
361
361
  const currentVal = obj[key]
@@ -376,11 +376,11 @@ export function mergeDeepConfigurable<
376
376
  /** { a: {b:2}} => {'a.b':2} useful for translations
377
377
  * NOTE: will remove circular references
378
378
  */
379
- export function flattenObject(data, config: { withoutArraySyntax?: boolean, withArraySyntaxMinified?: boolean } = {}): Record<string, any> {
379
+ export function flattenObject(data: any, config: { withoutArraySyntax?: boolean, withArraySyntaxMinified?: boolean } = {}): Record<string, any> {
380
380
  const { withoutArraySyntax = false, withArraySyntaxMinified = false } = config
381
- const result = {}
381
+ const result = {} as Record<string, any>
382
382
  const seenObjects: any[] = [] // avoidCircular reference to infinite loop
383
- const recurse = (cur, prop) => {
383
+ const recurse = (cur: any, prop: string) => {
384
384
  if (Array.isArray(cur)) {
385
385
  const l = cur.length
386
386
  let i = 0
@@ -33,10 +33,10 @@ export function firstMatch(str: string, regExp: RegExp): string | undefined { re
33
33
  * Eg: [ [full, match1, m2], [f, m1, m2]... ]
34
34
  * NOTE: the G flag will be appended to regexp
35
35
  */
36
- export function allMatches(str: string, reg: RegExp): string[] {
36
+ export function allMatches(str: string, reg: RegExp) {
37
37
  let i = 0
38
- let matches
39
- const arr: string[] = []
38
+ let matches: RegExpExecArray | null
39
+ const arr: (RegExpExecArray | null)[] = []
40
40
  if (typeof str !== 'string') C.error('Not a string provided as first argument for allMatches()')
41
41
  else {
42
42
  reg = new RegExp(reg, 'g')
@@ -1,10 +1,10 @@
1
1
 
2
2
 
3
3
  /** Best way to stringify a value! Default indent: 2 */
4
- export function removeCircularJSONstringify(object, indent = 2) {
4
+ export function removeCircularJSONstringify(object: any, indent = 2) {
5
5
  const getCircularReplacer = () => {
6
6
  const seen = new WeakSet()
7
- return (_, value) => {
7
+ return (_: any, value: any) => {
8
8
  if (typeof value === 'object' && value !== null) {
9
9
  if (seen.has(value)) {
10
10
  return
@@ -76,7 +76,7 @@ export function getValuesBetweenSeparator(str: string, separator: string, remove
76
76
  * @param ignoreBetweenOpen default ['\'', '`', '"', '/'], when reaching an opening char, it will ignore all until it find the corresponding closing char
77
77
  * @param ignoreBetweenClose default ['\'', '`', '"', '/'] list of corresponding closing chars
78
78
  */
79
- export function getValuesBetweenStrings(str: string, openingOrSeparator, closing, ignoreBetweenOpen = ['\'', '`', '"', '/'], ignoreBetweenClose = ['\'', '`', '"', '/'], removeTrailingSpaces = true) {
79
+ export function getValuesBetweenStrings(str: string, openingOrSeparator: string, closing?: string, ignoreBetweenOpen = ['\'', '`', '"', '/'], ignoreBetweenClose = ['\'', '`', '"', '/'], removeTrailingSpaces = true) {
80
80
  err500IfEmptyOrNotSet({ openingOrSeparator, str })
81
81
 
82
82
  str = str.replace(/<</g, '§§"').replace(/>>/g, '"§§')
@@ -129,7 +129,7 @@ export function getValuesBetweenStrings(str: string, openingOrSeparator, closing
129
129
 
130
130
  pushActualValue()
131
131
 
132
- const replaceValz = arr => arr.map(v => v.replace(/§§"/g, '<<').replace(/"§§/g, '>>')).filter(v => v)
132
+ const replaceValz = (arr: string[]) => arr.map(v => v.replace(/§§"/g, '<<').replace(/"§§/g, '>>')).filter(v => v)
133
133
 
134
134
  return { inner: replaceValz(arrayValues), outer: replaceValz(betweenArray) }
135
135
  }
@@ -240,7 +240,7 @@ export function miniTemplater(content: string, varz: ObjectGeneric, options: Par
240
240
 
241
241
 
242
242
  /** Clean output for outside world. All undefined / null / NaN / Infinity values are changed to '-' */
243
- export function cln(val, replacerInCaseItIsUndefinNaN = '-') { return ['undefined', undefined, 'indéfini', 'NaN', NaN, Infinity, null].includes(val) ? replacerInCaseItIsUndefinNaN : val }
243
+ export function cln(val: any, replacerInCaseItIsUndefinNaN = '-') { return ['undefined', undefined, 'indéfini', 'NaN', NaN, Infinity, null].includes(val) ? replacerInCaseItIsUndefinNaN : val }
244
244
 
245
245
  export function nbOccurenceInString(baseString: string, searchedString: string, allowOverlapping: boolean = false) {
246
246
 
@@ -16,7 +16,7 @@ export const restTestMini = {
16
16
  restTestMini.lastErrors = []
17
17
  restTestMini.throwOnErr = throwOnErr
18
18
  },
19
- newErr(err) {
19
+ newErr(err: any) {
20
20
  restTestMini.nbError++
21
21
  restTestMini.lastErrors.push(err)
22
22
  if (restTestMini.throwOnErr) throw new Error(err)
@@ -7,9 +7,9 @@ import { DescriptiveError } from './error-utils'
7
7
  import { round2 } from './math-utils'
8
8
 
9
9
 
10
- export async function timeout(ms, fn = () => { /* */ }) { return new Promise(res => setTimeout(res, ms)).then(fn) }
10
+ export async function timeout(ms: number, fn = () => { /* */ }) { return new Promise(res => setTimeout(res, ms)).then(fn) }
11
11
 
12
- export async function runAsync(callback, milliseconds$ = 1) { return timeout(milliseconds$, callback) }
12
+ export async function runAsync(callback: () => any, milliseconds$ = 1) { return timeout(milliseconds$, callback) }
13
13
 
14
14
  /**
15
15
  *
@@ -18,7 +18,7 @@ export async function runAsync(callback, milliseconds$ = 1) { return timeout(mil
18
18
  * @param {Boolean|String} errorAfterNSeconds default:true output an error in case of timeout, can be the displayed error message
19
19
  * @param {*} cliOutput write a cli progress to show that a process is running
20
20
  */
21
- export async function waitUntilTrue(callback, timeoutSec = 10, errorAfterNSeconds = true, cliOutput = true) {
21
+ export async function waitUntilTrue(callback: () => any, timeoutSec = 10, errorAfterNSeconds = true, cliOutput = true) {
22
22
  let generalTimeout = true
23
23
  let step = 3
24
24
  const errMess = typeof errorAfterNSeconds === 'string' ? 'Timeout: ' + errorAfterNSeconds : 'Timeout for waitUntilTrue() callback'
@@ -42,7 +42,7 @@ let isExecuting = false
42
42
  * @param {Number} time default: 500ms;
43
43
  * @param {Function} errorCallback default: e => C.error(e)
44
44
  */
45
- export async function executeInDelayedLoop(callback, time = 500, errorCallback = e => C.error(e)) {
45
+ export async function executeInDelayedLoop(callback: () => any, time = 500, errorCallback = (e: any) => C.error(e)) {
46
46
  delayedLoopParams.push([callback, time, errorCallback])
47
47
  if (isExecuting) return
48
48
  isExecuting = true
@@ -9,7 +9,7 @@ import { timeout } from './timer-utils'
9
9
  describe('TRANSACTION TEST', () => {
10
10
  const statusArr = [] as number[]
11
11
 
12
- const asyncCallback = i => async () => {
12
+ const asyncCallback = (i: number) => async () => {
13
13
  await timeout(1000)
14
14
  statusArr.push(i)
15
15
  }
@@ -5,8 +5,8 @@ import { isset } from './isset'
5
5
  import { C } from './logger-utils'
6
6
  import { timeout } from './timer-utils'
7
7
 
8
- const transactionRunning = { __default: false }
9
- const queue = { __default: [] }
8
+ const transactionRunning = { __default: false } as Record<string, boolean>
9
+ const queue = { __default: [] } as Record<string, any[]>
10
10
 
11
11
  /** Allow to perform async functions in a defined order
12
12
  * This adds the callback to a queue and is resolved when ALL previous callbacks with same name are executed
@@ -16,7 +16,7 @@ const queue = { __default: [] }
16
16
  * @param {Number} timeout default: 120000 (120s) will throw an error if transaction time is higher that this amount of ms
17
17
  * @returns {Promise}
18
18
  */
19
- export async function transaction(name, asyncCallback, timeout = 120000, doNotThrow = false) {
19
+ export async function transaction(name: string, asyncCallback: () => any, timeout = 120000, doNotThrow = false) {
20
20
  if (typeof name === 'function') {
21
21
  asyncCallback = name
22
22
  name = '__default'
@@ -45,7 +45,7 @@ export async function transaction(name, asyncCallback, timeout = 120000, doNotTh
45
45
  })
46
46
  }
47
47
 
48
- export async function removeItemFromQueue(name) {// meoww!
48
+ export async function removeItemFromQueue(name: string) {// meoww!
49
49
  if (transactionRunning[name] === true) return // v
50
50
  transactionRunning[name] = true // A A /\
51
51
  while (queue[name].length) await queue[name].shift()() // ||
@@ -54,7 +54,7 @@ export async function removeItemFromQueue(name) {// meoww!
54
54
  // 11 11
55
55
 
56
56
  /** Wait for a transaction to complete without creating a new transaction */
57
- export async function waitForTransaction(transactionName, forceReleaseInSeconds = 30) {
57
+ export async function waitForTransaction(transactionName: string, forceReleaseInSeconds = 30) {
58
58
  let brk = false
59
59
  setTimeout(() => brk = true, forceReleaseInSeconds * 1000)
60
60
  while (isset(transactionRunning[transactionName]) && transactionRunning[transactionName] === true) {
@@ -11,17 +11,17 @@ import { removeCircularJSONstringify } from './remove-circular-json-stringify'
11
11
 
12
12
  export type BaseTypes = 'objectId' | 'dateInt6' | 'dateInt' | 'dateInt8' | 'dateInt12' | 'time' | 'humanReadableTimestamp' | 'date' | 'dateObject' | 'array' | 'object' | 'buffer' | 'string' | 'function' | 'boolean' | 'number' | 'bigint' | 'year' | 'email' | 'any'
13
13
 
14
- export function issetOr(...elms) { return elms.some(elm => typeof elm !== 'undefined' && elm !== null) }
14
+ export function issetOr(...elms: any[]) { return elms.some(elm => typeof elm !== 'undefined' && elm !== null) }
15
15
 
16
- export function isEmptyOrNotSet(...elms) { return elms.some(elm => !isset(elm) || isEmpty(elm)) }
16
+ export function isEmptyOrNotSet(...elms: any[]) { return elms.some(elm => !isset(elm) || isEmpty(elm)) }
17
17
 
18
- export function isDateObject(variable) { return variable instanceof Date }
18
+ export function isDateObject(variable: any[]) { return variable instanceof Date }
19
19
 
20
20
  /** Check all values are set */
21
- export function checkAllObjectValuesAreEmpty(o) { return Object.values(o).every(value => !isset(value)) }
21
+ export function checkAllObjectValuesAreEmpty(o: Record<string, any>) { return Object.values(o).every(value => !isset(value)) }
22
22
 
23
23
  /** Throw an error in case data passed is not a valid ctx */
24
- export function checkCtxIntegrity(ctx) {
24
+ export function checkCtxIntegrity(ctx: Record<string, any>) {
25
25
  if (!isset(ctx) || !isset(ctx.user)) throw new DescriptiveError('ctxNotSet', { code: 500 })
26
26
  }
27
27
 
@@ -102,7 +102,7 @@ export function isValid(...paramsToValidate: ValidatorObject[]) {
102
102
  return errArray.length ? false : true
103
103
  }
104
104
 
105
- function parseValueForDisplay(value?) {
105
+ function parseValueForDisplay(value?: any) {
106
106
  try {
107
107
  if (value === undefined) return 'undefined'
108
108
  else if (value?.data?.data) return { ...value, data: 'Buffer' }
@@ -115,7 +115,7 @@ function parseValueForDisplay(value?) {
115
115
  /** Default types + custom types
116
116
  * 'objectId','dateInt6','dateInt','dateInt8','dateInt12','time','humanReadableTimestamp','date','array','object','buffer','string','function','boolean','number','bigint',
117
117
  */
118
- export function isType(value, type: BaseTypes) { return isValid({ name: 'Is type check', value, type, emptyAllowed: true }) }
118
+ export function isType(value: any, type: BaseTypes) { return isValid({ name: 'Is type check', value, type, emptyAllowed: true }) }
119
119
 
120
120
  export function validatorReturnErrArray(...paramsToValidate: ValidatorObject[]): [string?, object?] {
121
121
  const paramsFormatted: ValidatorObject[] = []
@@ -127,7 +127,7 @@ export function validatorReturnErrArray(...paramsToValidate: ValidatorObject[]):
127
127
 
128
128
  // parse => name: {myVar1: 'blah, myvar2: myvar2}
129
129
  if (typeof param.name === 'object' && !Array.isArray(param.name))
130
- Object.keys(param.name).forEach(name => paramsFormatted.push(Object.assign({}, param, { name: name, value: param?.name?.[name] })))
130
+ Object.keys(param.name).forEach(name => paramsFormatted.push(Object.assign({}, param, { name: name, value: param?.name?.[name as any] })))
131
131
  else paramsFormatted.push(param)
132
132
  })
133
133
 
@@ -138,7 +138,7 @@ export function validatorReturnErrArray(...paramsToValidate: ValidatorObject[]):
138
138
  let optional = paramObj.optional || false
139
139
  const emptyAllowed = optional || paramObj.emptyAllowed || false
140
140
  if (paramObj.isset === false) paramObj.mustNotBeSet = true // ALIAS
141
- const errMess = (msg, extraInfos = {}, errCode = 422): [string, object] => [msg, { code: errCode, origin: 'Generic validator', varName: name, varType: typeof value, gotValue: parseValueForDisplay(value), ...extraInfos }]
141
+ const errMess = (msg: string, extraInfos = {}, errCode = 422): [string, object] => [msg, { code: errCode, origin: 'Generic validator', varName: name, varType: typeof value, gotValue: parseValueForDisplay(value), ...extraInfos }]
142
142
 
143
143
  // accept syntax { 'myVar.var2': myVar.var2, ... }
144
144
  if (typeof name !== 'undefined' && !hasValue) {
@@ -167,7 +167,7 @@ export function validatorReturnErrArray(...paramsToValidate: ValidatorObject[]):
167
167
  const areSomeTypeValid = types.some(type => {
168
168
  if (type.endsWith('[]')) {
169
169
  if (!Array.isArray(value)) errMess('wrongTypeForVar', { expectedType: 'array', gotType: typeof value })
170
- type = type.replace('[]', '')
170
+ type = type.replace('[]', '') as typeof type
171
171
  }
172
172
 
173
173
  const allTypes: Array<BaseTypes> = [
@@ -197,26 +197,28 @@ export function validatorReturnErrArray(...paramsToValidate: ValidatorObject[]):
197
197
  if (!allTypes.includes(type)) throw new DescriptiveError('typeDoNotExist', { code: 500, type })
198
198
 
199
199
  const basicTypeCheck = {
200
- objectId: val => /^[0-9a-fA-F-]{24,}$/.test(val), // "0c65940b-6b0c-4dd8-9c7a-7c5fe1ba907a"
201
- dateInt6: val => isDateIntOrStringValid(parseInt(val + '01'), true, 8),
202
- dateInt: val => isDateIntOrStringValid(val, true, 8),
203
- dateInt8: val => isDateIntOrStringValid(val, true, 8),
204
- dateInt12: val => isDateIntOrStringValid(val, true, 12),
205
- time: val => /^\d\d:\d\d$/.test(val) && isTimeStringValid(val),
206
- humanReadableTimestamp: val => (val + '').length === 17,
207
- date: val => isDateIsoOrObjectValid(val, true),
208
- dateObject: val => isDateIsoOrObjectValid(val, true),
209
- array: val => Array.isArray(val),
210
- object: val => !Array.isArray(val) && val !== null && typeof val === type,
211
- buffer: val => Buffer.isBuffer(val),
212
- year: val => /^\d\d\d\d$/.test(val),
213
- email: val => /^[^\s@]+@([^\s@.,]+\.)+[^\s@.,]+$/.test(val),
200
+ objectId: (val: any) => /^[0-9a-fA-F-]{24,}$/.test(val), // "0c65940b-6b0c-4dd8-9c7a-7c5fe1ba907a"
201
+ dateInt6: (val: any) => isDateIntOrStringValid(parseInt(val + '01'), true, 8),
202
+ dateInt: (val: any) => isDateIntOrStringValid(val, true, 8),
203
+ dateInt8: (val: any) => isDateIntOrStringValid(val, true, 8),
204
+ dateInt12: (val: any) => isDateIntOrStringValid(val, true, 12),
205
+ time: (val: any) => /^\d\d:\d\d$/.test(val) && isTimeStringValid(val),
206
+ humanReadableTimestamp: (val: any) => (val + '').length === 17,
207
+ date: (val: any) => isDateIsoOrObjectValid(val, true),
208
+ dateObject: (val: any) => isDateIsoOrObjectValid(val, true),
209
+ array: (val: any) => Array.isArray(val),
210
+ object: (val: any) => !Array.isArray(val) && val !== null && typeof val === type,
211
+ buffer: (val: any) => Buffer.isBuffer(val),
212
+ year: (val: any) => /^\d\d\d\d$/.test(val),
213
+ email: (val: any) => /^[^\s@]+@([^\s@.,]+\.)+[^\s@.,]+$/.test(val),
214
214
  any: () => true,
215
215
  }
216
216
 
217
- return typeof basicTypeCheck?.[type] !== 'undefined' && basicTypeCheck?.[type](value) ||
217
+ const typeTyped = type as keyof typeof basicTypeCheck
218
+
219
+ return typeof basicTypeCheck?.[typeTyped] !== 'undefined' && basicTypeCheck?.[typeTyped](value) ||
218
220
  typeof value === type && type !== 'object' || // for string, number, boolean...
219
- typeof configFn()?.customTypes?.[type] !== 'undefined' && configFn()?.customTypes?.[type]?.test(value)
221
+ typeof (configFn()?.customTypes as any)?.[typeTyped as any] !== 'undefined' && (configFn()?.customTypes as any)?.[typeTyped as any]?.test(value)
220
222
  })
221
223
  if (!areSomeTypeValid) return errMess(`wrongTypeForVar`, { expectedTypes: types.join(', '), gotType: Object.prototype.toString.call(value), gotValue: parseValueForDisplay(value) })
222
224
  }
package/src/wtf-utils.ts CHANGED
@@ -12,7 +12,7 @@ export function chineseProverb() {
12
12
  return ['é ', 'àe', 'èa', 'ùt', 'çi'].reduce((s, e) => s.replace(new RegExp(e[0], 'g'), e[1]), str).split('$')[Math.floor(Math.random() * 11)]
13
13
  }
14
14
 
15
- export function randomEmoji(msg, length = 20) {
15
+ export function randomEmoji(msg: string, length = 20) {
16
16
  const o = `\u0298\u203f\u0298§\u0ca0\u005f\u0ca0§\u0028\uff61\u25d5\u203f\u25d5\uff61\u0029§\uff08\u3000\uff9f\u0414\uff9f\uff09§\u0028\u256c\u0020\u0ca0\u76ca\u0ca0\u0029§\u0ca0\u203f\u0ca0§\u0028\u0020\u0361\u00b0\u0020\u035c\u0296\u0020\u0361\u00b0\u0029§\u0ca5\u005f\u0ca5§\u0ca5\ufe4f\u0ca5§\u2299\ufe4f\u2299§\u00b0\u203f\u203f\u00b0§\u0028\u00b4\uff65\u005f\uff65\u0060\u0029§\u0c20\u005f\u0c20§\u0028\u2299\u005f\u25ce\u0029§\u30df\u25cf\ufe4f\u2609\u30df§\u0028\u0ca5\u2323\u0ca5\u0029§\u0028\u0e51\u2022\u0301\u0020\u2083\u0020\u2022\u0300\u0e51\u0029§\u25d4\u005f\u25d4§\u2665\u203f\u2665§\u0028\u0020\u02d8\u0020\u00b3\u02d8\u0029\u2665§\u0028\u0020\u02c7\u0df4\u02c7\u0020\u0029§\u0028\u0482\u25e1\u005f\u25e1\u0029§\u2940\u002e\u2940§\u0028\u2a7e\ufe4f\u2a7d\u0029§\u0028\u0020\u0c20\u0020\u035f\u0296\u0020\u0c20\u0029§\u0028\u0020\u0361\u0ca0\u0020\u0296\u032f\u0020\u0361\u0ca0\u0029§\u0028\u0020\u0ca0\u0020\u0296\u032f\u0020\u0ca0\u0029§\u2668\u005f\u2668§\u0028\u002e\u005f\u002e\u0029§\ub208\u005f\ub208§\u0028\u25e0\ufe4f\u25e0\u0029§\u25d6\u1d54\u1d25\u1d54\u25d7\u0020\u266a\u0020\u266b§\u007b\u2022\u0303\u005f\u2022\u0303\u007d§\u0028\u1d54\u1d25\u1d54\u0029§\u0028\u053e\u2038\u0020\u053e\u0029§\u00af\u005c\u005f\u0028\u30c4\u0029\u005f\u002f\u00af§\u00af\u005c\u0028\u00b0\u005f\u006f\u0029\u002f\u00af§\u00af\u005c\u005f\u0028\u2299\ufe3f\u2299\u0029\u005f\u002f\u00af§\u0505\u0028\u2256\u203f\u2256\u0505\u0029§\u10da\u0028\uff40\u30fc\u00b4\u10da\u0029§\u261c\u0028\u2312\u25bd\u2312\u0029\u261e§\u30fd\u0028\u00b4\u25bd\u0060\u0029\u002f§\u30fd\u0028\u00b4\u30fc\uff40\u0029\u30ce§\u1559\u0028\u21c0\u2038\u21bc\u2036\u0029\u1557§\u1566\u0028\u00f2\u005f\u00f3\u02c7\u0029\u1564§\u2282\u0028\u25c9\u203f\u25c9\u0029\u3064§\u0071\u0028\u2742\u203f\u2742\u0029\u0070§\u00bf\u24e7\u005f\u24e7\ufb8c§\u0028\u2299\u002e\u2609\u0029§\u0449\uff08\uff9f\u0414\uff9f\u0449\uff09§\u0669\u0028\u0e4f\u005f\u0e4f\u0029\u06f6§\u0074\u0028\u002d\u005f\u002d\u0074\u0029§\u0028\u3065\uffe3\u0020\u00b3\uffe3\u0029\u3065§\u0028\u3065\uff61\u25d5\u203f\u203f\u25d5\uff61\u0029\u3065§\u201c\u30fd\u0028\u00b4\u25bd\uff40\u0029\u30ce\u201d§\u250c\u0028\u3186\u3268\u3186\u0029\u0283§\u0028\u2283\uff61\u2022\u0301\u203f\u2022\u0300\uff61\u0029\u2283§\u0028\u3063\u02d8\u06a1\u02d8\u03c2\u0029§\u0028\u0e07\u30c4\u0029\u0e27§\u30fe\u0028\u002d\u005f\u002d\u0020\u0029\u309e§\u266a\u266a\u0020\u30fd\u0028\u02c7\u2200\u02c7\u0020\u0029\u309e§\u30fe\u0028\u00b4\u3007\u0060\u0029\uff89\u266a\u266a\u266a§\u0028\u3063\u2580\u00af\u2580\u0029\u3064§\u0028\u00b4\u0436\uff40\u03c2\u0029§\u0028\u00b0\u0020\u035c\u0296\u0361\u00b0\u0029\u256d\u2229\u256e§\u062d\u0028\u2022\u0300\u0436\u2022\u0301\u0029\u0e07\u0020\u2020§\u007e\u0028\u005e\u002d\u005e\u0029\u007e§\u005c\u0028\u1d54\u1d55\u1d54\u0029\u002f§\u10da\u0028\u2022\u0301\u2022\u0301\u10da\u0029§\u0028\u0e07\u2019\u0300\u002d\u2018\u0301\u0029\u0e07§\u0028\u2022\u0300\u1d17\u2022\u0301\u0029\u0648\u0020\u0311\u0311§\u005b\u00ac\u00ba\u002d\u00b0\u005d\u00ac§\u0028\u261e\uff9f\u30ee\uff9f\u0029\u261e§\u00bb\u2310\u0028\u0ca0\u06fe\u0ca0\u0029\u00ac\u0020\u00bb\u2019§\u0028\u3063\u2022\u0301\uff61\u2022\u0301\u0029\u266a\u266c§\u01aa\u0028\u0693\u05f2\u0029\u200e\u01aa\u200b\u200b§\u0295\u2022\u1d25\u2022\u0294§\u0295\u1d54\u1d25\u1d54\u0294§\u0295\u0020\u2022\u0060\u1d25\u2022\u00b4\u0294§\u0295\u0020\u2022\u0301\u0608\u2022\u0300\u0020\u208e§\u0028\u0060\uff65\u03c9\uff65\u00b4\u0029§\u1d52\u1d25\u1d52§\u0056\u2022\u1d25\u2022\u0056§\u0e05\u005e\u2022\ufecc\u2022\u005e\u0e05§\u0028\u0020\u0c20\u0d60\u0c20\u0020\u0029\uff89§\u0295\u0298\u0305\u035c\u0298\u0305\u0294§\u062d\u02da\u0bf0\u02da\u3065§\u0028\u256f\u00b0\u25a1\u00b0\uff09\u256f\ufe35\u0020\u253b\u2501\u253b§\u252c\u2500\u252c\ufeff\u0020\u30ce\u0028\u0020\u309c\u002d\u309c\u30ce\u0029§\u252c\u2500\u252c\u20f0\u0361\u2007\u0028\u1d54\u1d55\u1d54\u035c\u2007\u0029§\u253b\u2501\u253b\u0020\ufe35\u30fd\u0028\u0060\u0414\u00b4\u0029\uff89\ufe35\ufeff\u0020\u253b\u2501\u253b§\u0028\u30ce\u0ca0\u0020\u2229\u0ca0\u0029\u30ce\u5f61\u0028\u0020\u005c\u006f\u00b0\u006f\u0029\u005c§\uff08\u0020\u005e\u005f\u005e\uff09\u006f\u81ea\u81ea\u006f\uff08\u005e\u005f\u005e\u0020\uff09§\u0f3c\u2235\u0f3d§\u0f3c\u2368\u0f3d§\u0f3c\u2362\u0f3d§\u0f3c\u2364\u0f3d§\u30fd\u0f3c\u0020\u0ca0\u76ca\u0ca0\u0020\u0f3d\uff89§\u4e41\u0028\u0020\u25d4\u0020\u0c6a\u25d4\u0029\u300c§\u0028\u2229\uff40\u002d\u00b4\u0029\u2283\u2501\u2606\uff9f\u002e\u002a\uff65\uff61\uff9f`.split('§')[Math.floor(Math.random() * 100)]
17
17
  return o.padEnd(length, ' ') + (msg ? '< ' + msg : '')
18
18
  }
@@ -22,7 +22,7 @@ type CompObject = { char: string, replacement: string }
22
22
  /** STRING COMPRESSOR
23
23
  * peut facilement être utilisé par uncomp directement (stock les metadonnées sur la comp)
24
24
  */
25
- export function compAuto(str) {
25
+ export function compAuto(str: string) {
26
26
 
27
27
  const oldStrLength = str.length
28
28
  const utf8Chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ:;<=>%?@"#$&\'()*+,-./[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u007f€\u0081‚ƒ„…†‡ˆ‰Š‹ŒŽ\u008f‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŔŕŖŗŘřŚśŜŝŞşŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŹźŻżſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƓƔƕƖƗƘƙƚƛƜƝƞƟ'.split('')
@@ -31,8 +31,8 @@ export function compAuto(str) {
31
31
  const unusedChars = utf8Chars.filter(c => !str.includes(c))
32
32
  const charMap: CompObject[] = []
33
33
 
34
- const mostFreqStr = str2 => {
35
- const o = {}
34
+ const mostFreqStr = (str2: string) => {
35
+ const o = {} as Record<string, any>
36
36
  // recherche la meilleure optim selon le nb de char
37
37
  for (let strLength = 2; strLength < 16; strLength++) {
38
38
  for (let i = 0; isset(str2[i + strLength - 1]); i++) {
@@ -68,10 +68,10 @@ export function compAuto(str) {
68
68
  return str
69
69
  }
70
70
 
71
- export function unComp(str) {
71
+ export function unComp(str: string) {
72
72
  const charMap: CompObject[] = []
73
73
  const map = str.split('§')
74
- str = map.pop()
74
+ str = map.pop() as string
75
75
  map.forEach(e => {
76
76
  const char: string = e[0]
77
77
  let replacement = e.substring(1, 999)
package/tsconfig.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "module": "commonjs",
5
5
  "esModuleInterop": true,
6
6
  "allowSyntheticDefaultImports": true,
7
- "noImplicitAny": false,
7
+ // "noImplicitAny": false,
8
8
  "strict": true,
9
9
  "declaration": true,
10
10
  "moduleResolution": "node",