@keeex/utils 7.0.1

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 (183) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +105 -0
  3. package/lib/array.d.ts +28 -0
  4. package/lib/array.js +36 -0
  5. package/lib/arraybuffer.d.ts +138 -0
  6. package/lib/arraybuffer.js +141 -0
  7. package/lib/async/asynctrigger.d.ts +50 -0
  8. package/lib/async/asynctrigger.js +108 -0
  9. package/lib/async/deferredpromise.d.ts +32 -0
  10. package/lib/async/deferredpromise.js +66 -0
  11. package/lib/async/keycache.d.ts +56 -0
  12. package/lib/async/keycache.js +103 -0
  13. package/lib/async/queues.d.ts +69 -0
  14. package/lib/async/queues.js +135 -0
  15. package/lib/async/timecache.d.ts +58 -0
  16. package/lib/async/timecache.js +118 -0
  17. package/lib/base58.d.ts +27 -0
  18. package/lib/base58.js +83 -0
  19. package/lib/base64.d.ts +51 -0
  20. package/lib/base64.js +126 -0
  21. package/lib/benchmark.d.ts +126 -0
  22. package/lib/benchmark.js +177 -0
  23. package/lib/bits/arraybuffer.d.ts +35 -0
  24. package/lib/bits/arraybuffer.js +64 -0
  25. package/lib/bits/base64.d.ts +35 -0
  26. package/lib/bits/base64.js +70 -0
  27. package/lib/bits/hex.d.ts +17 -0
  28. package/lib/bits/hex.js +30 -0
  29. package/lib/bits/uint8array.d.ts +28 -0
  30. package/lib/bits/uint8array.js +42 -0
  31. package/lib/bytebuffer.d.ts +27 -0
  32. package/lib/bytebuffer.js +29 -0
  33. package/lib/consts.d.ts +33 -0
  34. package/lib/consts.js +33 -0
  35. package/lib/cron/logger.d.ts +22 -0
  36. package/lib/cron/logger.js +31 -0
  37. package/lib/cron/scheduledtask.d.ts +71 -0
  38. package/lib/cron/scheduledtask.js +137 -0
  39. package/lib/cron/types.d.ts +53 -0
  40. package/lib/cron/types.js +31 -0
  41. package/lib/cron.d.ts +29 -0
  42. package/lib/cron.js +47 -0
  43. package/lib/dict.d.ts +56 -0
  44. package/lib/dict.js +74 -0
  45. package/lib/error.d.ts +25 -0
  46. package/lib/error.js +41 -0
  47. package/lib/global.d.ts +27 -0
  48. package/lib/global.js +53 -0
  49. package/lib/hex.d.ts +32 -0
  50. package/lib/hex.js +58 -0
  51. package/lib/idx.d.ts +51 -0
  52. package/lib/idx.js +81 -0
  53. package/lib/json.d.ts +57 -0
  54. package/lib/json.js +116 -0
  55. package/lib/marshalling/marshaller.d.ts +51 -0
  56. package/lib/marshalling/marshaller.js +155 -0
  57. package/lib/marshalling/unmarshaller.d.ts +53 -0
  58. package/lib/marshalling/unmarshaller.js +124 -0
  59. package/lib/marshalling/util.d.ts +25 -0
  60. package/lib/marshalling/util.js +25 -0
  61. package/lib/number.d.ts +17 -0
  62. package/lib/number.js +21 -0
  63. package/lib/path.d.ts +25 -0
  64. package/lib/path.js +29 -0
  65. package/lib/promise.d.ts +42 -0
  66. package/lib/promise.js +78 -0
  67. package/lib/starttime.d.ts +23 -0
  68. package/lib/starttime.js +29 -0
  69. package/lib/string.d.ts +65 -0
  70. package/lib/string.js +108 -0
  71. package/lib/types/array.d.ts +34 -0
  72. package/lib/types/array.js +64 -0
  73. package/lib/types/enum.d.ts +30 -0
  74. package/lib/types/enum.js +44 -0
  75. package/lib/types/predicateerror.d.ts +40 -0
  76. package/lib/types/predicateerror.js +107 -0
  77. package/lib/types/primitive.d.ts +23 -0
  78. package/lib/types/primitive.js +34 -0
  79. package/lib/types/record.d.ts +67 -0
  80. package/lib/types/record.js +235 -0
  81. package/lib/types/types.d.ts +64 -0
  82. package/lib/types/types.js +115 -0
  83. package/lib/types/utils.d.ts +18 -0
  84. package/lib/types/utils.js +67 -0
  85. package/lib/uint8array.d.ts +176 -0
  86. package/lib/uint8array.js +438 -0
  87. package/lib/units.d.ts +159 -0
  88. package/lib/units.js +290 -0
  89. package/lib/utils/buffer.d.ts +49 -0
  90. package/lib/utils/buffer.js +79 -0
  91. package/lib/utils/fourbytes.d.ts +29 -0
  92. package/lib/utils/fourbytes.js +45 -0
  93. package/package.json +1 -0
  94. package/web/array.d.ts +28 -0
  95. package/web/array.js +34 -0
  96. package/web/arraybuffer.d.ts +138 -0
  97. package/web/arraybuffer.js +141 -0
  98. package/web/async/asynctrigger.d.ts +50 -0
  99. package/web/async/asynctrigger.js +106 -0
  100. package/web/async/deferredpromise.d.ts +32 -0
  101. package/web/async/deferredpromise.js +65 -0
  102. package/web/async/keycache.d.ts +56 -0
  103. package/web/async/keycache.js +97 -0
  104. package/web/async/queues.d.ts +69 -0
  105. package/web/async/queues.js +131 -0
  106. package/web/async/timecache.d.ts +58 -0
  107. package/web/async/timecache.js +107 -0
  108. package/web/base58.d.ts +27 -0
  109. package/web/base58.js +78 -0
  110. package/web/base64.d.ts +51 -0
  111. package/web/base64.js +136 -0
  112. package/web/benchmark.d.ts +126 -0
  113. package/web/benchmark.js +183 -0
  114. package/web/bits/arraybuffer.d.ts +35 -0
  115. package/web/bits/arraybuffer.js +59 -0
  116. package/web/bits/base64.d.ts +35 -0
  117. package/web/bits/base64.js +67 -0
  118. package/web/bits/hex.d.ts +17 -0
  119. package/web/bits/hex.js +27 -0
  120. package/web/bits/uint8array.d.ts +28 -0
  121. package/web/bits/uint8array.js +41 -0
  122. package/web/bytebuffer.d.ts +27 -0
  123. package/web/bytebuffer.js +29 -0
  124. package/web/consts.d.ts +33 -0
  125. package/web/consts.js +33 -0
  126. package/web/cron/logger.d.ts +22 -0
  127. package/web/cron/logger.js +30 -0
  128. package/web/cron/scheduledtask.d.ts +71 -0
  129. package/web/cron/scheduledtask.js +136 -0
  130. package/web/cron/types.d.ts +53 -0
  131. package/web/cron/types.js +31 -0
  132. package/web/cron.d.ts +29 -0
  133. package/web/cron.js +47 -0
  134. package/web/dict.d.ts +56 -0
  135. package/web/dict.js +67 -0
  136. package/web/error.d.ts +25 -0
  137. package/web/error.js +39 -0
  138. package/web/global.d.ts +27 -0
  139. package/web/global.js +49 -0
  140. package/web/hex.d.ts +32 -0
  141. package/web/hex.js +52 -0
  142. package/web/idx.d.ts +51 -0
  143. package/web/idx.js +76 -0
  144. package/web/json.d.ts +57 -0
  145. package/web/json.js +98 -0
  146. package/web/marshalling/marshaller.d.ts +51 -0
  147. package/web/marshalling/marshaller.js +150 -0
  148. package/web/marshalling/unmarshaller.d.ts +53 -0
  149. package/web/marshalling/unmarshaller.js +115 -0
  150. package/web/marshalling/util.d.ts +25 -0
  151. package/web/marshalling/util.js +25 -0
  152. package/web/number.d.ts +17 -0
  153. package/web/number.js +21 -0
  154. package/web/path.d.ts +25 -0
  155. package/web/path.js +26 -0
  156. package/web/promise.d.ts +42 -0
  157. package/web/promise.js +74 -0
  158. package/web/starttime.d.ts +23 -0
  159. package/web/starttime.js +29 -0
  160. package/web/string.d.ts +65 -0
  161. package/web/string.js +101 -0
  162. package/web/types/array.d.ts +34 -0
  163. package/web/types/array.js +63 -0
  164. package/web/types/enum.d.ts +30 -0
  165. package/web/types/enum.js +40 -0
  166. package/web/types/predicateerror.d.ts +40 -0
  167. package/web/types/predicateerror.js +128 -0
  168. package/web/types/primitive.d.ts +23 -0
  169. package/web/types/primitive.js +33 -0
  170. package/web/types/record.d.ts +67 -0
  171. package/web/types/record.js +213 -0
  172. package/web/types/types.d.ts +64 -0
  173. package/web/types/types.js +123 -0
  174. package/web/types/utils.d.ts +18 -0
  175. package/web/types/utils.js +30 -0
  176. package/web/uint8array.d.ts +176 -0
  177. package/web/uint8array.js +412 -0
  178. package/web/units.d.ts +159 -0
  179. package/web/units.js +312 -0
  180. package/web/utils/buffer.d.ts +49 -0
  181. package/web/utils/buffer.js +76 -0
  182. package/web/utils/fourbytes.d.ts +29 -0
  183. package/web/utils/fourbytes.js +45 -0
