topkat-utils 1.0.60 → 1.1.2

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 (102) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/index.d.ts +34 -0
  3. package/dist/index.js +56 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/src/array-utils.d.ts +56 -0
  6. package/dist/src/array-utils.js +138 -0
  7. package/dist/src/array-utils.js.map +1 -0
  8. package/dist/src/date-utils.d.ts +100 -0
  9. package/dist/src/date-utils.js +357 -0
  10. package/dist/src/date-utils.js.map +1 -0
  11. package/dist/src/env-utils.d.ts +8 -0
  12. package/dist/src/env-utils.js +38 -0
  13. package/dist/src/env-utils.js.map +1 -0
  14. package/dist/src/error-utils.d.ts +8 -0
  15. package/dist/src/error-utils.js +99 -0
  16. package/dist/src/error-utils.js.map +1 -0
  17. package/dist/src/is-empty.d.ts +1 -0
  18. package/dist/src/is-empty.js +13 -0
  19. package/dist/src/is-empty.js.map +1 -0
  20. package/dist/src/is-object.d.ts +2 -0
  21. package/dist/src/is-object.js +7 -0
  22. package/dist/src/is-object.js.map +1 -0
  23. package/dist/src/isset.d.ts +1 -0
  24. package/dist/src/isset.js +8 -0
  25. package/dist/src/isset.js.map +1 -0
  26. package/dist/src/logger-utils.d.ts +76 -0
  27. package/dist/src/logger-utils.js +355 -0
  28. package/dist/src/logger-utils.js.map +1 -0
  29. package/dist/src/loop-utils.d.ts +37 -0
  30. package/dist/src/loop-utils.js +105 -0
  31. package/dist/src/loop-utils.js.map +1 -0
  32. package/dist/src/math-utils.d.ts +23 -0
  33. package/dist/src/math-utils.js +43 -0
  34. package/dist/src/math-utils.js.map +1 -0
  35. package/dist/src/mongo-utils.d.ts +11 -0
  36. package/dist/src/mongo-utils.js +49 -0
  37. package/dist/src/mongo-utils.js.map +1 -0
  38. package/dist/src/object-utils.d.ts +96 -0
  39. package/dist/src/object-utils.js +369 -0
  40. package/dist/src/object-utils.js.map +1 -0
  41. package/dist/src/private/config.d.ts +44 -0
  42. package/dist/src/private/config.js +55 -0
  43. package/dist/src/private/config.js.map +1 -0
  44. package/dist/src/private/error-handler.d.ts +10 -0
  45. package/dist/src/private/error-handler.js +18 -0
  46. package/dist/src/private/error-handler.js.map +1 -0
  47. package/dist/src/private/types.d.ts +4 -0
  48. package/dist/src/private/types.js +3 -0
  49. package/dist/src/private/types.js.map +1 -0
  50. package/dist/src/regexp-utils.d.ts +12 -0
  51. package/dist/src/regexp-utils.js +44 -0
  52. package/dist/src/regexp-utils.js.map +1 -0
  53. package/dist/src/remove-circular-json-stringify.d.ts +1 -0
  54. package/dist/src/remove-circular-json-stringify.js +20 -0
  55. package/dist/src/remove-circular-json-stringify.js.map +1 -0
  56. package/dist/src/string-utils.d.ts +77 -0
  57. package/dist/src/string-utils.js +209 -0
  58. package/dist/src/string-utils.js.map +1 -0
  59. package/dist/src/tests-utils.js +77 -0
  60. package/dist/src/tests-utils.js.map +1 -0
  61. package/dist/src/timer-utils.d.ts +16 -0
  62. package/dist/src/timer-utils.js +79 -0
  63. package/dist/src/timer-utils.js.map +1 -0
  64. package/dist/src/transaction-utils.d.ts +14 -0
  65. package/dist/src/transaction-utils.js +87 -0
  66. package/dist/src/transaction-utils.js.map +1 -0
  67. package/dist/src/validation-utils.d.ts +89 -0
  68. package/dist/src/validation-utils.js +192 -0
  69. package/dist/src/validation-utils.js.map +1 -0
  70. package/dist/src/wtf-utils.d.ts +7 -0
  71. package/dist/src/wtf-utils.js +83 -0
  72. package/dist/src/wtf-utils.js.map +1 -0
  73. package/index.ts +38 -0
  74. package/package.json +2 -2
  75. package/src/array-utils.ts +128 -0
  76. package/src/date-utils.ts +377 -0
  77. package/src/env-utils.ts +29 -0
  78. package/src/error-utils.ts +77 -0
  79. package/src/is-empty.ts +5 -0
  80. package/src/is-object.ts +3 -0
  81. package/src/isset.ts +3 -0
  82. package/src/logger-utils.ts +349 -0
  83. package/src/loop-utils.ts +101 -0
  84. package/src/math-utils.ts +38 -0
  85. package/src/mongo-utils.ts +38 -0
  86. package/src/object-utils.ts +356 -0
  87. package/src/private/config.ts +85 -0
  88. package/src/private/error-handler.ts +21 -0
  89. package/src/private/types.ts +6 -0
  90. package/src/regexp-utils.ts +37 -0
  91. package/src/remove-circular-json-stringify.ts +17 -0
  92. package/src/string-utils.ts +212 -0
  93. package/src/tests-utils.ts +70 -0
  94. package/src/timer-utils.ts +58 -0
  95. package/src/transaction-utils.ts +63 -0
  96. package/src/validation-utils.ts +253 -0
  97. package/src/wtf-utils.ts +88 -0
  98. package/tsconfig.json +11 -4
  99. package/utils.d.ts +0 -694
  100. package/utils.js +0 -2227
  101. package/utils.js.map +0 -1
  102. package/utils.ts +0 -2304
