@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
@@ -0,0 +1,67 @@
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 { isNumber } from "./primitive.js";
17
+ import { makeOrPredicate, makeTemplatePredicate } from "./types.js";
18
+ /** All `ms()` units, extracted from type definition */
19
+ const msBaseUnits = [
20
+ "Years",
21
+ "Year",
22
+ "Yrs",
23
+ "Yr",
24
+ "Y",
25
+ "Weeks",
26
+ "Week",
27
+ "W",
28
+ "Days",
29
+ "Day",
30
+ "D",
31
+ "Hours",
32
+ "Hour",
33
+ "Hrs",
34
+ "Hr",
35
+ "H",
36
+ "Minutes",
37
+ "Minute",
38
+ "Mins",
39
+ "Min",
40
+ "M",
41
+ "Seconds",
42
+ "Second",
43
+ "Secs",
44
+ "Sec",
45
+ "s",
46
+ "Milliseconds",
47
+ "Millisecond",
48
+ "Msecs",
49
+ "Msec",
50
+ "Ms",
51
+ ];
52
+ /** All `ms()` units, including lowercase and uppercase */
53
+ const msUnitAnyCase = Array.from(new Set([
54
+ ...msBaseUnits,
55
+ ...msBaseUnits.map((c) => c.toUpperCase()),
56
+ ...msBaseUnits.map((c) => c.toLowerCase()),
57
+ ]));
58
+ const isMsStrInput = makeTemplatePredicate("${number}");
59
+ const isMsStrUnitPredicate = makeTemplatePredicate("${number}${msUnitAnyCase}", { msUnitAnyCase });
60
+ const isMsSpaceUnitPredicate = makeTemplatePredicate("${number} ${msUnitAnyCase}", { msUnitAnyCase });
61
+ /** Check that a value is suitable for input for `ms()` */
62
+ export const isMsInput = makeOrPredicate([
63
+ isNumber,
64
+ isMsStrInput,
65
+ isMsStrUnitPredicate,
66
+ isMsSpaceUnitPredicate,
67
+ ]);
@@ -0,0 +1,176 @@
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 { pureBuf82B64, buf82b64 } from "./bits/uint8array.js";
17
+ /**
18
+ * Return a Uint8Array view on the provided ArrayBuffer.
19
+ *
20
+ * If clone is set to true, return a clone of the source array. Otherwise a view is returned.
21
+ *
22
+ * @public
23
+ */
24
+ export declare const getUint8Array: (arrayBuffer: ArrayBuffer | Uint8Array, offset?: number, length?: number, clone?: boolean) => Uint8Array;
25
+ /**
26
+ * Convert an Uint8Array to a raw string.
27
+ *
28
+ * @public
29
+ */
30
+ export declare const buf82str: (buf8: Uint8Array) => string;
31
+ /**
32
+ * Convert a string to an Uint8Array
33
+ *
34
+ * @public
35
+ */
36
+ export declare const str2buf8: (str: string) => Uint8Array;
37
+ /** @internal */
38
+ export declare const pureBuf82Hex: (buf8: Uint8Array, addPrefix?: boolean) => string;
39
+ /**
40
+ * Convert an Uint8Array to a hex string.
41
+ *
42
+ * @public
43
+ */
44
+ export declare const buf82hex: (buf8: Uint8Array, addPrefix?: boolean) => string;
45
+ /** @internal */
46
+ export declare const pureHex2Buf8: (hex: string) => Uint8Array;
47
+ /**
48
+ * Convert an hex string to an Uint8Array.
49
+ *
50
+ * @public
51
+ */
52
+ export declare const hex2buf8: (hex: string) => Uint8Array;
53
+ /**
54
+ * Concatenate multiple Uint8Array into one output.
55
+ *
56
+ * The output will have each individual buffer length stored so that they can be
57
+ * split afterward using explodeBuf8List(). Simple concatenation is available with merge().
58
+ *
59
+ * Output have the following format for each buffer:
60
+ *
61
+ * - 1 byte: the character "!", that identifies the kind of data that follows
62
+ * - 1 byte: length of the "buffer length as a string(base36)"
63
+ * - x bytes: buffer length as a string(base36)
64
+ * - y bytes: buffer content
65
+ *
66
+ * A special byte set to '#' can be appended to indicate the end of the buffers list. This allows
67
+ * the output of this function to be followed by other data while still being able to use the
68
+ * explode function.
69
+ *
70
+ * @public
71
+ */
72
+ export declare const concatenateBuf8List: (buf8s: Array<Uint8Array>, addEndMarker?: boolean) => Uint8Array;
73
+ /**
74
+ * Separate Uint8Array previously merged using concatenateBuf8List().
75
+ *
76
+ * Each buffer prefixed by a "!" uses the format described in `concatenateBuf8List()`.
77
+ * If a buffer is not prefixed by a "!", it uses the old format:
78
+ *
79
+ * - x bytes: the length of the buffer, as an hexadecimal string
80
+ * - 1 bytes: the "," character
81
+ * - y bytes: buffer content
82
+ *
83
+ * As a special case, if the first byte read for the next buffer is "#", which is an impossible
84
+ * character for both the old and new format, it is interpreted as the end of the buffer list.
85
+ *
86
+ * @public
87
+ */
88
+ export declare const explodeBuf8List: (mergedBuf8s: Uint8Array) => Array<Uint8Array>;
89
+ /**
90
+ * Return the length of the buffer list, up to either the end marker or the buffer size.
91
+ *
92
+ * @public
93
+ */
94
+ export declare const concatenatedBuf8ListSize: (mergedBuf8s: Uint8Array) => number;
95
+ /**
96
+ * Merge Uint8Arrays into one.
97
+ *
98
+ * This performs a simple concatenation;
99
+ *
100
+ * @public
101
+ */
102
+ export declare const merge: (buf8s: Array<Uint8Array>) => Uint8Array;
103
+ /** @internal */
104
+ export declare const pureB642Buf8: (b64: string, strict?: boolean) => Uint8Array;
105
+ /**
106
+ * Convert a B64 string to an Uint8Array.
107
+ *
108
+ * @public
109
+ */
110
+ export declare const b642buf8: (b64: string, strict?: boolean) => Uint8Array;
111
+ /** @internal */
112
+ export declare const pureUtf82Buf8: (str: string) => Uint8Array;
113
+ /**
114
+ * Convert an UTF-8 string into an Uint8Array.
115
+ *
116
+ * @public
117
+ */
118
+ export declare const utf82buf8: (utf8: string) => Uint8Array;
119
+ /** @internal */
120
+ export declare const pureBuf82Utf8: (buf8: Uint8Array) => string;
121
+ /**
122
+ * Convert an Uint8Array into an UTF-8 string
123
+ *
124
+ * @public
125
+ */
126
+ export declare const buf82utf8: (buf8: Uint8Array) => string;
127
+ /**
128
+ * Check that the content of two Uint8Array is equal.
129
+ *
130
+ * @public
131
+ */
132
+ export declare const buf8Equal: (op1: Uint8Array, op2: Uint8Array) => boolean;
133
+ /**
134
+ * Find the position of a string in a buffer
135
+ *
136
+ * @param needle - String to find. Only work with 1 byte-wide characters.
137
+ *
138
+ * @param ab - Buffer to look into
139
+ *
140
+ * @param startPosition - Starting index to look from
141
+ *
142
+ * @returns
143
+ * The position of the string in the buffer. If not found returns -1
144
+ *
145
+ * @public
146
+ */
147
+ export declare const findString: (needle: string, buf8: Uint8Array, startPosition?: number) => number;
148
+ /**
149
+ * Find the position of a string in a buffer from the end
150
+ *
151
+ * @param needle - String to find. Only work with 1 byte characters.
152
+ *
153
+ * @param ab - Buffer to look into
154
+ *
155
+ * @param startPosition - Starting index to look from
156
+ *
157
+ * @param endPosition - Last index to look from. The needle must fit completely before this.
158
+ * -1 mean end of the file.
159
+ *
160
+ * @returns
161
+ * The position of the string in the buffer. If not found returns -1
162
+ *
163
+ * @public
164
+ */
165
+ export declare const findLastString: (needle: string, buf8: Uint8Array, startPosition?: number, endPosition?: number) => number;
166
+ /**
167
+ * Check if a byte sequence looks like a valid UTF-8 sequence that *does* have wide characters.
168
+ *
169
+ * https://en.wikipedia.org/wiki/UTF-8
170
+ *
171
+ * @returns
172
+ * `true` if the byte sequence does contain UTF-8 sequences.
173
+ * Regular ASCII string will return `false` as they won't contain such sequence.
174
+ */
175
+ export declare const isUTF8Sequence: (bytes: Uint8Array) => boolean;
176
+ export { buf82b64, pureBuf82B64 };
@@ -0,0 +1,438 @@
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 TextEncodingShim from "text-encoding-shim";
17
+ import { arrayEqual } from "./array.js";
18
+ import { b642ab as bitsB642ab } from "./bits/arraybuffer.js";
19
+ import { clearHexInput } from "./bits/hex.js";
20
+ import { getUint8Array as getUint8ArrayBits, pureBuf82B64, buf82b64 } from "./bits/uint8array.js";
21
+ import { HEXBYTE_CHR_COUNT, HEX_DIGITS, MAX_RADIX } from "./consts.js";
22
+ import { bufferB642Buf8, bufferBuf82Hex, bufferBuf82Utf8, bufferHex2Buf8, bufferUtf82Buf8, haveBufferBase64, haveBufferHex, haveBufferUTF8, } from "./utils/buffer.js";
23
+ import FourBytes from "./utils/fourbytes.js";
24
+ /**
25
+ * Return a Uint8Array view on the provided ArrayBuffer.
26
+ *
27
+ * If clone is set to true, return a clone of the source array. Otherwise a view is returned.
28
+ *
29
+ * @public
30
+ */
31
+ export const getUint8Array = getUint8ArrayBits;
32
+ /**
33
+ * Convert an Uint8Array to a raw string.
34
+ *
35
+ * @public
36
+ */
37
+ export const buf82str = (buf8) => {
38
+ const charArray = [];
39
+ const length = buf8.byteLength;
40
+ charArray.length = length;
41
+ for (let i = 0; i < length; i++)
42
+ charArray[i] = String.fromCharCode(buf8[i]);
43
+ return charArray.join("");
44
+ };
45
+ /**
46
+ * Convert a string to an Uint8Array
47
+ *
48
+ * @public
49
+ */
50
+ export const str2buf8 = (str) => {
51
+ const buf8 = new Uint8Array(str.length);
52
+ for (let i = 0, strLen = str.length; i < strLen; i++)
53
+ buf8[i] = str.charCodeAt(i);
54
+ return buf8;
55
+ };
56
+ /** @internal */
57
+ export const pureBuf82Hex = (buf8, addPrefix) => {
58
+ const hexArray = [];
59
+ const length = buf8.length;
60
+ hexArray.length = length * HEXBYTE_CHR_COUNT;
61
+ for (let i = 0; i < length; i++) {
62
+ hexArray[i] = buf8[i].toString(HEX_DIGITS).padStart(HEXBYTE_CHR_COUNT, "0");
63
+ }
64
+ const hexResult = hexArray.join("");
65
+ return addPrefix ? `0x${hexResult}` : hexResult;
66
+ };
67
+ /**
68
+ * Convert an Uint8Array to a hex string.
69
+ *
70
+ * @public
71
+ */
72
+ export const buf82hex = haveBufferHex() ? bufferBuf82Hex : pureBuf82Hex;
73
+ /** @internal */
74
+ export const pureHex2Buf8 = (hex) => {
75
+ const input = clearHexInput(hex);
76
+ const buf8 = new Uint8Array(input.length / HEXBYTE_CHR_COUNT);
77
+ for (let i = 0; i < buf8.length; ++i) {
78
+ buf8[i] = parseInt(input[i * HEXBYTE_CHR_COUNT] + input[i * HEXBYTE_CHR_COUNT + 1], HEX_DIGITS);
79
+ }
80
+ return buf8;
81
+ };
82
+ /**
83
+ * Convert an hex string to an Uint8Array.
84
+ *
85
+ * @public
86
+ */
87
+ export const hex2buf8 = haveBufferHex() ? bufferHex2Buf8 : pureHex2Buf8;
88
+ const lengthAsUint8Array = (length) => {
89
+ const lengthAsString = length.toString(MAX_RADIX);
90
+ const maxByteValue = 255;
91
+ if (lengthAsString.length > maxByteValue)
92
+ throw new Error("Unsupported buffer length");
93
+ return str2buf8(lengthAsString);
94
+ };
95
+ /**
96
+ * Concatenate multiple Uint8Array into one output.
97
+ *
98
+ * The output will have each individual buffer length stored so that they can be
99
+ * split afterward using explodeBuf8List(). Simple concatenation is available with merge().
100
+ *
101
+ * Output have the following format for each buffer:
102
+ *
103
+ * - 1 byte: the character "!", that identifies the kind of data that follows
104
+ * - 1 byte: length of the "buffer length as a string(base36)"
105
+ * - x bytes: buffer length as a string(base36)
106
+ * - y bytes: buffer content
107
+ *
108
+ * A special byte set to '#' can be appended to indicate the end of the buffers list. This allows
109
+ * the output of this function to be followed by other data while still being able to use the
110
+ * explode function.
111
+ *
112
+ * @public
113
+ */
114
+ export const concatenateBuf8List = (buf8s, addEndMarker = false) => {
115
+ const inputs = buf8s.map((buf8Input) => ({
116
+ buf8Input,
117
+ lengthBuf8: lengthAsUint8Array(buf8Input.length),
118
+ }));
119
+ const totalOutputLength = inputs.reduce(
120
+ // + 2 because of the length's length and the '!' prefix
121
+ (acc, cur) => acc + cur.buf8Input.length + cur.lengthBuf8.length + 1 + 1, 0) + (addEndMarker ? 1 : 0);
122
+ const buf8 = new Uint8Array(totalOutputLength);
123
+ let cursor = 0;
124
+ const EXCLAMATION_CODE = "!".charCodeAt(0);
125
+ for (const input of inputs) {
126
+ buf8[cursor++] = EXCLAMATION_CODE;
127
+ buf8[cursor++] = input.lengthBuf8.length;
128
+ buf8.set(input.lengthBuf8, cursor);
129
+ cursor += input.lengthBuf8.length;
130
+ buf8.set(input.buf8Input, cursor);
131
+ cursor += input.buf8Input.length;
132
+ }
133
+ if (addEndMarker)
134
+ buf8[cursor] = "#".charCodeAt(0);
135
+ return buf8;
136
+ };
137
+ /** Helper for explodeBuf8List() */
138
+ const extractConcatenatedBuffer = (mergedBuf8s, start, length) => {
139
+ const buffer = mergedBuf8s.slice(start, start + length);
140
+ return { buffer, newCursorPos: start + length };
141
+ };
142
+ /** Helper for explodeBuf8List() */
143
+ const readNewConcatenatedBuffer = (mergedBuf8s, initialCursor) => {
144
+ // Skip '!'
145
+ let cursor = initialCursor + 1;
146
+ const bufferLengthLength = mergedBuf8s[cursor++];
147
+ const bufferLength = parseInt(buf82str(mergedBuf8s.slice(cursor, cursor + bufferLengthLength)), MAX_RADIX);
148
+ cursor += bufferLengthLength;
149
+ return extractConcatenatedBuffer(mergedBuf8s, cursor, bufferLength);
150
+ };
151
+ /**
152
+ * Try to read a "middle" version buffer; the intermediate version with no delimiters.
153
+ *
154
+ * This format was short-lived and we just assume the buffers reach the end.
155
+ */
156
+ const tryReadMiddleVersionBuffer = (mergedBuf8s) => {
157
+ if (mergedBuf8s.byteLength < 1)
158
+ return;
159
+ // Don't lose time fake-decoding a newer buffer
160
+ const firstChar = mergedBuf8s[0];
161
+ if (firstChar === "!".charCodeAt(0) || firstChar === "#".charCodeAt(0))
162
+ return;
163
+ let cursor = 0;
164
+ const result = [];
165
+ while (cursor < mergedBuf8s.byteLength) {
166
+ const lengthStringLength = mergedBuf8s[cursor++];
167
+ if (cursor + lengthStringLength > mergedBuf8s.byteLength)
168
+ return;
169
+ const lengthString = buf82str(getUint8Array(mergedBuf8s, cursor, lengthStringLength));
170
+ const length = parseInt(lengthString, MAX_RADIX);
171
+ cursor += lengthStringLength;
172
+ if (cursor + length > mergedBuf8s.byteLength)
173
+ return;
174
+ const extraction = extractConcatenatedBuffer(mergedBuf8s, cursor, length);
175
+ cursor = extraction.newCursorPos;
176
+ result.push(extraction.buffer);
177
+ }
178
+ // Somewhat redundant but kept because I'm not sure the whole logic is sound
179
+ if (cursor !== mergedBuf8s.byteLength)
180
+ return;
181
+ return result;
182
+ };
183
+ /** Helper for explodeBuf8List() */
184
+ const readOldConcatenatedBuffer = (mergedBuf8s, initialCursor) => {
185
+ let cursor = initialCursor;
186
+ const lengthCharacters = [];
187
+ const COMMA_CODE = ",".charCodeAt(0);
188
+ while (cursor < mergedBuf8s.length) {
189
+ const readChar = mergedBuf8s[cursor++];
190
+ if (readChar === COMMA_CODE)
191
+ break;
192
+ lengthCharacters.push(readChar);
193
+ }
194
+ const bufferLength = parseInt(lengthCharacters.map((charCode) => String.fromCharCode(charCode)).join(""), HEX_DIGITS);
195
+ return extractConcatenatedBuffer(mergedBuf8s, cursor, bufferLength);
196
+ };
197
+ const parseBuf8List = (mergedBuf8s) => {
198
+ let cursor = 0;
199
+ // Compatibility layer
200
+ const result = tryReadMiddleVersionBuffer(mergedBuf8s) ?? [];
201
+ if (result.length === 0) {
202
+ while (cursor < mergedBuf8s.length) {
203
+ // Read buffer's length's length
204
+ const bufferFirstChar = mergedBuf8s[cursor];
205
+ // eslint-disable-next-line @typescript-eslint/init-declarations
206
+ let bufferResult;
207
+ if (bufferFirstChar === "!".charCodeAt(0)) {
208
+ // Read new buffer
209
+ bufferResult = readNewConcatenatedBuffer(mergedBuf8s, cursor);
210
+ }
211
+ else if (bufferFirstChar === "#".charCodeAt(0)) {
212
+ ++cursor;
213
+ break;
214
+ }
215
+ else {
216
+ bufferResult = readOldConcatenatedBuffer(mergedBuf8s, cursor);
217
+ }
218
+ result.push(bufferResult.buffer);
219
+ cursor = bufferResult.newCursorPos;
220
+ }
221
+ }
222
+ else {
223
+ // This result comes from the compatibility layer, we used all the input buffer
224
+ cursor = mergedBuf8s.byteLength;
225
+ }
226
+ return { data: result, inputBytesUsed: cursor };
227
+ };
228
+ /**
229
+ * Separate Uint8Array previously merged using concatenateBuf8List().
230
+ *
231
+ * Each buffer prefixed by a "!" uses the format described in `concatenateBuf8List()`.
232
+ * If a buffer is not prefixed by a "!", it uses the old format:
233
+ *
234
+ * - x bytes: the length of the buffer, as an hexadecimal string
235
+ * - 1 bytes: the "," character
236
+ * - y bytes: buffer content
237
+ *
238
+ * As a special case, if the first byte read for the next buffer is "#", which is an impossible
239
+ * character for both the old and new format, it is interpreted as the end of the buffer list.
240
+ *
241
+ * @public
242
+ */
243
+ export const explodeBuf8List = (mergedBuf8s) => parseBuf8List(mergedBuf8s).data;
244
+ /**
245
+ * Return the length of the buffer list, up to either the end marker or the buffer size.
246
+ *
247
+ * @public
248
+ */
249
+ export const concatenatedBuf8ListSize = (mergedBuf8s) => parseBuf8List(mergedBuf8s).inputBytesUsed;
250
+ /**
251
+ * Merge Uint8Arrays into one.
252
+ *
253
+ * This performs a simple concatenation;
254
+ *
255
+ * @public
256
+ */
257
+ export const merge = (buf8s) => {
258
+ const fullLength = buf8s.reduce((acc, cur) => acc + cur.length, 0);
259
+ const buf8 = new Uint8Array(fullLength);
260
+ let cursor = 0;
261
+ for (const buf8Input of buf8s) {
262
+ buf8.set(buf8Input, cursor);
263
+ cursor += buf8Input.length;
264
+ }
265
+ return buf8;
266
+ };
267
+ /** @internal */
268
+ export const pureB642Buf8 = (b64, strict = false) => getUint8Array(bitsB642ab(b64, strict));
269
+ /**
270
+ * Convert a B64 string to an Uint8Array.
271
+ *
272
+ * @public
273
+ */
274
+ export const b642buf8 = haveBufferBase64() ? bufferB642Buf8 : pureB642Buf8;
275
+ /** @internal */
276
+ export const pureUtf82Buf8 = (str) => new TextEncodingShim.TextEncoder().encode(str);
277
+ /**
278
+ * Convert an UTF-8 string into an Uint8Array.
279
+ *
280
+ * @public
281
+ */
282
+ export const utf82buf8 = haveBufferUTF8() ? bufferUtf82Buf8 : pureUtf82Buf8;
283
+ /** @internal */
284
+ export const pureBuf82Utf8 = (buf8) => new TextEncodingShim.TextDecoder().decode(buf8);
285
+ /**
286
+ * Convert an Uint8Array into an UTF-8 string
287
+ *
288
+ * @public
289
+ */
290
+ export const buf82utf8 = haveBufferUTF8() ? bufferBuf82Utf8 : pureBuf82Utf8;
291
+ /**
292
+ * Check that the content of two Uint8Array is equal.
293
+ *
294
+ * @public
295
+ */
296
+ export const buf8Equal = (op1, op2) => arrayEqual(op1, op2);
297
+ /**
298
+ * Find the position of a string in a buffer
299
+ *
300
+ * @param needle - String to find. Only work with 1 byte-wide characters.
301
+ *
302
+ * @param ab - Buffer to look into
303
+ *
304
+ * @param startPosition - Starting index to look from
305
+ *
306
+ * @returns
307
+ * The position of the string in the buffer. If not found returns -1
308
+ *
309
+ * @public
310
+ */
311
+ export const findString = (needle, buf8, startPosition = 0) => {
312
+ let position = startPosition;
313
+ const charCodes = needle.split("").map((strChr) => strChr.charCodeAt(0));
314
+ while (position < buf8.length) {
315
+ position = buf8.indexOf(charCodes[0], position);
316
+ // First character not found in buffer?
317
+ if (position === -1)
318
+ break;
319
+ // Maybe we're too late
320
+ if (position > buf8.length - charCodes.length)
321
+ break;
322
+ let valid = true;
323
+ // Possible match, test all upcoming characters
324
+ for (let i = 1; valid && i < charCodes.length; ++i) {
325
+ // Mismatch?
326
+ if (buf8[position + i] !== charCodes[i])
327
+ valid = false;
328
+ }
329
+ // Found string
330
+ if (valid)
331
+ return position;
332
+ ++position;
333
+ }
334
+ return -1;
335
+ };
336
+ /**
337
+ * Find the position of a string in a buffer from the end
338
+ *
339
+ * @param needle - String to find. Only work with 1 byte characters.
340
+ *
341
+ * @param ab - Buffer to look into
342
+ *
343
+ * @param startPosition - Starting index to look from
344
+ *
345
+ * @param endPosition - Last index to look from. The needle must fit completely before this.
346
+ * -1 mean end of the file.
347
+ *
348
+ * @returns
349
+ * The position of the string in the buffer. If not found returns -1
350
+ *
351
+ * @public
352
+ */
353
+ export const findLastString = (needle, buf8, startPosition = 0, endPosition = -1) => {
354
+ let position = endPosition === -1 ? buf8.length - 1 : endPosition;
355
+ const charCodes = needle
356
+ .split("")
357
+ .reverse()
358
+ .map((strChr) => strChr.charCodeAt(0));
359
+ while (position >= startPosition) {
360
+ position = buf8.lastIndexOf(charCodes[0], position);
361
+ // First character not found in buffer?
362
+ if (position === -1)
363
+ break;
364
+ // Maybe we're too late
365
+ if (position < startPosition + charCodes.length)
366
+ break;
367
+ let valid = true;
368
+ // Possible match, test all upcoming characters
369
+ for (let i = 1; valid && i < charCodes.length; ++i) {
370
+ // Mismatch?
371
+ if (buf8[position - i] !== charCodes[i])
372
+ valid = false;
373
+ }
374
+ // Found string
375
+ if (valid)
376
+ return position - charCodes.length + 1;
377
+ --position;
378
+ }
379
+ return -1;
380
+ };
381
+ /* eslint-disable @typescript-eslint/no-magic-numbers */
382
+ const isInvalidFollowByte = (value) => value === undefined || value < 0b10000000 || value >= 0b11000000;
383
+ const utf8SequenceLength = (byte1) => {
384
+ if (byte1 < 0b10000000)
385
+ return 1;
386
+ if (byte1 < 0b11100000)
387
+ return 2;
388
+ if (byte1 < 0b11110000)
389
+ return 3;
390
+ if (byte1 < 0b11111000)
391
+ return 4;
392
+ throw new Error("Invalid first byte");
393
+ };
394
+ /**
395
+ * Check if a byte sequence looks like a valid UTF-8 sequence that *does* have wide characters.
396
+ *
397
+ * https://en.wikipedia.org/wiki/UTF-8
398
+ *
399
+ * @returns
400
+ * `true` if the byte sequence does contain UTF-8 sequences.
401
+ * Regular ASCII string will return `false` as they won't contain such sequence.
402
+ */
403
+ export const isUTF8Sequence = (bytes) => {
404
+ try {
405
+ let haveUTF8 = false;
406
+ const b = new FourBytes(bytes);
407
+ while (b.byte1 !== undefined) {
408
+ const seqLength = utf8SequenceLength(b.byte1);
409
+ // Voluntary fallthrough
410
+ /* eslint-disable no-fallthrough */
411
+ switch (seqLength) {
412
+ // Range 0x10000-0x10FFFF
413
+ case 4:
414
+ if (isInvalidFollowByte(b.byte4))
415
+ return false;
416
+ // Range 0x0800-0xFFFF
417
+ case 3:
418
+ if (isInvalidFollowByte(b.byte3))
419
+ return false;
420
+ // Range 0x80-0x07FF
421
+ case 2:
422
+ if (isInvalidFollowByte(b.byte2))
423
+ return false;
424
+ haveUTF8 = true;
425
+ // Range 0x00-0x7F
426
+ case 1:
427
+ }
428
+ /* eslint-enable no-fallthrough */
429
+ b.advance(seqLength);
430
+ }
431
+ return haveUTF8;
432
+ }
433
+ catch {
434
+ return false;
435
+ }
436
+ };
437
+ /* eslint-enable @typescript-eslint/no-magic-numbers */
438
+ export { buf82b64, pureBuf82B64 };