package/lib/path.js ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ const forbiddenCharacters = ["<", ">", ":", '"', "/", "\\", "|", "?", "*"];
17
+ /**
18
+ * Sanitize a filename
19
+ *
20
+ * Removes some characters known to cause issues with file names.
21
+ *
22
+ * Does not work on path.
23
+ *
24
+ * @public
25
+ */
26
+ export const sanitizeFilename = (filename, replacement = "_") => filename
27
+ .split("")
28
+ .map((c) => (forbiddenCharacters.includes(c) ? replacement : c))
29
+ .join("");
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ /**
17
+ * Create a promise that resolves after a given delay.
18
+ *
19
+ * @public
20
+ */
21
+ export declare const delayPromise: (delayInMS: number) => Promise<void>;
22
+ export type PromiseFunction<T> = () => Promise<T>;
23
+ /** Retry a promise until it succeed.
24
+ *
25
+ * This is probably a bad idea (or a bad implementation). Avoid using it.
26
+ *
27
+ * @public
28
+ */
29
+ export declare const retryPromise: <T>(promiseFunction: PromiseFunction<T>, retryDelayInS: number, retryTimeoutInS: number) => Promise<T>;
30
+ export type PromiseFunc<T> = () => Promise<T | void>;
31
+ /**
32
+ * Try all promises in the array until one resolves with a truthy value.
33
+ *
34
+ * @public
35
+ */
36
+ export declare const firstTruthy: <T>(promiseFuncs: Array<PromiseFunc<T>>) => Promise<T>;
37
+ /**
38
+ * Drop a promise and silence any exception.
39
+ *
40
+ * This is to be used *only* on dropped promises to explicitly silence any warning.
41
+ */
42
+ export declare const dropPromise: <T>(promise: Promise<T>) => void;
package/lib/promise.js ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ /* eslint-env node */
17
+ import { timeConvert } from "./units.js";
18
+ /**
19
+ * Create a promise that resolves after a given delay.
20
+ *
21
+ * @public
22
+ */
23
+ export const delayPromise = (delayInMS) =>
24
+ // eslint-disable-next-line promise/avoid-new
25
+ new Promise((resolve) => {
26
+ setTimeout(resolve, delayInMS);
27
+ });
28
+ /** Retry a promise until it succeed.
29
+ *
30
+ * This is probably a bad idea (or a bad implementation). Avoid using it.
31
+ *
32
+ * @public
33
+ */
34
+ export const retryPromise = async (promiseFunction, retryDelayInS, retryTimeoutInS) => {
35
+ const firstCallTime = timeConvert(`${Date.now()}ms`);
36
+ // eslint-disable-next-line @typescript-eslint/init-declarations
37
+ let firstError;
38
+ while (timeConvert(`${Date.now()}ms`) - firstCallTime < retryTimeoutInS) {
39
+ try {
40
+ // eslint-disable-next-line no-await-in-loop
41
+ const result = await promiseFunction();
42
+ return result;
43
+ }
44
+ catch (e) {
45
+ if (firstError === undefined)
46
+ firstError = e;
47
+ // eslint-disable-next-line no-await-in-loop
48
+ await delayPromise(timeConvert(retryDelayInS, "ms"));
49
+ }
50
+ }
51
+ throw firstError;
52
+ };
53
+ /**
54
+ * Try all promises in the array until one resolves with a truthy value.
55
+ *
56
+ * @public
57
+ */
58
+ export const firstTruthy = async (promiseFuncs) => {
59
+ for (const promiseFunc of promiseFuncs) {
60
+ try {
61
+ // eslint-disable-next-line no-await-in-loop
62
+ const res = await promiseFunc();
63
+ if (res)
64
+ return res;
65
+ }
66
+ catch { }
67
+ }
68
+ throw new Error("No result");
69
+ };
70
+ /**
71
+ * Drop a promise and silence any exception.
72
+ *
73
+ * This is to be used *only* on dropped promises to explicitly silence any warning.
74
+ */
75
+ export const dropPromise = (promise) => {
76
+ // eslint-disable-next-line @typescript-eslint/no-empty-function, promise/prefer-await-to-then
77
+ promise.catch(() => { });
78
+ };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ /**
17
+ * Return the number of seconds since the program/JavaScript environment started.
18
+ *
19
+ * The result is always rounded to a decisecond at most.
20
+ *
21
+ * @public
22
+ */
23
+ export declare const getElapsedTime: () => number;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ const startTime = Date.now();
17
+ const CENTI = 100;
18
+ const DECI = 10;
19
+ /**
20
+ * Return the number of seconds since the program/JavaScript environment started.
21
+ *
22
+ * The result is always rounded to a decisecond at most.
23
+ *
24
+ * @public
25
+ */
26
+ export const getElapsedTime = () => {
27
+ const resultValue = Date.now() - startTime;
28
+ return Math.round(resultValue / CENTI) / DECI;
29
+ };
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ /**
17
+ * JavaScript implementation of Java's hashCode
18
+ *
19
+ * Source: https://stackoverflow.com/a/7616484
20
+ *
21
+ * @public
22
+ */
23
+ export declare const hashCode: (str: string) => number;
24
+ export type HashCallback = (value: string) => string;
25
+ /**
26
+ * Simplify a string, removing all characters outside of a restricted subset.
27
+ *
28
+ * @param replacement - The replacement for each character removed.
29
+ * Defaults to ""
30
+ *
31
+ * @param subset - A regex to be used as the filter subset.
32
+ * Defaults to /[^[a-zA-Z0-9_]/g
33
+ *
34
+ * @param hash - A hash function to use as fallback.
35
+ * Defaults to hashCode().
36
+ *
37
+ * @returns
38
+ * The stripped down string. If the string ends empty after stripping, it will
39
+ * fall back to the hash function to not return an empty string.
40
+ *
41
+ * If the hash function is used, its result is converted to a string but is not
42
+ * subject to the restriction of subset.
43
+ *
44
+ * @public
45
+ */
46
+ export declare const simplify: (str: string, replacement?: string, subset?: RegExp, hash?: HashCallback) => string;
47
+ /**
48
+ * Encode a string containing multi-bytes characters using URI encoding.
49
+ *
50
+ * Only the multi-bytes characters are encoded; any ASCII (\<127) character is
51
+ * kept as-is, except for the "%" character.
52
+ *
53
+ * @public
54
+ */
55
+ export declare const encodeUTF8: (str: string) => string;
56
+ /**
57
+ * Decode a string containing escaped UTF-8 sequences
58
+ *
59
+ * This is almost an alias to decodeURIComponent
60
+ *
61
+ * @public
62
+ */
63
+ export declare const decodeUTF8: (str: string, skipErrors?: boolean) => string;
64
+ /** Capitalize (or uncapitalize) the first character of a string */
65
+ export declare const capitalize: (str: string, upperFirstLetter: boolean) => string;
package/lib/string.js ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ const hashCodeShift = 5;
17
+ /**
18
+ * JavaScript implementation of Java's hashCode
19
+ *
20
+ * Source: https://stackoverflow.com/a/7616484
21
+ *
22
+ * @public
23
+ */
24
+ export const hashCode = (str) => Array.from(str).reduce((hash, chr) => (hash << hashCodeShift) - hash + chr.charCodeAt(0), 0);
25
+ /**
26
+ * Simplify a string, removing all characters outside of a restricted subset.
27
+ *
28
+ * @param replacement - The replacement for each character removed.
29
+ * Defaults to ""
30
+ *
31
+ * @param subset - A regex to be used as the filter subset.
32
+ * Defaults to /[^[a-zA-Z0-9_]/g
33
+ *
34
+ * @param hash - A hash function to use as fallback.
35
+ * Defaults to hashCode().
36
+ *
37
+ * @returns
38
+ * The stripped down string. If the string ends empty after stripping, it will
39
+ * fall back to the hash function to not return an empty string.
40
+ *
41
+ * If the hash function is used, its result is converted to a string but is not
42
+ * subject to the restriction of subset.
43
+ *
44
+ * @public
45
+ */
46
+ export const simplify = (str, replacement, subset, hash) => {
47
+ const result = str.replace(subset ?? /[^[a-zA-Z0-9_]/gu, replacement ?? "");
48
+ return result.length > 0 ? result : String((hash ?? hashCode)(str));
49
+ };
50
+ // Only filter character point higher than 127
51
+ const FILTER_LIMIT = 127;
52
+ /**
53
+ * Encode a string containing multi-bytes characters using URI encoding.
54
+ *
55
+ * Only the multi-bytes characters are encoded; any ASCII (\<127) character is
56
+ * kept as-is, except for the "%" character.
57
+ *
58
+ * @public
59
+ */
60
+ export const encodeUTF8 = (str) => Array.from(str)
61
+ .map((chr) => {
62
+ if (chr.charCodeAt(0) > FILTER_LIMIT || chr.startsWith("%") || chr.length > 1) {
63
+ return encodeURIComponent(chr);
64
+ }
65
+ return chr;
66
+ })
67
+ .join("");
68
+ /**
69
+ * Decode a string containing escaped UTF-8 sequences
70
+ *
71
+ * This is almost an alias to decodeURIComponent
72
+ *
73
+ * @public
74
+ */
75
+ export const decodeUTF8 = (str, skipErrors) => {
76
+ try {
77
+ const fixedString = str.replace(/%(?<trailer>[0-9a-fA-F][^0-9a-fA-F]|[^0-9a-fA-F]|[0-9a-fA-F]$|$)/gu, "%25$<trailer>");
78
+ return decodeURIComponent(fixedString);
79
+ }
80
+ catch (error) {
81
+ if (!skipErrors)
82
+ throw error;
83
+ }
84
+ const outputParts = [];
85
+ let cursor = 0;
86
+ while (cursor < str.length) {
87
+ try {
88
+ const part = decodeURIComponent(str.substring(cursor));
89
+ outputParts.push(part);
90
+ cursor = str.length;
91
+ }
92
+ catch {
93
+ const nextPercentPosition = str.indexOf("%", cursor);
94
+ outputParts.push(str.substring(cursor, nextPercentPosition + 1));
95
+ cursor = nextPercentPosition + 1;
96
+ }
97
+ }
98
+ return outputParts.join("");
99
+ };
100
+ /** Capitalize (or uncapitalize) the first character of a string */
101
+ export const capitalize = (str, upperFirstLetter) => {
102
+ const firstLetter = str.charAt(0);
103
+ const transformedFirstLetter = upperFirstLetter
104
+ ? firstLetter.toUpperCase()
105
+ : firstLetter.toLowerCase();
106
+ const rest = str.slice(1);
107
+ return `${transformedFirstLetter}${rest}`;
108
+ };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import { PredicateOptions, TypePredicate } from "./types.js";
17
+ /** Shorthand for an object that can be either T or an array of T */
18
+ export type Arrayable<T> = Array<T> | T;
19
+ /**
20
+ * Check that a given object is an array of string
21
+ *
22
+ * @public
23
+ */
24
+ export declare const isStringArray: TypePredicate<Array<string>>;
25
+ /**
26
+ * Check that a given object is an array where each value have the given type.
27
+ *
28
+ * @public
29
+ */
30
+ export declare const isArrayOfType: <T>(obj: unknown, predicate: TypePredicate<T>, options?: PredicateOptions) => obj is Array<T>;
31
+ export declare const isArrayableOfType: <T>(obj: unknown, predicate: TypePredicate<T>, options?: PredicateOptions) => obj is Arrayable<T>;
32
+ /** @public */
33
+ export declare const makeArrayOfTypePredicate: <ValueType>(valuePredicate: TypePredicate<ValueType>) => TypePredicate<Array<ValueType>>;
34
+ export declare const makeArrayableOfTypePredicate: <ValueType>(valuePredicate: TypePredicate<ValueType>) => TypePredicate<Arrayable<ValueType>>;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import { PredicateError } from "./predicateerror.js";
17
+ import { getPredicateOptions } from "./types.js";
18
+ // #endregion
19
+ /**
20
+ * Check that a given object is an array of string
21
+ *
22
+ * @public
23
+ */
24
+ export const isStringArray = (obj, options = false) => {
25
+ const opt = getPredicateOptions(options);
26
+ if (!Array.isArray(obj)) {
27
+ PredicateError.expected(opt.raise, undefined, "an array");
28
+ return false;
29
+ }
30
+ for (const value of obj) {
31
+ if (typeof value !== "string") {
32
+ PredicateError.expected(opt.raise, "<array>", "a string");
33
+ return false;
34
+ }
35
+ }
36
+ return true;
37
+ };
38
+ /**
39
+ * Check that a given object is an array where each value have the given type.
40
+ *
41
+ * @public
42
+ */
43
+ export const isArrayOfType = (obj, predicate, options = false) => {
44
+ const opt = getPredicateOptions(options);
45
+ if (!Array.isArray(obj)) {
46
+ PredicateError.expected(opt.raise, undefined, "an array");
47
+ return false;
48
+ }
49
+ for (const value of obj) {
50
+ if (!predicate(value, opt)) {
51
+ PredicateError.predicateFailed(opt.raise, "<array>");
52
+ return false;
53
+ }
54
+ }
55
+ return true;
56
+ };
57
+ export const isArrayableOfType = (obj, predicate, options = false) => {
58
+ if (Array.isArray(obj))
59
+ return isArrayOfType(obj, predicate, options);
60
+ return predicate(obj, options);
61
+ };
62
+ /** @public */
63
+ export const makeArrayOfTypePredicate = (valuePredicate) => (obj, options = false) => isArrayOfType(obj, valuePredicate, options);
64
+ export const makeArrayableOfTypePredicate = (valuePredicate) => (obj, options = false) => isArrayableOfType(obj, valuePredicate, options);
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import { PredicateOptions, TypePredicate } from "./types.js";
17
+ /**
18
+ * Return an enum-type value whose key matches the provided key string.
19
+ *
20
+ * @public
21
+ */
22
+ export declare const keyToEnum: <EnumType>(key: string, enumType: Record<string, EnumType>) => EnumType;
23
+ /**
24
+ * Check if an object is of the given enum type.
25
+ *
26
+ * @public
27
+ */
28
+ export declare const isEnumType: <EnumType>(obj: unknown, enumType: unknown, options?: PredicateOptions) => obj is EnumType;
29
+ /** @public */
30
+ export declare const makeEnumTypePredicate: <EnumType>(enumType: unknown) => TypePredicate<EnumType>;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import { PredicateError } from "./predicateerror.js";
17
+ import { getPredicateOptions } from "./types.js";
18
+ /**
19
+ * Return an enum-type value whose key matches the provided key string.
20
+ *
21
+ * @public
22
+ */
23
+ export const keyToEnum = (key, enumType) => {
24
+ if (typeof enumType !== "object")
25
+ throw new Error("Invalid enum type");
26
+ for (const enumKey of Object.keys(enumType))
27
+ if (key === enumKey)
28
+ return enumType[enumKey];
29
+ throw new Error("Invalid enum key");
30
+ };
31
+ /**
32
+ * Check if an object is of the given enum type.
33
+ *
34
+ * @public
35
+ */
36
+ export const isEnumType = (obj, enumType, options = false) => {
37
+ const opt = getPredicateOptions(options);
38
+ const res = Object.values(enumType).includes(obj);
39
+ if (!res)
40
+ PredicateError.expected(opt.raise, undefined, "value from enum");
41
+ return res;
42
+ };
43
+ /** @public */
44
+ export const makeEnumTypePredicate = (enumType) => (obj, options = false) => isEnumType(obj, enumType, options);
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ interface PredicateErrorCtor {
17
+ keyName?: string;
18
+ error?: string;
19
+ cause?: Array<Error> | Error;
20
+ }
21
+ /**
22
+ * Construct an error whose message indicate what property failed to validate and why
23
+ *
24
+ * The static function provided will raise the appropriate error if the `raise` parameter is true,
25
+ * and do nothing otherwise.
26
+ *
27
+ * @internal
28
+ */
29
+ export declare class PredicateError extends Error {
30
+ #private;
31
+ constructor(params: PredicateErrorCtor);
32
+ get keyName(): string | undefined;
33
+ get error(): string | undefined;
34
+ static readonly mandatory: (raise: boolean, keyName: string) => void;
35
+ static readonly expected: (raise: boolean, keyName: string | undefined, expectedMessage: string, value?: unknown) => void;
36
+ static readonly predicateFailed: (raise: boolean, keyName: string | undefined) => void;
37
+ static readonly allTryFailed: (raise: boolean, keyName: string | undefined, cause: Array<Error>) => void;
38
+ static readonly keyError: (raise: boolean, keyName: string, cause: Error) => void;
39
+ }
40
+ export {};