-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
SvCoreLib.d.ts
1310 lines (1154 loc) · 61.9 KB
/
SvCoreLib.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
TypeScript Type Declaration file
Original declarations made by @canarado
>> If you came here looking for the source code, you're in the wrong file!
>> See the file `SvCoreLib.js` instead, it acts as a proxy to all of SCLs features.
>> From there, you can follow the file paths.
>> This file is responsible for the In-IDE documentation and explicit types (usually seen by pressing CTRL+Space or hovering over stuff)
*/
import { EventEmitter } from "events";
import { ServerResponse, IncomingMessage } from "http";
import { Connection, QueryOptions } from "mysql";
import { SelectionMenuSettings, SelectionMenuResult, SelectionMenuLocale, SelectionMenuOption } from "./src/types/SelectionMenu";
//#MARKER types
/**
* Describes an object that is JSON-compatible, aka doesn't contain self- / circular references or non-primitive JS properties
* [Source](https://github.com/microsoft/TypeScript/issues/1897#issuecomment-338650717)
*/
export type JSONCompatible = boolean | number | string | null | JSONArray | JSONMap;
interface JSONMap { [key: string]: JSONCompatible; }
interface JSONArray extends Array<JSONCompatible> {}
/** Describes a value that either is a string itself or has a `.toString()` method, meaning it can be converted to a string */
export type Stringifiable = string | {
toString(): string;
}
/** Describes any class reference that is constructable/newable */
export type Newable<T> = { new(...args: any[]): T; };
/** Describes any value that is a constructable/newable class reference or a function (ES5 classes and abstract ES6 classes) */
export type AnyClass<T> = Newable<T> | (Function & { prototype: T });
/**
* ![icon](https://sv443.net/resources/images/svcorelib_tiny.png)
*
* ### SvCoreLib
* Core Library used in the projects of Sv443 and the Sv443 Network. Contains tons of miscellaneous QoL features
*
* ---
*
* **[Documentation](https://github.com/Sv443-Network/SvCoreLib/blob/master/docs.md#readme) • [GitHub Repo](https://github.com/Sv443-Network/SvCoreLib) • [Changelog](https://github.com/Sv443-Network/SvCoreLib/blob/master/changelog.md#readme) • [Discord](https://dc.sv443.net)**
*
* ---
*
* If you like this library please consider [supporting me ❤](https://github.com/sponsors/Sv443)
* @author [Sv443](https://github.com/Sv443)
* @copyright © 2020 Sv443 Network
* @license [MIT](https://sv443.net/LICENSE)
* @module svcorelib
*/
declare module "svcorelib" {
//#MARKER functions
//#SECTION Miscellaneous
/**
* 🔹 Returns true, if the input is undefined, null, an empty string, an empty array or an object with length = 0.
* Otherwise returns false. The number 0 and NaN will return false though, so check them independently if needed! 🔹
* @param input Variable that should be checked - this can be of any type but the basic types will work best
* @returns true, if empty or false, if not
* @since 1.4.0
* @version 1.6.5 lowercase alias scl.isempty was removed
* @version 1.8.0 Added check for objects with length = 0
* @version 1.13.0 Fixed TypeError when input is `null`
*/
function isEmpty<T>(input: T): boolean;
/**
* 🔹 Checks how many values of the array are empty (does the same check as `scl.isEmpty()`, but on each array item) 🔹
* @param array Array that should be checked
* @returns true if all are empty, false if none are empty and number if only some are empty
* @throws Throws an error if the parameter isn't an array
* @since 1.5.0
* @version 1.8.0 Throwing error now instead of returning string
*/
function isArrayEmpty<T>(array: T[]): boolean | number;
/**
* 🔹 Checks if the passed value is a reference to a class 🔹
* @param val Value to check
* @since 1.17.0
*/
function isClass<T>(val: any): val is AnyClass<T>;
/**
* 🔹 Sends a red console message and optionally exits the process with an optional status code. 🔹
* @param cause The cause of the error
* @param log_file_path if the error message should automatically be logged to the file with the specified path. undefined or null to disable.
* @param shutdown if the process should be exited or not
* @param status with which status code the process should be exited
* @param consoleMsg whether to show a red message in the console or not
* @throws Throws an error if the "cause" parameter isn't a string
* @since 1.5.0
* @version 1.8.0 Throwing error now instead of logging to console and returning undefined
*/
function error(cause: string, log_file_path?: string, shutdown?: boolean, status?: number, consoleMsg?: boolean): void;
/**
* 🔹 Tests an array and returns true if all values are equal. 🔹
* @param array The array you want to test
* @param loose Set to `true` to use loose equality comparison instead of strict equality comparison. Defaults to `false`
* @returns true if all values are equal, false if not
* @throws Throws an error if the parameter is not an array
* @since 1.5.0
* @version 1.8.0 Throwing error now instead of returning string
*/
function allEqual<T>(array: T[], loose?: boolean): boolean;
type JSPrimitiveTypeName = "bigint" | "boolean" | "function" | "number" | "object" | "string" | "symbol" | "undefined";
/**
* 🔹 Tests if all items of an array are of the specified type. 🔹
* @param array The array you want to test
* @param type The type you want to test the array's items on
* @returns true if all items are of the specified type, false if not
* @throws Throws a TypeError if the first parameter is not an array or if the second parameter is not a valid primitive data type name
* @since 1.11.0
*/
function allOfType<T>(array: T[], type: JSPrimitiveTypeName): boolean;
/**
* 🔹 Checks if each item of an array is an instance of the passed class reference. 🔹
* @param array Array that should be checked
* @param Class Reference to the class to be checked. Don't pass an actual instance of that class!
* @returns Returns true if all items are an instance of `Class`, else returns false
* @throws Throws a TypeError if the parameters are invalid
* @since 1.17.0
*/
function allInstanceOf<T>(array: T[], Class: AnyClass<T>): boolean;
/**
* 🔹 Reserializes a JSON-compatible object. This means it copies the value of an object and loses the internal reference to it.
* Using an object that contains special JavaScript classes or circular objects will throw an error. 🔹
* @param obj The object you want to reserialize - if this is not of type `object`, you will just get the original value back
* @param immutable Set this to `true` if you want to make the returned object immutable (its properties can't be modified anymore)
* @returns Returns the reserialized object or the unmodified original value if it is not of type `object`
* @since 1.10.0
*/
function reserialize<O extends JSONCompatible, I extends boolean>(obj: O, immutable?: I): I extends true ? Readonly<O> : O;
/**
* 🔹 Splits an array into a certain amount of parts 🔹
* @param array The array to split
* @param partsAmt Into how many parts the array should be split
* @param balanced Default (false): returned parts all have the same length except the last one. (true): returned parts are equally balanced and have similar lengths.
* @since 1.18.0
*/
function splitIntoParts<T>(array: T[], partsAmt: number, balanced?: boolean): T[][];
/**
* 🔹 Splits an array into any number of parts with a max length. 🔹
* @param array The array to split
* @param maxLength The maximum length of each part. Has to be at least 1 or higher.
* @since 1.18.0
*/
function splitIntoPartsOfLength<T>(array: T[], maxLength: number): T[][];
type ParseDurationResult = Record<"days" | "hrs" | "mins" | "secs" | "ms", number>;
/**
* 🔹 Parses a duration in milliseconds into the larger units; days, hours, minutes, seconds and milliseconds 🔹
* @param millis The duration in milliseconds
* @throws Throws a TypeError if `millis` is not a number or less than 0
* @since 1.15.0
*/
function parseDuration(millis: number): ParseDurationResult;
/**
* 🔹 Formats a duration in milliseconds to a human-friendly string, according to a provided format 🔹
* @param millis The duration in milliseconds
* @param format The format of the duration. Use the following placeholders: `%d` for days, `%h` for hours, `%m` for minutes, `%s` for seconds and `%ms` for milliseconds
* @param leadingZeroes Whether to pad the numbers with leading zero(es). Defaults to true
* @throws Throws a TypeError if the parameters are invalid or `millis` is less than 0
* @since 1.15.0
*/
function formatDuration(millis: number, format: string, leadingZeroes?: boolean): string;
/**
* 🔹 Converts an array to a better readable one 🔹
* @param array The array you want to make readable
* @param separators The default separator for all values except the last one. Defaults to `, ` if left empty. Add whitespaces if needed!
* @param lastSeparator The last separator. Defaults to ` and ` if empty. Add whitespaces if needed!
* @returns Better readable array as string
* @since 1.7.0
*/
function readableArray(array: (string | Stringifiable)[], separators?: string, lastSeparator?: string): string;
/**
* 🔹 Transforms the `value` parameter, which is inside the numerical range [`range_1_min`-`range_1_max`] to where it would be on the numerical range [`range_2_min`-`range_2_max`] 🔹
* @param value The value from the first numerical range, that you want to transform to a value inside the second numerical range
* @param range_1_min lowest possible value of the **first** numerical range
* @param range_1_max highest possible value of the **first** numerical range
* @param range_2_min lowest possible value of the **second** numerical range
* @param range_2_max highest possible value of the **second** numerical range
* @returns Floating point number of `value` inside the second numerical range
* @throws Throws an error if the arguments are not of type `Number` or the `*_max` argument(s) is/are equal to 0
* @since 1.8.0
*/
function mapRange(value: number, range_1_min: number, range_1_max: number, range_2_min: number, range_2_max: number): number;
/**
* 🔹 Use this if you are using a linter that complains about unused vars.
* As this function basically does nothing, you can even leave it in once the variable is used again and nothing will break. 🔹
* @param variables Any amount of variable(s) of any type
* @since 1.8.0
* @version 1.9.0 Function now accepts an infinite number of parameters
*/
function unused(...variables: any): void;
/**
* 🔹 Replaces a character from the specified `string` at the specified `index` with the value of `replacement` 🔹
* @param input The input string
* @param index The zero-based index of the char you want to replace
* @param replacement What you want the char to be replaced with
* @since 1.8.0
*/
function replaceAt(input: string, index: number, replacement: string): string;
/**
* 🔹 Returns the length of a string in bytes.
* Passing anything other than a string will return `-1` 🔹
* @param str
* @since 1.10.0
*/
function byteLength(str: string): number;
/**
* 🔹 Returns both halves of an array as a tuple. 🔹
* @param array An array of any size, with any values contained inside
* @returns Returns a tuple with two array entries, being the first and second half of the array
* @since 1.15.0
* @example ```js
* const [first, second] = halves([ 1, 2, 3, 4, 5 ]);
*
* console.log(first); // [ 1, 2, 3 ]
* console.log(second); // [ 4, 5 ]
* ```
*/
function halves<T>(array: T[]): [first: T[], second: T[]];
/**
* 🔹 Inserts values into a percent-formatted string.
* If there are no insertion marks, this function returns the unmodified input string. 🔹
* @param str A string containing numbered insertion marks (%1, %2, ..., %10, %11, ...)
* @param values [Rest parameter] The values to insert into the string - All values that are not of type `string` will be attempted to be converted using their method `.toString()`
* @throws Throws a "TypeError" if the parameter `str` is not a string or if one of the values could not be converted to a string
* @since 1.12.0
*/
function insertValues(str: string, ...values: (string | Stringifiable)[]): string;
//#SECTION randomization
/**
* 🔹 Random number generator with upper and lower boundary. 🔹
*
* ❗ Warning! This RNG is not cryptographically secure, so don't do any password hashing or stuff that needs to be highly secure with this function!
* @param min Lower boundary of the RNG
* @param max Upper boundary of the RNG
* @throws Throws a TypeError if the arguments are not of type `number`
* @since 1.5.0
*/
function randRange(min: number, max: number): number;
/**
* 🔹 Random number generator with upper boundary.
* This overload automatically sets the lower boundary to 0. 🔹
*
* ❗ Warning! This RNG is not cryptographically secure, so don't do any password hashing or stuff that needs to be highly secure with this function!
* @param max Upper boundary of the RNG - using this overload will set the lower boundary to 0
* @throws Throws a TypeError if the arguments are not of type `number`
* @since 1.14.0
* @version 1.16.0 No longer depending on the `performance` module
*/
function randRange(max: number): number;
/**
* 🔹 Makes sure the provided `num` is always in between `min` and `max` 🔹
* @param num The number to clamp between `min` and `max`
* @param min Lower boundary
* @param max Upper boundary
* @throws Throws a TypeError if the parameters are not of type `number` or are NaN
* @since 1.16.0
*/
function clamp(num: number, min: number, max: number): number;
/**
* 🔹 Randomizes all items in an array and returns it 🔹
* @param array The array that should be randomized
* @returns Returns the randomized array
* @throws Throws an error if the parameter is not an array
* @since 1.8.0
*/
function randomizeArray<T>(array: T[]): T[];
/**
* 🔹 Chooses a random item in an array and returns it 🔹
* @param array An array of any size, with any values contained inside
* @returns Returns a random item of the provided array. **Returns undefined if the array is empty.**
* @since 1.9.4
*/
function randomItem<T>(array: T[]): T;
/**
* 🔹 Chooses a random item in an array and returns it, along with its index in the array. 🔹
* @param array An array of any size, with any values contained inside
* @returns Returns a tuple array with two entries. First entry is the randomly chosen item, second entry is the index of the random item. **Both entries are undefined if the array is empty.**
* @since 1.17.0
*/
function randomItemIndex<T>(array: T[]): [item: T, index: number];
/**
* 🔹 Chooses a random item in an array and returns it. Mutates the original array so the chosen item is no longer contained! 🔹
* @param array An array of any size, with any values contained inside
* @returns Returns the randomly chosen item. **Returns undefined if the array is empty.**
* @since 1.17.0
*/
function takeRandomItem<T>(array: T[]): T;
/**
* 🔹 Removes duplicate items in an array 🔹
* @param array An array with any values
* @since 1.9.0
*/
function removeDuplicates<T>(array: T[]): T[];
/**
* 🔸 Offers a few functions to generate seeded random numbers.
* This means using the same input seed, you will always get the same output number, just like you get the same Minecraft world when using the same seed twice. 🔸
*/
namespace seededRNG {
/**
* Represents a seed to be used in functions of the `seededRNG` namespace.
* Note that seeds can't start with the number `0` as they need to be compatible with both `string` and `number` types
*/
type Seed = (number | string);
/**
* Describes a set of numbers generated or needed by functions of the `seededRNG` namespace
*/
interface SeededRandomNumbers
{
[key: string]: number[] | string | number;
/** An array of the random numbers */
numbers: number[];
/** The random numbers, but as a string */
stringified: string;
/** The random numbers, but as an integer */
integer: number;
/** The seed that was used to create the random numbers */
seed: number;
}
/**
* 🔹 Generates random numbers from the numerical range [0-9] based on a seed.
* To make sure the seed is valid, you can use the function `validateSeed()`. 🔹
* @param count How many random numbers should be generated - will default to 16 if left empty
* @param seed The seed to generate numbers from. Leave empty to use a random default seed. The used seed will be included in the returned object
* @returns An object containing the seed and the random number in three different formats
* @since 1.8.0
*/
function generateNumbers(count?: number, seed?: Seed): SeededRandomNumbers;
/**
* 🔹 Creates a random seed 🔹
* @param digitCount How many digits the seed should have - defaults to 10 if left empty
* @since 1.8.0
*/
function randomSeed(digitCount?: number): number;
/**
* 🔹 Validates a seed to be used in `generateSeededNumbers()` 🔹
* @param seed The seed to validate - accepts string or number (also accepts octal and hexadecimal notation)
* @since 1.8.0
*/
function validateSeed(seed: Seed): boolean;
}
/**
* 🔸 Offers many functions to generate Universally Unique Identifiers (UUIDs) 🔸
*/
namespace uuid {
/**
* 🔹 Creates an alphanumerical [0-9,A-Z] UUID with a given format. This uses a RNG that is even more random than the standard Math.random() 🔹
* @param uuidFormat The format of the UUID. All x's and y's will be affected by the RNG. Example: "xxxx-yyyy-xxxx-yyyy" - if you want an x or y to not be replaced, escape (prefix) it with this character: `^`
* @param upperCase Set to true to have all letters in upper case, false for lower case
* @since 1.8.0
*/
function alphanumerical(uuidFormat: string, upperCase?: boolean): string;
/**
* 🔹 Creates a binary [0-1] UUID with a given format. This uses a RNG that is even more random than the standard Math.random() 🔹
* @param uuidFormat The format of the UUID. All x's and y's will be affected by the RNG. Example: "xxxx-yyyy-xxxx-yyyy" - if you want an x or y to not be replaced, escape (prefix) it with this character: `^`
* @param asBooleanArray Set to true to get an array of booleans instead of a string of 1 and 0. Setting this to true will ignore the uuidFormat parameter. Instead, the amount of x's and y's will be equivalent to the resulting array items.
* @since 1.8.0
*/
function binary(uuidFormat: string, asBooleanArray?: boolean): string | boolean[];
/**
* ❌ Warning: This overload is deprecated! Please use the other one. ❌
*
* 🔹 Creates a custom UUID with a given format from a list of characters specified by the possibleValues parameter. This uses a RNG that is even more random than the standard Math.random() 🔹
* @param uuidFormat The format of the UUID. All x's and y's will be affected by the RNG. Example: "xxxx-yyyy-xxxx-yyyy" - if you want an x or y to not be replaced, escape (prefix) it with this character: `^`
* @param possibleValues A string containing all characters that can be injected into the final UUID - (delimited by nothing) - Example: "ABCDEF01234$%&#"
* @since 1.8.0
* @deprecated
*/
function custom(uuidFormat: string, possibleValues: string): string;
/**
* 🔹 Creates a custom UUID with a given format from a list of characters specified by the possibleValues parameter. This uses a RNG that is even more random than the standard Math.random() 🔹
* @param uuidFormat The format of the UUID. All x's and y's will be affected by the RNG. Example: "xxxx-yyyy-xxxx-yyyy" - if you want an x or y to not be replaced, escape (prefix) it with this character: `^`
* @param possibleValues An array containing all characters that can be injected into the final UUID
* @since 1.14.0
*/
function custom(uuidFormat: string, possibleValues: (string | Stringifiable)[]): string;
/**
* 🔹 Creates a decimal [0-9] UUID with a given format. This uses a RNG that is even more random than the standard Math.random() 🔹
* @param uuidFormat The format of the UUID. All x's and y's will be affected by the RNG. Example: "xxxx-yyyy-xxxx-yyyy" - if you want an x or y to not be replaced, escape (prefix) it with this character: `^`
* @since 1.8.0
*/
function decimal(uuidFormat: string): string;
/**
* 🔹 Creates a hexadecimal [0-9,A-F] UUID with a given format. This uses a RNG that is even more random than the standard Math.random() 🔹
* @param uuidFormat The format of the UUID. All x's and y's will be affected by the RNG. Example: "xxxx-yyyy-xxxx-yyyy" - if you want an x or y to not be replaced, escape (prefix) it with this character: `^`
* @param upperCase Set to true to have all letters in upper case, false for lower case
* @since 1.5.0
* @version 1.8.0 Renamed the function and moved it
*/
function hexadecimal(uuidFormat: string, upperCase?: boolean): string;
}
//#SECTION http
/**
* 🔸 Offers a few functions that work in conjunction with Node's builtin `http` and `https` modules 🔸
*/
namespace http {
/**
* An encoding's identifier / name
*/
type EncodingName = "br" | "gzip" | "deflate" | "compress" | "identity";
/**
* 🔹 Pipes a file into a HTTP response. This is a tiny bit faster and much more efficient than loading the file into RAM first. 🔹
* @param res The HTTP res object
* @param filePath Path to the file to respond with - relative to the project root directory
* @param mimeType The MIME type to respond with - defaults to "text/plain" if left empty
* @param statusCode The status code to respond with - defaults to 200
* @returns Returns `null` if there was no error or a string containing the error message
* @throws Throws an "InvalidMimeTypeError" if the provided "mimeType" parameter is not a valid MIME type
*/
function pipeFile(res: ServerResponse, filePath: string, mimeType?: string, statusCode?: number): null | string;
/**
* 🔹 Pipes a string into a HTTP response. This is a tiny bit faster and much more efficient than loading the string into RAM first. 🔹
* @param res The HTTP res object
* @param text The response body
* @param mimeType The MIME type to respond with - defaults to "text/plain" if left empty
* @param statusCode The status code to respond with - defaults to 200
* @returns Returns `null` if there was no error or a string containing the error message
* @throws Throws an "InvalidMimeTypeError" if the provided "mimeType" parameter is not a valid MIME type
*/
function pipeString(res: ServerResponse, text: string, mimeType?: string, statusCode?: number): null | string;
/**
* 🔹 Returns the name of the client's accepted encoding.
* If the client supports multiple encodings, returns the most efficient and modern encoding.
* For more information, visit the [MDN documentation page](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding) 🔹
* @param req The HTTP `req` object
* @returns Returns "identity" if no encodings are supported, else returns the encoding's name
* @since 1.10.0
*/
function getClientEncoding(req: IncomingMessage): EncodingName;
/**
* This object contains the return values of a ping
*/
interface PingReturnValues
{
[key: string]: number | string;
/** The ping's returned status code (eg. 200 or 404) */
statusCode: number;
/** The status message of the ping - Could be something like "Ok" for status 200 or "Not Found" for status 404 */
statusMessage: string;
/** The response time in milliseconds as an integer */
responseTime: number;
/** The `content-type` header - this will contain the MIME type and the content encoding */
contentType: string;
}
/**
* 🔹 Pings the specified URL and returns the status code 🔹
* @param url The URL that should be pinged
* @param timeout time in milliseconds after which the ping will time out and return a 404 error - defaults to 5000 ms
* @returns Promise gets passed the HTTP status code (for example 200 or 404), the status message and the response duration in ms; if errored returns a string with the error message
* @throws Throws an error if the `url` parameter is not present or malformatted
* @since 1.6.0
* @version 1.6.1 changed attributes
* @version 1.6.5 changed time measurement dependency due to deprecation
* @version 1.6.6 updated documentation for the resulting object
* @version 1.8.0 changed time measurement method to be a much more accurate one
*/
function ping(url: string, timeout?: number): Promise<PingReturnValues>;
}
//#SECTION file system
/**
* 🔸 Offers a few functions to interface with the file system 🔸
*/
namespace files {
interface LoggerOptions
{
[key: string]: boolean;
/** Set to true to append content to the bottom of a file, false to just override the file's contents */
append_bottom: boolean;
/** Set to true to add a timestamp to the logged content */
timestamp: boolean;
}
/**
* 🔹 Logs a string to a specified log file 🔹
* @param path Relative path to the log file
* @param content Content that should be written to the log file
* @param options Additional options
* @throws Throws an error if the parameters are of the wrong type or not present
* @since 1.5.0
*/
function logger(path: string, content: string, options?: Partial<LoggerOptions>): void;
/**
* 🔹 Reads a folder asynchronously and recursively and returns all absolute file paths (starting at the drive letter (eg. "C:/Users/...")) in the callback - Warning! Large amounts of files (like letting it run on "C:/") can freeze the process completely or exceed the maximum possible index of a JS array 🔹
* @param folder The folder that should be recursively read
* @param callback The function that gets called after the folder has been read - has two arguments: error and result - you can also use the returned promise as a callback
* @returns Returns a Promise - resolution gets passed the result, rejection gets passed an error message
* @since 1.7.0
* @version 1.9.2 Now this function also supports the Promise API
*/
function readdirRecursive(folder: string, callback?: (result: string[]) => void): Promise<string[]>;
/**
* 🔹 Reads a folder synchronously and recursively and returns all absolute file paths (starting at the drive letter (eg. "C:/Users/...")) in the callback 🔹
*
* ❗ This function uses blocking operations, contrary to the async `fs.ensureDirs()`, so it is recommended to use the async one if possible.
* @param folder The folder that should be recursively read
* @returns an array of strings containing absolute paths to all found files
* @since 1.7.0
* @version 1.8.0 Now the paths are being resolved as absolute, not relative + fixed JSDoc return type
*/
function readdirRecursiveSync(folder: string): string[];
/**
* 🔹 This function checks if a file exists at the given path.
* (Reimplementation of the deprecated [`fs.exists()`](https://nodejs.org/api/fs.html#fs_fs_exists_path_callback)) 🔹
* @param path The path to the file - Gets passed through [`path.resolve()`](https://nodejs.org/api/path.html#path_path_resolve_paths)
* @returns Returned Promise always resolves to a boolean (and never rejects) - true, if the file exists, false if not
* @since 1.13.0
* @version 1.15.0 Now using [`fs-extra`](https://npmjs.com/package/fs-extra)'s `pathExists()`
*/
function exists(path: string): Promise<boolean>;
/**
* 🔹 Synchronously checks if a file exists at the given path.
* (Reimplementation of the deprecated [`fs.exists()`](https://nodejs.org/api/fs.html#fs_fs_exists_path_callback)) 🔹
*
* ❗ This function uses blocking operations, contrary to the async `fs.ensureDirs()`, so it is recommended to use the async one if possible.
* @param path The path to the file - Gets passed through [`path.resolve()`](https://nodejs.org/api/path.html#path_path_resolve_paths)
* @returns Returned Promise always resolves to a boolean (and never rejects) - true, if the file exists, false if not
* @since 1.13.0
* @version 1.15.0 Now using [`fs-extra`](https://npmjs.com/package/fs-extra)'s `pathExists()`
*/
function existsSync(path: string): Promise<boolean>;
/**
* 🔹 Ensures that a set of directories exist and creates them if not. 🔹
* @param directories The directories to ensure the existance of
* @throws Throws a TypeError if the `directories` parameter is not an array of strings
* @since 1.13.0
*/
function ensureDirs(directories: string[]): Promise<void>;
/**
* 🔹 Synchronously ensures that a set of directories exist and creates them if not. 🔹
*
* ❗ This function uses blocking operations, contrary to the async `fs.ensureDirs()`, so it is recommended to use the async one if possible.
* @param directories The directories to ensure the existance of
* @throws Throws a TypeError if the `directories` parameter is not an array of strings
* @since 1.13.0
*/
function ensureDirsSync(directories: string[]): void;
interface DownloadProgress
{
[key: string]: number;
/** The current download progress in bytes */
currentB: number;
/** The current download progress in kilobytes */
currentKB: number;
/** The current download progress in megabytes */
currentMB: number;
/** The total file size in bytes */
totalB: number;
/** The total file size in kilobytes */
totalKB: number;
/** The total file size in megabytes */
totalMB: number;
}
interface DownloadOptions
{
/** The name that the downloaded file should be saved as, including the file extension - for example: "image.png" or "archive.zip" - defaults to "download.txt" */
fileName?: string;
/** A callback function that gets called every 50 milliseconds that gets passed an object containing info on the download progress - sometimes the download progress can't be gotten so this callback won't contain the total size or will not be called a final time on finish. This behavior is normal. */
progressCallback?: (progress: DownloadProgress) => void;
/** A callback function that gets called when the download finished and gets passed a parameter that is `null` if no error was encountered, or contains a string if an error was encountered */
finishedCallback?: (error: (null | string)) => void;
}
/**
* 🔹 Downloads a file from the specified URL, to the specified destination path, according to the specified options 🔹
* @param url The URL to the file you want to download
* @param destPath The path where the file should be saved to - can be absolute or relative - If left empty, it will default to the root directory of the project - **❗ Do not include the file name here - set it in the `options` parameter ❗**
* @param options
* @returns Promise that resolves to a void value and rejects to an error string
* @since 1.8.0
* @version 1.9.2 Added the option of using the Promise API instead of a callback
*/
function downloadFile(url: string, destPath?: string, options?: DownloadOptions): Promise<void | string>;
}
//#SECTION SQL
/**
* 🔸 Offers functions to interface with a SQL database 🔸
*/
namespace sql {
/**
* 🔹 Sends a formatted (SQLI-protected) query 🔹
* @param connection An SQL connection instantiated with [`mysql.createConnection()`](https://www.npmjs.com/package/mysql#establishing-connections)
* @param query The SQL query with question marks where the inserted values should be
* @param options The options of this query. [Here are the possible properties](https://www.npmjs.com/package/mysql#connection-options) - leave undefined to choose the default options
* @param insertValues [Rest parameter] The values to be inserted into the question marks
* @since 1.12.0
*/
function sendQuery(connection: Connection, query: string, options?: QueryOptions, ...insertValues: (null | string | number)[]): Promise<object>;
}
//#SECTION System
/**
* 🔸 Offers few functions that refer to the system the process is executed on 🔸
*/
namespace system {
/**
* 🔹 Returns the percentage of heap space that is used by the process 🔹
* @returns Returns a floating point number between 0 and 100
* @since 1.13.0
*/
function usedHeap(): number;
/**
* 🔹 Executes a synchronous function or promise before the process gets shut down (on SIGINT or SIGTERM).
* This can be used to close files, abort connections or just to print a console message before shutdown. 🔹
*
* - ❗ If `scl.noShutdown()` was used, the passed function will be executed, but the process will not exit
* - ❗ Due to how the Promise API works, you will need to call this function again if the passed Promise is rejected
* @param funct This function or Promise will get executed before process shutdown. Rejecting the Promise will prevent a shutdown.
* @param code The exit code with which the process should be closed. Defaults to 0
* @since 1.5.0
* @version 1.8.0 Added "code" parameter to specify an exit code
* @version 1.9.0 Function will now still be called when `scl.noShutdown()` was used
* @version 1.9.4 Removed signal SIGKILL because it caused crashes on Linux
* @version 1.13.0 Moved namespace
* @version 1.14.0 Added support for the Promise API
*/
function softShutdown(funct: (() => void | Promise<void>), code?: number): void;
/**
* 🔹 Prevents the script from shutting down with default commands (CTRL + C).
* It has to either be killed with the task manager or internally, through the script (using `process.exit()`) 🔹
* @since 1.5.0
* @version 1.13.0 Moved namespace
*/
function noShutdown(): void;
/**
* 🔹 Removes the script shut down prevention that was previously enabled with noShutdown() 🔹
* (Sorry for the name, I saw an opportunity and I took it, don't judge me)
* @since 1.6.0
* @version 1.13.0 Moved namespace
*/
function yesShutdown(): void;
/**
* 🔹 Checks if the process is currently running in the debugger environment.
* This can be useful because some features like child processes and reading from stdin do not work in certain debuggers. 🔹
* ❗ This function should support all major debuggers but this isn't guaranteed!
* If it doesn't detect your debugger, pass the command line argument `--debug` or `--inspect` ❗
* @param checkArg If provided, checks if this command line argument is present. Makes the function return `true` if it is.
* @returns true, if the process is currently running in a debugger, false if not.
* @since 1.9.0
* @version 1.13.0 Moved namespace
* @version 1.14.2 Added `inspector.url()` check for better results & added `checkArg` argument
*/
function inDebugger(checkArg?: string): boolean;
/**
* 🔹 Sets the terminal window's title. Supports both Windows and *nix. 🔹
* @param title The string to set the window title to
* @throws Throws a "TypeError" if the parameter `title` is not a string or couldn't be converted to one
* @since 1.12.0
* @version 1.13.0 Moved namespace
*/
function setWindowTitle(title: string | Stringifiable): void;
/**
* 🔹 Waits for the user to press a key and then resolves a Promise 🔹
* @param text The text to display - if left empty this defaults to "Press any key to continue..."
* @returns Passes the pressed key in the resolution or the error message in the rejection
* @since 1.9.0
* @version 1.9.3 Events are now being correctly unregistered
*/
function pause(text?: string): Promise<string>;
}
//#MARKER classes
//#SECTION ProgressBar
/**
* 🔹 Creates a dynamic progress bar in the CLI 🔹
*
* **Make sure to use the keyword `new` to create an object of this class, don't just use it like this!**
*
* Example:
* ![ProgressBar example image](https://sv443.net/cdn/jsl/doc/progress_bar_small.png)
*/
class ProgressBar {
/** The character to use for filled parts of the progress bar */
public filledChar: string;
/** The character to use for blank / empty parts of the progress bar */
public blankChar: string;
/**
* 🔹 Creates a dynamic progress bar with a percentage and custom message display 🔹
*
* ![ProgressBar example image](https://sv443.net/cdn/jsl/doc/progress_bar_small.png)
* @param timesToUpdate How many times you will call ProgressBar.next() in total - example: 4 means you will need to call ProgressBar.next() exactly four times to reach 100% progress
* @param initialMessage Initial message that appears at 0% progress - omit parameter to not have an initial message
* @constructor
* @since 1.7.0
*/
constructor(timesToUpdate: number, initialMessage?: string);
/**
* 🔹 Increment the progress bar. The amount of these functions should be known at the point of initially creating the ProgressBar object. 🔹
* @param message Message that should be displayed
* @since 1.7.0
*/
next(message?: string): void;
/**
* 🔹 Executes a function once the progress reaches 100% 🔹
* @param {function} [callback] Function to be called when the progress bar reaches 100%
* @returns {Promise} Promise that gets resolved when the progress bar reaches 100%
* @throws Throws an error if the "callback" argument is not a function
* @since 1.7.0
* @version 1.12.0 Method now also returns a Promise
*/
onFinish(callback: () => void): Promise<void>;
/**
* 🔹 Get the current progress as a float value (between `0.0` and `1.0`) 🔹
* @since 1.7.0
*/
getProgress(): number;
/**
* 🔹 Get the amount of increments that are still needed to reach 100% progress aka how many times the `next()` method still needs to be called 🔹
* @returns {Number}
* @since 1.7.0
*/
getRemainingIncrements(): number;
}
//#SECTION MenuPrompt
/** An option of a menu of the menu prompt */
interface MenuPromptMenuOption
{
[key: string]: string;
/** The key(s) that need(s) to be pressed to select this option */
key: string;
/** The description of this option */
description: string;
}
/** A single menu of the menu prompt */
interface MenuPromptMenu
{
[key: string]: string | MenuPromptMenuOption[];
/** The title of this menu */
title: string;
/** An array of options for this menu */
options: MenuPromptMenuOption[];
}
/** The result of a single menu of a menu prompt. This object is usually present inside an array. */
interface MenuPromptResult
{
[key: string]: string | number;
/** The key that had to be pressed to select this option */
key: string;
/** The description of the selected option */
description: string;
/** The title of the menu */
menuTitle: string;
/** The zero-based index of the selected option */
optionIndex: number;
/** The zero-based index of the menu */
menuIndex: number;
}
/** A callback that gets executed once the MenuPrompt has finished */
interface MenuPromptOnFinishedCallback
{
[key: string]: MenuPromptResult[];
/** The results of the MenuPrompt (an array containing objects) - will be an empty array if there aren't any results */
results: MenuPromptResult[];
}
/** The options of the menu prompt */
interface MenuPromptOptions
{
[key: string]: string | boolean | MenuPromptOnFinishedCallback;
/** The key or keys that need to be entered to exit the prompt */
exitKey: string;
/** The separator character(s) between the option key and the option description */
optionSeparator: string;
/** Character(s) that should be prefixed to the cursor. Will default to this arrow: "─►" */
cursorPrefix: string;
/** Whether the menu should be retried if the user entered a wrong option - if false, continues to next menu */
retryOnInvalid: boolean;
/** A function that gets called when the user is done with all of the menus of the prompt or entered the exit key(s). The only passed parameter is an array containing all selected option keys */
onFinished: MenuPromptOnFinishedCallback;
/** If set to true, the MenuPrompt will only accept a single character of input and will then automatically submit the value. If set to false, the user will have to explicitly press the Enter key to submit a value */
autoSubmit: boolean;
}
/** Used for translating a menu prompt */
interface MenuPromptLocalization
{
[key: string]: string;
/** The text that's displayed when a wrong key was pressed */
wrongOption: string;
/** A different text that's displayed when a wrong key was pressed */
invalidOptionSelected: string;
/** The name of the exit option */
exitOptionText: string;
}
/**
* 🔹 Creates an interactive prompt in the CLI with one or more menus. 🔹
*
* **Make sure to use the keyword `new` to create an object of this class, don't just use it like this!**
*
* Example:
* ![MenuPrompt example image](https://sv443.net/cdn/jsl/doc/menu_prompt_small.png)
*/
class MenuPrompt {
/** This is where all texts of the MenuPrompt are stored. Use this to translate or change them. */
public localization: MenuPromptLocalization;
/**
* 🔹 Creates an interactive prompt with one or many menus - add them using `MenuPrompt.addMenu()`.
* To translate the messages, you can use the `MenuPrompt.localization` object, which is where all localization variables are stored. 🔹
* ❗ Warning: After creating a MenuPrompt object, the process will no longer exit automatically until the MenuPrompt has finished or was explicitly closed. You have to explicitly use process.exit() until the menu has finished or is closed
*
* ![MenuPrompt example image](https://sv443.net/cdn/jsl/doc/menu_prompt_small.png)
* @param options The options for the prompt
* @constructor
* @since 1.8.0
* @version 1.8.2 Removed second parameter - use `MenuPrompt.addMenu()` instead
* @version 1.9.0 The construction of a MenuPrompt object will now set the process.stdin raw mode to true + There is now a `localization` property you can use to translate some messages
*/
constructor(options?: Partial<MenuPromptOptions>);
/**
* 🔹 Opens the menu 🔹
* ❗ Warning: While the menu is opened you shouldn't write anything to the console / to the stdout and stderr as this could mess up the layout of the menu and/or make stuff unreadable
* @returns Returns true, if the menu could be opened or a string containing an error message, if not
* @since 1.8.0
*/
open(): boolean | string;
/**
* 🔹 Closes the menu prompt and returns the selected options up to this point 🔹
* @returns Returns the results of the menu prompt as an array of objects
* @since 1.8.0
*/
close(): MenuPromptResult[];
/**
* 🔹 Adds a new menu to the menu prompt.
* You can even add new menus while the MenuPrompt is already open. 🔹
* @param menu The menu to add to the menu prompt
* @returns Returns true, if the menu could be added or a string containing an error message, if not
* @since 1.8.0
*/
addMenu(menu: MenuPromptMenu): boolean | string;
/**
* 🔹 Returns the (zero-based) index of the current menu of the menu prompt 🔹
* @returns The zero-based index of the current menu or `-1` if the menu hasn't been opened yet
* @since 1.8.0
*/
currentMenu(): number;
/**
* 🔹 Returns the current results of the menu prompt.
* This does **not** close the menu prompt, unlike `close()` 🔹
* @returns Returns the results of the menu prompt or null, if there aren't any results yet
* @since 1.8.0
*/
result(): MenuPromptResult[] | null;
/**
* 🔹 Checks a menu for valid syntax 🔹
* @param menu The menu that should be validated
* @returns Returns true if the menu is valid, a string array containing the error messages if not
* @throws Throws an error if a falsy parameter or no parameter at all was passed
*/
validateMenu(menu: MenuPromptMenu): boolean | string[];
}
//#SECTION FolderDaemon
/** The options of the FolderDaemon */
interface FolderDaemonOptions
{
[key: string]: string[] | undefined | boolean | number;
/**
* An array of [glob patterns.](https://en.wikipedia.org/wiki/Glob_(programming)) Only the matched files will be supervised by the FolderDaemon.
* Example: `['*.js']` will make the daemon only scan files that end in `.js`.
* ❗ You can only use *either* a whitelist *or* a blacklist, not both!
*/
whitelist?: string[] | undefined;
/**
* An array of [glob patterns.](https://en.wikipedia.org/wiki/Glob_(programming)) The matched files will be ignored by the FolderDaemon.
* Example: `['*.js']` will block all .js files from being scanned by the daemon.
* ❗ You can only use *either* a blacklist *or* a whitelist, not both!
*/
blacklist?: string[] | undefined;
/** Whether to recursively scan through all subdirectories to supervise files. Defaults to `false` */
recursive?: boolean;
/** The interval in milliseconds at which to check if files have been changed. Defaults to 500. */
updateInterval?: number;
}
/**
* 🔹 Supervises a directory (and optionally its subdirectories) and executes a callback function if one or more of the files have changed. 🔹
*
* **Make sure to use the keyword `new` to create an object of this class, don't just use it like this!**
*/
class FolderDaemon {
/**
* 🔹 Constructs a new object of class FolderDaemon.
* The FolderDaemon supervises a directory and listens for changes in the files and then it executes a callback function that is registered with the method `onChanged()`. 🔹
* @param dirPath The path to the directory you want the daemon to supervise
* @param options Options of the FolderDaemon
*
* @throws Throws an `InvalidPathError` if the path to the directory is invalid
* @throws Throws a `NotAFolderError` if the path leads to a file instead of a directory
* @throws Throws a `PatternInvalidError` if the whitelist or blacklist glob pattern is invalid
* @throws Throws a `TypeError` if both the `whitelist` and `blacklist` properties are set in the `options` object
*
* @since 1.10.0
* @version 1.13.0 Condensed parameters into options object + added whitelist option