package/utils.d.ts DELETED
@@ -1,694 +0,0 @@
1
- declare type Color = [number, number, number];
2
- declare type ObjectGeneric = {
3
- [k: string]: any;
4
- };
5
- export declare type BaseTypes = 'objectId' | 'dateInt6' | 'dateInt' | 'dateInt8' | 'dateInt12' | 'time' | 'humanReadableTimestamp' | 'date' | 'dateObject' | 'array' | 'object' | 'buffer' | 'string' | 'function' | 'boolean' | 'number' | 'bigint' | 'year' | 'email' | 'any';
6
- /** Round with custom number of decimals (default:0) */
7
- export declare function round(number: number | string, decimals?: number): number;
8
- /** Round with custom number of decimals (default:2) */
9
- export declare function round2(number: number | string, decimals?: number): number;
10
- /** Is number between two numbers (including those numbers) */
11
- export declare function isBetween(number: number, min: number, max: number, inclusive?: boolean): boolean;
12
- /** Random number between two values with 0 decimals by default */
13
- export declare function random(nb1: number, nb2: number, nbOfDecimals?: number): number;
14
- /** Sum all values of an array, all values MUST be numbers */
15
- export declare function sumArray(array: number[]): number;
16
- /** Moyenne / average between array of values
17
- * @param {Number} round number of decimals to keep. Default:2
18
- */
19
- export declare function moyenne(array: number[], nbOfDecimals?: number): number;
20
- /** Clean output for outside world. All undefined / null / NaN / Infinity values are changed to '-' */
21
- export declare function cln(val: any, replacerInCaseItIsUndefinNaN?: string): any;
22
- /** length default 2, shortcut for 1 to 01 */
23
- export declare function pad(numberOrStr: number | string, length?: number): string;
24
- /** return the number or the closest number of the range
25
- * * nb min max => returns
26
- * * 7 5 10 => 7 // in the range
27
- * * 2 5 10 => 5 // below the min value
28
- * * 99 5 10 => 10// above the max value
29
- */
30
- export declare function minMax(nb: number, min: number, max: number): number;
31
- export declare function tryCatch(callback: Function, onErr?: Function): Promise<any>;
32
- /** minLength 8 if unique
33
- * @param {Number} length default: 20
34
- * @param {Boolean} unique default: true. Generate a real unique token base on the date. min length will be min 8 in this case
35
- * @param {string} mode one of ['alphanumeric', 'hexadecimal']
36
- * NOTE: to generate a mongoDB Random Id, use the params: 24, true, 'hexadecimal'
37
- */
38
- export declare function generateToken(length?: number, unique?: boolean, mode?: 'alphanumeric' | 'hexadecimal'): any;
39
- export declare function generateObjectId(): any;
40
- /** Useful to join differents bits of url with normalizing slashes
41
- * * urlPathJoin('https://', 'www.kikou.lol/', '/user', '//2//') => https://www.kikou.lol/user/2/
42
- * * urlPathJoin('http:/', 'kikou.lol') => https://www.kikou.lol
43
- */
44
- export declare function urlPathJoin(...bits: string[]): string;
45
- /** path shall always be sorted before using in express
46
- * to avoid a generic route like /* to catch a specific one like /bonjour
47
- *
48
- * @param {Object[]} urlObjOrArr
49
- * @param {String} propInObjectOrIndexInArray
50
- * @return {Array} urls modified
51
- */
52
- export declare function sortUrlsByDeepnessInArrayOrObject(urlObjOrArr: any, propInObjectOrIndexInArray: any): any;
53
- export declare type MiniTemplaterOptions = {
54
- valueWhenNotSet?: string;
55
- regexp?: RegExp;
56
- valueWhenContentUndefined?: string;
57
- };
58
- /** Replace variables in a string like: `Hello {{userName}}!`
59
- * @param {String} content
60
- * @param {Object} varz object with key => value === toReplace => replacer
61
- * @param {Object} options
62
- * * valueWhenNotSet => replacer for undefined values. Default: ''
63
- * * regexp => must be 'g' and first capturing group matching the value to replace. Default: /{{\s*([^}]*)\s*}}/g
64
- */
65
- export declare function miniTemplater(content: string, varz: ObjectGeneric, options?: MiniTemplaterOptions): string;
66
- /**
67
- *
68
- * @param {Object} object main object
69
- * @param {String[]} maskedOrSelectedFields array of fields
70
- * @param {Boolean} isMask default: true; determine the behavior of the function. If is mask, selected fields will not appear in the resulting object. If it's a select, only selected fields will appear.
71
- * @param {Boolean} deleteKeysInsteadOfReturningAnewObject default:false; modify the existing object instead of creating a new instance
72
- */
73
- export declare function simpleObjectMaskOrSelect(object: ObjectGeneric, maskedOrSelectedFields: string[], isMask?: boolean, deleteKeysInsteadOfReturningAnewObject?: boolean): ObjectGeneric;
74
- /** Parse one dimention object undefined, true, false, null represented as string will be converted to primitives */
75
- export declare function parseEnv(env: any): {};
76
- /** READ ONLY, output a parsed version of process.env
77
- * use it like ENV().myVar
78
- */
79
- export declare function ENV(): {
80
- [key: string]: any;
81
- };
82
- /**
83
- * @param {any} mayBeAstring
84
- * @return !!value
85
- */
86
- export declare function parseBool(mayBeAstring: string | boolean | number): boolean;
87
- export declare function dim(str?: string): string;
88
- export declare type Config = {
89
- env: string;
90
- isProd: boolean;
91
- nbOfLogsToKeep: number;
92
- customTypes: object;
93
- preprocessLog?: Function;
94
- terminal: {
95
- noColor: boolean;
96
- theme: {
97
- primary: Color;
98
- shade1: Color;
99
- shade2: Color;
100
- bgColor?: Color;
101
- paddingX: number;
102
- paddingY: number;
103
- fontColor?: Color;
104
- pageWidth: number;
105
- debugModeColor: Color;
106
- };
107
- };
108
- };
109
- /** Allow dynamic changing of config */
110
- export declare function configFn(): Config;
111
- /** Register custom config
112
- * @param {object} customConfig { 'email': email => /.+@.+/.test(email), type2 : myTestFunction() }
113
- * * env: 'development',
114
- * * customTypes: {},
115
- * * terminal: {
116
- * * noColor: false, // disable colored escape sequences like /mOO35...etc
117
- * * theme: {
118
- * * primary: [61, 167, 32], // main color (title font)
119
- * * shade1: [127, 192, 39], // gradient shade 1
120
- * * shade2: [194, 218, 47], // gradient shade 2
121
- * * bgColor: false, // background color
122
- * * paddingX: 2, // nb spaces added before an outputted str
123
- * * paddingY: 2, //
124
- * * fontColor: false, // default font color
125
- * * pageWidth: 53, // page size in character
126
- * * debugModeColor: [147, 212, 6], // usually orange
127
- * * }
128
- * * },
129
- */
130
- export declare function registerConfig(customConfig: any): void;
131
- /**
132
- * check if **object OR array** has property Safely (avoid cannot read property x of null and such)
133
- * @param {Object} obj object to test against
134
- * @param {string} addr `a.b.c.0.1` will test if myObject has props a that has prop b. Work wit arrays as well (like `arr.0`)
135
- */
136
- export declare function has(obj: ObjectGeneric, addr: string): boolean;
137
- /** Find address in an object "a.b.c" IN { a : { b : {c : 'blah' }}} RETURNS 'blah'
138
- * @param obj
139
- * @param addr accept syntax like "obj.subItem.[0].sub2" OR "obj.subItem.0.sub2" OR "obj.subItem[0].sub2"
140
- * @returns the last item of the chain OR undefined if not found
141
- */
142
- export declare function findByAddress(obj: ObjectGeneric, addr: string): any | undefined;
143
- /** Will return all objects matching that path. Eg: user.*.myVar */
144
- export declare function findByAddressAll(obj: any, addr: any, returnAddresses?: true): Array<[string, any]>;
145
- export declare function findByAddressAll(obj: any, addr: any, returnAddresses?: false): Array<any>;
146
- /** Enforce writing subItems. Eg: user.name.blah will ensure all are set until the writing of the last item
147
- * NOTE: doesn't work with arrays
148
- */
149
- export declare function objForceWrite(obj: ObjectGeneric, addr: string, item: any): void;
150
- /** Enforce writing subItems, only if obj.addr is empty.
151
- * Eg: user.name.blah will ensure all are set until the writing of the last item
152
- * if user.name.blah has a value it will not change it.
153
- * NOTE: doesn't work with arrays
154
- */
155
- export declare function objForceWriteIfNotSet(obj: ObjectGeneric, addr: string, item: any): void;
156
- /** Merge mixins into class. Use it in the constructor like: mergeMixins(this, {myMixin: true}) */
157
- export declare function mergeMixins(that: any, ...mixins: any[]): void;
158
- /** If a string is provided, return it as array else return the value */
159
- export declare function strAsArray(arrOrStr: any): any;
160
- /** If not an array provided, return the array with the value
161
- * /!\ NOTE /!\ In case the value is null or undefined, it will return that value
162
- */
163
- export declare function asArray<T extends any[] | any>(item: T): T extends undefined ? undefined : T extends any[] ? T : T[];
164
- /** Array comparison
165
- * @return {object} { inCommon, notInB, notInA }
166
- */
167
- export declare function compareArrays(arrayA: any[], arrayB: any[], compare?: (a: any, b: any) => boolean): {
168
- inCommon: any[];
169
- notInB: any[];
170
- notInA: any[];
171
- };
172
- /**
173
- * @return [] only elements that are both in arrayA and arrayB
174
- */
175
- export declare function getArrayInCommon(arrayA?: any[], arrayB?: any[], compare?: (a: any, b: any) => boolean): any[];
176
- /**
177
- * @return [] only elements that are in arrayB and not in arrayA
178
- */
179
- export declare function getNotInArrayA(arrayA?: any[], arrayB?: any[], compare?: (a: any, b: any) => boolean): any[];
180
- /**
181
- * @return [] only elements that are in neither arrayA and arrayB
182
- */
183
- export declare function getArrayDiff(arrayA?: any[], arrayB?: any[], compare?: (a: any, b: any) => boolean): any[];
184
- /** filter duplicate values in an array
185
- * @param {function} comparisonFn default:(a, b) => a === b. A function that shall return true if two values are considered equal
186
- * @return {array|function}
187
- */
188
- export declare function noDuplicateFilter(arr: any, comparisonFn?: (a: any, b: any) => boolean): any[];
189
- /** Count number of occurence of item in array */
190
- export declare function arrayCount(item: any, arr: any[]): number;
191
- /**
192
- * Sort an array in an object of subArrays, no duplicate.
193
- * @param {Array} array
194
- * @param {function} getFieldFromItem (itemOfArray) => field[String|Number]
195
- * tell me how you want to sort your Array
196
- */
197
- export declare function arrayToObjectSorted(array: any, getFieldFromItem: any): {};
198
- /**
199
- * @param {Function} comparisonFunction default: (itemToPush, itemAlreadyInArray) => itemToPush === itemAlreadyInArray; comparison function to consider the added item duplicate
200
- */
201
- export declare function pushIfNotExist(arrayToPushInto: any, valueOrArrayOfValuesToBePushed: any, comparisonFunction?: (a: any, b: any) => boolean): any[];
202
- export declare function isNotEmptyArray(arr: any): boolean;
203
- export declare function randomItemInArray<T>(array: T[]): T;
204
- export declare function cloneObject(o: any): any;
205
- /** Deep clone. WILL REMOVE circular references */
206
- export declare function deepClone<T>(obj: T, cache?: any[]): T;
207
- /** test if object but not array and not null (null is an object in Js) */
208
- export declare function isObject(o: any): boolean;
209
- /** object and array merge
210
- * @warn /!\ Array will be merged and duplicate values will be deleted /!\
211
- * @return {Object} new object result from merge
212
- * NOTE: objects in params will NOT be modified*/
213
- export declare function mergeDeep(...objects: any[]): any;
214
- /** object and array merge
215
- * @warn /!\ Array will be replaced by the latest object /!\
216
- * @return {Object} new object result from merge
217
- * NOTE: objects in params will NOT be modified */
218
- export declare function mergeDeepOverrideArrays(...objects: any[]): any;
219
- /** object and array merge
220
- * @param {Function} replacerForArrays item[key] = (prevValue, currentVal) => () When 2 values are arrays,
221
- * @param {Function} replacerForObjects item[key] = (prevValue, currentVal) => () When 2 values are objects,
222
- * @param {Function} replacerDefault item[key] = (prevValue, currentVal) => () For all other values
223
- * @param {...Object} objects
224
- * @return {Object} new object result from merge
225
- * NOTE: objects in params will NOT be modified
226
- */
227
- export declare function mergeDeepConfigurable(replacerForArrays: (prev: any, curr: any) => any, replacerForObjects: any, replacerDefault?: (prev: any, curr: any) => any, ...objects: any[]): any;
228
- /** { a: {b:2}} => {'a.b':2} useful for translations
229
- * NOTE: will remove circular references
230
- */
231
- export declare function flattenObject(data: any, config?: {
232
- withoutArraySyntax?: boolean;
233
- withArraySyntaxMinified?: boolean;
234
- }): {};
235
- /** {'a.b':2} => { a: {b:2}} */
236
- export declare function unflattenObject(data: any): {};
237
- export declare type RecursiveCallback = (item: any, addr: string, lastElementKey: string, parent: ObjectGeneric | any[]) => false | any;
238
- /**
239
- * @param {any} item the first array or object or whatever you want to recursively browse
240
- * @param {function} callback the callback you want to apply on items including the main one
241
- * * this callback has 2 arguments: (item, address) =>
242
- * * `item` => the actual item
243
- * * `addr` => the address of the item, not including root (Eg: subItem1.sub2.[3].[2]) array indexes are juste written as numbers
244
- * * `lastElementKey` => the key of last item. May be a number if last item is an array
245
- * * `parent` => reference the parent object as this is the only way of reassigning a value for the item. Eg: parent[lastElementKey] = myNewItem
246
- * * **NOTE** => if a key of an item contains dots, they will be replaced by '%' in `addr`
247
- * * **NOTE2** => if false is returned by the callback it will stop all other iterations (but not in an array)
248
- * @param {string} addr$ optional, the base address for the callback function
249
- * @param lastElementKey technical field
250
- * NOTE: will remove circular references
251
- * /!\ check return values
252
- */
253
- export declare function recursiveGenericFunction(item: ObjectGeneric | any[], callback: RecursiveCallback, addr$?: string, lastElementKey?: string, parent?: any, techFieldToAvoidCircularDependency?: any[]): Promise<any[] | ObjectGeneric>;
254
- /**
255
- * @param {any} item the first array or object or whatever you want to recursively browse
256
- * @param {function} callback the callback you want to apply on items including the main one
257
- * * this callback has 2 arguments: (item, address) =>
258
- * * `item` => the actual item
259
- * * `addr` => the address of the item, not including root (Eg: subItem1.sub2.[3].[2]) array indexes are juste written as numbers
260
- * * `lastElementKey` => the key of last item. May be a number if last item is an array
261
- * * `parent` => reference the parent object as this is the only way of reassigning a value for the item. Eg: parent[lastElementKey] = myNewItem
262
- * * **NOTE** => if a key of an item contains dots, they will be replaced by '%' in `addr`
263
- * * **NOTE2** => if false is returned by the callback it will stop all other iterations (but not in an array)
264
- * * **NOTE3** => to reassign a key use => parent[lastElementKey] = myNewItem
265
- * @param {string} addr$ optional, the base address for the callback function
266
- * @param lastElementKey technical field
267
- * NOTE: will remove circular references
268
- * /!\ check return values
269
- */
270
- export declare function recursiveGenericFunctionSync(item: ObjectGeneric | any[], callback: RecursiveCallback, addr$?: string, lastElementKey?: string, parent?: any, techFieldToAvoidCircularDependency?: any[]): any[] | ObjectGeneric;
271
- /** Remove all key/values pair if value is undefined */
272
- export declare function objFilterUndefined(o: any): any;
273
- /** Lock all 1st level props of an object to read only */
274
- export declare function readOnly(o: any): any;
275
- /** Fields of the object can be created BUT NOT reassignated */
276
- export declare function reassignForbidden(o: any): any;
277
- /** All fileds and subFields of the object will become readOnly */
278
- export declare function readOnlyForAll(object: any): any;
279
- export declare function objFilterUndefinedRecursive(obj: any): any;
280
- export declare function sortObjKeyAccordingToValue(unorderedObj: any, ascending?: boolean): {};
281
- /**
282
- * Make default value if object key do not exist
283
- * @param {object} obj
284
- * @param {string} addr
285
- * @param {any} defaultValue
286
- * @param {function} callback (obj[addr]) => processValue. Eg: myObjAddr => myObjAddr.push('bikou')
287
- * @return obj[addr] eventually processed by the callback
288
- */
289
- export declare function ensureObjectProp(obj: object, addr: string, defaultValue: any, callback?: (o: any) => any): any;
290
- /**
291
- * Maye sure obj[addr] is an array and push a value to it
292
- * @param {Object} obj parent object
293
- * @param {String} addr field name in parent
294
- * @param {Any} valToPush
295
- * @param {Boolean} onlyUniqueValues default:false; may be true or a comparision function; (a,b) => return true if they are the same like (a, b) => a.name === b.name
296
- * @return obj[addr] eventually processed by the callback
297
- */
298
- export declare function ensureIsArrayAndPush(obj: object, addr: string, valToPush: any, onlyUniqueValues: Function): any;
299
- /**
300
- * @param {Object} obj the object on which we want to filter the keys
301
- * @param {function} filterFunc function that returns true if the key match the wanted criteria
302
- */
303
- export declare function filterKeys(obj: object, filter: any): any;
304
- /**
305
- * @param {Object} obj the object on which we want to delete a property
306
- * @param {Array} addr addressArray on which to delete the property
307
- */
308
- export declare function deleteByAddress(obj: object, addr: string[]): void;
309
- /** @return undefined if cannot find _id */
310
- export declare function getId(obj?: any): string;
311
- export declare function forI<T extends any[] | any>(nbIterations: number, callback: (number: number, previousValue: any, arrayOfPreviousValues: any[]) => T): T[];
312
- export declare function forIasync<T extends any[] | any>(nbIterations: number, callback: (number: any) => T): Promise<T[]>;
313
- export declare function cleanStackTrace(stack: any): string;
314
- export declare function isset(...elms: any[]): boolean;
315
- export declare function removeCircularJSONstringify(object: any, indent?: number): string;
316
- export declare function shuffleArray(array: any): any;
317
- /**Eg: camelCase */
318
- export declare function camelCase(...wordBits: any[]): string;
319
- /**Eg: snake_case
320
- * trimmed but not lowerCased
321
- */
322
- export declare function snakeCase(...wordBits: any[]): string;
323
- /**Eg: kebab-case
324
- * trimmed AND lowerCased
325
- * undefined, null... => ''
326
- */
327
- export declare function kebabCase(...wordBits: any[]): string;
328
- /**Eg: PascalCase undefined, null... => '' */
329
- export declare function pascalCase(...wordBits: any[]): string;
330
- /**Eg: Titlecase undefined, null... => '' */
331
- export declare function titleCase(...wordBits: any[]): string;
332
- /**Eg: UPPERCASE undefined, null... => '' */
333
- export declare function upperCase(...wordBits: any[]): string;
334
- /**Eg: lowercase undefined, null... => '' */
335
- export declare function lowerCase(...wordBits: any[]): string;
336
- export declare function capitalize1st(str?: string): string;
337
- export declare function camelCaseToWords(str: any): any;
338
- export declare function escapeRegexp(str: string, config?: {
339
- parseStarChar?: boolean;
340
- }): string;
341
- /** Get first match of the first capturing group of regexp
342
- * Eg: const basePath = firstMatch(apiFile, /basePath = '(.*?)'/); will get what is inside quotes
343
- */
344
- export declare function firstMatch(str: string, regExp: RegExp): string | undefined;
345
- /** Get all matches from regexp with g flag
346
- * Eg: [ [full, match1, m2], [f, m1, m2]... ]
347
- * NOTE: the G flag will be appended to regexp
348
- */
349
- export declare function allMatches(str: string, reg: RegExp): string[];
350
- /** GIVEN A STRING '{ blah;2}, ['nested,(what,ever)']' AND A SEPARATOR ",""
351
- * This will return the content separated by first level of separators
352
- * @return ["{ blah;2}", "['nested,(what,ever)']"]
353
- */
354
- export declare function getValuesBetweenSeparator(str: string, separator: string, removeTrailingSpaces?: boolean): any;
355
- /** GIVEN A STRING "a: [ 'str', /[^]]/, '[aa]]]str', () => [ nestedArray ] ], b: ['arr']"
356
- * @return matching: [ "'str', /[^]]/, '[aa]]]str', () => [ nestedArray ]", "'arr'" ], between: [ "a:", ", b: " ]
357
- * @param str base string
358
- * @param openingOrSeparator opening character OR separator if closing not set
359
- * @param closing
360
- * @param ignoreBetweenOpen default ['\'', '`', '"', '/'], when reaching an opening char, it will ignore all until it find the corresponding closing char
361
- * @param ignoreBetweenClose default ['\'', '`', '"', '/'] list of corresponding closing chars
362
- */
363
- export declare function getValuesBetweenStrings(str: string, openingOrSeparator: any, closing: any, ignoreBetweenOpen?: string[], ignoreBetweenClose?: string[], removeTrailingSpaces?: boolean): {
364
- inner: any;
365
- outer: any;
366
- };
367
- export declare function issetOr(...elms: any[]): boolean;
368
- export declare function isEmptyOrNotSet(...elms: any[]): boolean;
369
- export declare function errIfNotSet(objOfVarNamesWithValues: any, additionalMessage: any): void;
370
- export declare function err500IfNotSet(objOfVarNamesWithValues: any): void;
371
- export declare function errIfEmptyOrNotSet(objOfVarNamesWithValues: any): void;
372
- export declare function err500IfEmptyOrNotSet(objOfVarNamesWithValues: any): void;
373
- export declare function errXXXIfNotSet(errCode: any, checkEmpty: any, objOfVarNamesWithValues: any): void;
374
- export declare function isDateObject(variable: any): boolean;
375
- /** Check all values are set */
376
- export declare function checkAllObjectValuesAreEmpty(o: any): boolean;
377
- /** Throw an error in case data passed is not a valid ctx */
378
- export declare function checkCtxIntegrity(ctx: any): void;
379
- /**
380
- ## VALIDATOR
381
-
382
- @name validator
383
-
384
- @description support multiple names, multiple values and multiple type check
385
- @option if nameString ends by $ sign it is considered optional
386
-
387
- @function validator([Objects])
388
- @return {error|true/false|testMode} depend on mode (see prop mode)
389
- @param {} mode normal (default) | test (TODO) | boolean
390
- @param {} name 'myName' || [{myVar1: 'blah, myvar2: myvar2}], support multiple names / values
391
- @param {} value myVar,
392
- @param {string} myVar myVar, instead of name / value
393
- @param {array} in ['blah', 'otherPossibleValue', true], equal ONE OF THESE values
394
- @param {any} eq exactly equal to in, both support string or array of values
395
- @param {any} neq not in, both support string or array of values
396
- @param {number} lte 3, less than or equal
397
- @param {number} gte 1, greater or equal
398
- @param {number} lt 3, less than
399
- @param {number} gt 1, greater
400
- @param {string|string[]} type
401
- * possibleTypes: object, number, string, boolean, array, date, dateInt8, dateInt12, dateInt6, time, objectId (mongo), humanReadableTimestamp, buffer
402
- * Notes: multiples value is an OR, /!\ Array is type 'array' and not 'object' like in real JS /!\
403
- @param {regExp} regexp /regexp/, test against regexp
404
- @param {number} minLength for string, array or number length
405
- @param {number} maxLength
406
- @param {number} length
407
- @param {boolean} optional default false
408
- @param {boolean} emptyAllowed default false (to use if must be set but can be empty)
409
- @param {boolean} mustNotBeSet this one must not be set
410
- @param {any} includes check if array or string includes value (like js .includes())
411
-
412
- @example
413
- validator(
414
- { myNumber : 3, type: 'number', gte: 1, lte: 3 }, // use the name directly as a param
415
- { name: 'email', value: 'nameATsite.com', regexp: /[^\sAT]+AT[^\sAT]+\.[^\sAT]/},
416
- { name: [{'blahVar': blahVarValue, 'myOtherVar': myOtherVarValue}], type: 'string'} // multiple names for same check
417
- )
418
- ----------------------------------------*/
419
- export declare type ValidatorObject = {
420
- name?: string;
421
- value?: any;
422
- type?: BaseTypes;
423
- eq?: any;
424
- neq?: any;
425
- in?: any[];
426
- lt?: number;
427
- gt?: number;
428
- lte?: number;
429
- gte?: number;
430
- length?: number;
431
- minLength?: number;
432
- maxLength?: number;
433
- emptyAllowed?: boolean;
434
- regexp?: RegExp;
435
- mustNotBeSet?: boolean;
436
- optional?: boolean;
437
- isArray?: boolean;
438
- [k: string]: any;
439
- };
440
- export declare function validator(...paramsToValidate: ValidatorObject[]): void;
441
- export declare const restTestMini: {
442
- throwOnErr: boolean;
443
- reset(throwOnErr?: boolean): void;
444
- newErr(err: any): void;
445
- printStats(): void;
446
- nbSuccess: number;
447
- nbError: number;
448
- lastErrors: any[];
449
- };
450
- export declare function assert(msg: string, value: any, validatorObject?: ValidatorObject | number | boolean | string): void;
451
- /** Same as validator but return a boolean
452
- * See {@link validator}
453
- */
454
- export declare function isValid(...paramsToValidate: any[]): boolean;
455
- /** Default types + custom types
456
- * 'objectId','dateInt6','dateInt','dateInt8','dateInt12','time','humanReadableTimestamp','date','array','object','buffer','string','function','boolean','number','bigint',
457
- */
458
- export declare function isType(value: any, type: BaseTypes): boolean;
459
- export declare function validatorReturnErrArray(...paramsToValidate: ValidatorObject[]): [string?, number?, object?];
460
- export declare function isEmpty(objOrArr: object | any[] | string | null | undefined): boolean;
461
- export declare function err422IfNotSet(o: any): void;
462
- export declare function getDateAsInt12(dateAllFormat?: Date | string | number, errIfNotValid?: any): string;
463
- export declare function humanReadableTimestamp(dateAllFormat: any): number;
464
- /** format for 6/8/2018 => 20180806
465
- * @param dateAllFormat multiple format allowed 2012, 20120101, 201201011200, new Date(), "2019-12-08T16:19:10.341Z" and all string that new Date() can parse
466
- */
467
- export declare function getDateAsInt(dateAllFormat?: Date | string | number, errIfNotValid$?: boolean, withHoursAndMinutes$?: boolean): string;
468
- export declare function getMonthAsInt(dateAllFormat?: Date | string | number): number;
469
- /**
470
- * @param dateAllFormat multiple format allowed 2012, 20120101, 201201011200, new Date(), "2019-12-08T16:19:10.341Z" and all string that new Date() can parse
471
- */
472
- export declare function getDateAsObject(dateAllFormat?: any, errIfNotValid$?: boolean): Date;
473
- export declare function isDateIntOrStringValid(dateStringOrInt: any, outputAnError?: boolean, length?: any): boolean;
474
- export declare function isDateIsoOrObjectValid(dateIsoOrObj: any, outputAnError?: boolean): boolean;
475
- /** [2018,01,06] */
476
- export declare function dateStringToArray(strOrInt: any): any[];
477
- /**
478
- * @param dateAllFormat default: actualDate
479
- * @returns ['01', '01', '2019'] OR **string** if separator is provided */
480
- export declare function dateArray(dateAllFormat?: Date | string | number): [string, string, string];
481
- /**
482
- * @param dateAllFormat default: actualDate
483
- * @returns ['01', '01', '2019'] OR **string** if separator is provided */
484
- export declare function dateArrayInt(dateAllFormat?: Date | string | number): [number, number, number];
485
- /**
486
- * @return 01/01/2012 (alias of dateArrayFormatted(date, '/'))
487
- */
488
- export declare function dateFormatted(dateAllFormat: Date | string | number, separator?: string): string;
489
- /** Date with custom offset (Ex: +2 for France) */
490
- export declare function dateOffset(offsetHours: any, dateObj?: Date): Date;
491
- /** */
492
- export declare function getTimeAsInt(timeOrDateInt?: any): number | "dateInvalid";
493
- /**
494
- * @param {timeInt|dateInt12} Eg: 2222 OR 201201012222. Default, actual dateInt12
495
- * @param {String} separator default: ":"
496
- */
497
- export declare function getIntAsTime(intOrDateTimeInt?: string, separator?: string): string;
498
- export declare function isTimeStringValid(timeStr: any, outputAnError$?: boolean): boolean;
499
- export declare function getDuration(startDate: any, endDate: any, inMinutes?: boolean): number | number[];
500
- /** compare two object with DATE INT, if they overlap return true
501
- * @param {Object} event1 {startDate, endDate}
502
- * @param {Object} event2 {startDate, endDate}
503
- * @param {String} fieldNameForStartDate$ replace startDate with this string
504
- * @param {String} fieldNameForEndDate$ replace endDate with this string
505
- * @param {Boolean} allowNull$ if false, retrun false if any of the startdates or enddates are not set
506
- * @param {Boolean} strict$ if true,
507
- */
508
- export declare function doDateOverlap(event1: any, event2: any, fieldNameForStartDate$?: string, fieldNameForEndDate$?: string, allowNull$?: boolean, strict$?: boolean): boolean;
509
- declare type DateAllFormat = DateObjectFormat | DateStringFormats;
510
- declare type DateStringFormats = 'dateInt8' | 'dateInt12' | 'humanReadableTimestamp';
511
- declare type DateObjectFormat = 'date';
512
- export declare function nextWeekDay(fromDate: any, weekDayInt?: 0 | 1 | 2 | 3 | 4 | 5 | 6, outputFormat?: DateStringFormats, sameDayAllowed?: boolean): number;
513
- export declare function nextWeekDay(fromDate: any, weekDayInt?: 0 | 1 | 2 | 3 | 4 | 5 | 6, outputFormat?: DateObjectFormat, sameDayAllowed?: boolean): Date;
514
- /**
515
- * @param {String} outputFormat dateInt, dateInt8, dateInt12, date, humanReadableTimestamp, int (dateInt8)
516
- */
517
- export declare function addDays(dateAllFormat?: Date | string | number, numberOfDays?: number, outputFormat?: 'dateInt8' | 'dateInt12' | 'humanReadableTimestamp'): string;
518
- export declare function addDays(dateAllFormat?: Date | string | number, numberOfDays?: number, outputFormat?: 'date'): Date;
519
- /**
520
- * @param {String} outputFormat dateInt, dateInt8, dateInt12, date, humanReadableTimestamp, int (dateInt8)
521
- */
522
- export declare function addMinutes(dateAllFormat?: Date | string | number, numberOfMinutes?: number, outputFormat?: DateStringFormats): string;
523
- export declare function addMinutes(dateAllFormat?: Date | string | number, numberOfMinutes?: number, outputFormat?: DateObjectFormat): Date;
524
- /**
525
- * @param {String} outputFormat dateInt, dateInt8, dateInt12, date, humanReadableTimestamp, int (dateInt8)
526
- */
527
- export declare function addHours(dateAllFormat?: Date | string | number, numberOfHours?: number, outputFormat?: 'dateInt8' | 'dateInt12' | 'humanReadableTimestamp'): string;
528
- export declare function addHours(dateAllFormat?: Date | string | number, numberOfHours?: number, outputFormat?: 'date'): Date;
529
- /**
530
- * @param {String} outputFormat dateInt, dateInt8, dateInt12, date, humanReadableTimestamp, int (dateInt8)
531
- */
532
- export declare function addMonths(dateAllFormat?: Date | string | number, numberOfMonths?: number, outputFormat?: 'dateInt8' | 'dateInt12' | 'humanReadableTimestamp'): string;
533
- export declare function addMonths(dateAllFormat?: Date | string | number, numberOfMonths?: number, outputFormat?: 'date'): Date;
534
- /**
535
- * @param {String} outputFormat dateInt, dateInt8, dateInt12, date, humanReadableTimestamp, int (dateInt8)
536
- */
537
- export declare function addYears(dateAllFormat?: Date | string | number, numberOfYears?: number, outputFormat?: DateAllFormat): Date;
538
- export declare function getDayOfMonth(dateAllFormat?: Date | string | number): any;
539
- export declare function getYear(dateAllFormat?: Date | string | number): any;
540
- export declare function getHours(dateAllFormat?: Date | string | number): any;
541
- export declare function getMinutes(dateAllFormat?: Date | string | number): any;
542
- /**
543
- * @param {String} outputFormat dateInt, dateInt8, dateInt12, date, humanReadableTimestamp, int (dateInt8)
544
- */
545
- export declare function lastDayOfMonth(dateAllFormat?: Date | string | number, outputFormat?: DateAllFormat): Date;
546
- /**
547
- * @param {String} outputFormat dateInt, dateInt8, dateInt12, date, humanReadableTimestamp, int (dateInt8)
548
- */
549
- export declare function firstDayOfMonth(dateAllFormat?: Date | string | number, outputFormat?: DateAllFormat): Date;
550
- export declare function differenceInMilliseconds(startDateAllFormat: any, endDateAllFormat: any): number;
551
- export declare function differenceInSeconds(startDateAllFormat: any, endDateAllFormat: any): number;
552
- export declare function differenceInMinutes(startDateAllFormat: any, endDateAllFormat: any): number;
553
- export declare function differenceInHours(startDateAllFormat: any, endDateAllFormat: any): number;
554
- export declare function differenceInDays(startDateAllFormat: any, endDateAllFormat: any): number;
555
- export declare function differenceInWeeks(startDateAllFormat: any, endDateAllFormat: any): number;
556
- /**
557
- * @param {String} outputDateFormat dateInt, dateInt8, dateInt12, date, humanReadableTimestamp, int (dateInt8)
558
- */
559
- export declare function getDateAs(dateAllFormat?: Date | string | number, outputFormat?: 'dateInt8' | 'dateInt12' | 'humanReadableTimestamp'): string;
560
- export declare function getDateAs(dateAllFormat?: Date | string | number, outputFormat?: 'date'): Date;
561
- export declare const logger: any;
562
- /**
563
- // console colored output
564
- // * console.log(C.green(C.dim('Hey bro !')))
565
- // * or C.log() // will use padding and color defined by themes
566
- // * or C.line('MY TITLE', 53)
567
- // * or C.gradientize(myLongString)
568
- */
569
- export declare const C: {
570
- dim: (str: any) => string;
571
- green: (str: any) => string;
572
- red: (str: any) => string;
573
- yellow: (str: any) => string;
574
- grey: (str: any) => string;
575
- magenta: (str: any) => string;
576
- cyan: (str: any) => string;
577
- blue: (str: any) => string;
578
- primary: (str: any) => string;
579
- reset: string;
580
- output: (code: any, str?: string) => string;
581
- rgb: (r: any, g?: number, b?: number) => string;
582
- bg: (r?: any, g?: any, b?: any) => string;
583
- /** Output a line of title */
584
- line(title?: string, length?: number, clr?: Color, char?: string, paddingX?: number): void;
585
- /** Eg: ['cell1', 'cell2', 'cell3'], [25, 15] will start cell2 at 25 and cell 3 at 25 + 15
586
- * @param {Array} limits default divide the viewport
587
- */
588
- cols(strings: any, limits?: any[], clr?: Color, paddingX?: number): void;
589
- /** Console log alias */
590
- log(...stringsCtxMayBeFirstParam: any[]): void;
591
- logClr(str: any, clr?: Color, paddingX?: number): void;
592
- info(...str: any[]): void;
593
- success(...str: any[]): void;
594
- /** First param **false** to avoid logging stack trace */
595
- error: (...errors: any[]) => any;
596
- /** First param **false** to avoid logging stack trace */
597
- warning: (...str: any[]) => any;
598
- customError: (color: any, ...str: any[]) => any;
599
- customWarning: (color: any, ...str: any[]) => any;
600
- applicationError: (color: any, ...str: any[]) => any;
601
- warningLight: (color: any, ...str: any[]) => any;
602
- dimStrSplit(...logs: any[]): string;
603
- notifShow(): void;
604
- /** Keep in memory the logs to show when needed with C.notifShow()
605
- * Ex: C.notification('info', str); */
606
- notification(type: any, ...messages: any[]): void;
607
- notifications: any[];
608
- /** Gratientize lines of text (separated by \n) */
609
- gradientize(str?: string, rgb1?: Color, rgb2?: Color, bgRgb?: Color, paddingY?: number, paddingX?: number): void;
610
- debugModeLog(title: any, ...string: any[]): void;
611
- useTheme(): void;
612
- };
613
- export declare function logErrPrivate(type: any, color: Color, ...errors: any[]): any;
614
- export declare function stringifyInstanceOfError(err: any, type?: string, color?: Color, level?: number): {
615
- str: string;
616
- stackTrace?: undefined;
617
- } | {
618
- str: string;
619
- stackTrace: any;
620
- };
621
- export declare function stringifyExtraInfos(extraInfoOriginal: any, type: any, color: any, level?: number): {
622
- str: string;
623
- stackTrace?: undefined;
624
- } | {
625
- str: string;
626
- stackTrace: any;
627
- };
628
- /**
629
- * Call this at each steps of your progress and change the step value
630
- * @param {Number} step Number of "char" to output
631
- * @param {String} char Default: '.'
632
- * @param {String} msg String before char. Final output will be `${str}${char.repeat(step)}`
633
- */
634
- export declare function cliProgressBar(step: any, char?: string, msg?: string): void;
635
- /** Remove accentued character from string and eventually special chars and numbers
636
- * @param {String} str input string
637
- * @param {Object} config { removeSpecialChars: false, removeNumbers: false, removeSpaces: false }
638
- * @returns String with all accentued char replaced by their non accentued version + config formattting
639
- */
640
- export declare function convertAccentedCharacters(str: any, config?: {
641
- removeNumbers?: boolean;
642
- removeSpecialChars?: boolean;
643
- removeSpaces?: boolean;
644
- }): any;
645
- /** Merge filter with correct handling of OR and AND
646
- * @param {Object} filterA
647
- * @param {Object} filterB
648
- * @param {Boolean} assignToFilterA defualt false: if true, it will modify filterA, else it will return merged filters as a new object
649
- */
650
- export declare function mongoFilterMerger(filterA: any, filterB: any, assignToFilterA?: boolean): any;
651
- export declare function mongoPush(field: string, value: any, fields: {
652
- [k: string]: any;
653
- }): void;
654
- export declare function timeout(ms: any, fn?: () => void): Promise<void>;
655
- export declare function runAsync(callback: any, milliseconds$?: number): Promise<void>;
656
- /**
657
- *
658
- * @param {Function} callback function that shall return ===true asynchronously
659
- * @param {Number} timeoutSec default:10; general timeout in seconds
660
- * @param {Boolean|String} errorAfterNSeconds default:true output an error in case of timeout, can be the displayed error message
661
- * @param {*} cliOutput write a cli progress to show that a process is running
662
- */
663
- export declare function waitUntilTrue(callback: any, timeoutSec?: number, errorAfterNSeconds?: boolean, cliOutput?: boolean): Promise<void>;
664
- /** Allow to perform an action in a delayed loop, useful for example to avoid reaching limits on servers. This function can be securely called multiple times.
665
- * @param {Function} callback
666
- * @param {Number} time default: 500ms;
667
- * @param {Function} errorCallback default: e => C.error(e)
668
- */
669
- export declare function executeInDelayedLoop(callback: any, time?: number, errorCallback?: (e: any) => any): Promise<void>;
670
- /** Allow to perform async functions in a defined order
671
- * This adds the callback to a queue and is resolved when ALL previous callbacks with same name are executed
672
- * Use it like: await transaction('nameOfTheFlow', async () => { ...myFunction })
673
- * @param {String|Function} name name for the actions that should never happen concurrently
674
- * @param {Function} asyncCallback
675
- * @param {Number} timeout default: 120000 (120s) will throw an error if transaction time is higher that this amount of ms
676
- * @returns {Promise}
677
- */
678
- export declare function transaction(name: any, asyncCallback: any, timeout?: number, doNotThrow?: boolean): Promise<unknown>;
679
- export declare function removeItemFromQueue(name: any): Promise<void>;
680
- /** Wait for a transaction to complete without creating a new transaction
681
- *
682
- */
683
- export declare function waitForTransaction(transactionName: any, forceReleaseInSeconds?: number): Promise<void>;
684
- export declare const int: typeof parseInt;
685
- export declare const average: typeof moyenne;
686
- export declare const arrayUniqueValue: typeof noDuplicateFilter;
687
- export declare const JSONstringyParse: (o: any) => any;
688
- export declare const removeUndefinedKeys: typeof objFilterUndefinedRecursive;
689
- export declare const randomizeArray: typeof shuffleArray;
690
- export declare const dashCase: typeof kebabCase;
691
- export declare const underscoreCase: typeof snakeCase;
692
- export declare const required: typeof validator;
693
- export declare const orIsset: typeof issetOr;
694
- export {};