@bsb/base 9.0.0

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 (182) hide show
  1. package/LICENSE +665 -0
  2. package/LICENSE.commercial +32 -0
  3. package/README.md +263 -0
  4. package/bsb-plugin.json +62 -0
  5. package/lib/base/BSBConfig.d.ts +130 -0
  6. package/lib/base/BSBConfig.js +95 -0
  7. package/lib/base/BSBConfig.js.map +1 -0
  8. package/lib/base/BSBEvents.d.ts +207 -0
  9. package/lib/base/BSBEvents.js +101 -0
  10. package/lib/base/BSBEvents.js.map +1 -0
  11. package/lib/base/BSBObservable.d.ts +178 -0
  12. package/lib/base/BSBObservable.js +91 -0
  13. package/lib/base/BSBObservable.js.map +1 -0
  14. package/lib/base/BSBService.d.ts +277 -0
  15. package/lib/base/BSBService.js +366 -0
  16. package/lib/base/BSBService.js.map +1 -0
  17. package/lib/base/BSBServiceClient.d.ts +135 -0
  18. package/lib/base/BSBServiceClient.js +130 -0
  19. package/lib/base/BSBServiceClient.js.map +1 -0
  20. package/lib/base/EventValidator.d.ts +137 -0
  21. package/lib/base/EventValidator.js +210 -0
  22. package/lib/base/EventValidator.js.map +1 -0
  23. package/lib/base/ObservableBackend.d.ts +281 -0
  24. package/lib/base/ObservableBackend.js +515 -0
  25. package/lib/base/ObservableBackend.js.map +1 -0
  26. package/lib/base/PluginConfig.d.ts +196 -0
  27. package/lib/base/PluginConfig.js +96 -0
  28. package/lib/base/PluginConfig.js.map +1 -0
  29. package/lib/base/PluginEvents.d.ts +140 -0
  30. package/lib/base/PluginEvents.js +268 -0
  31. package/lib/base/PluginEvents.js.map +1 -0
  32. package/lib/base/PluginObservable.d.ts +196 -0
  33. package/lib/base/PluginObservable.js +250 -0
  34. package/lib/base/PluginObservable.js.map +1 -0
  35. package/lib/base/ResourceContext.d.ts +70 -0
  36. package/lib/base/ResourceContext.js +54 -0
  37. package/lib/base/ResourceContext.js.map +1 -0
  38. package/lib/base/base.d.ts +264 -0
  39. package/lib/base/base.js +182 -0
  40. package/lib/base/base.js.map +1 -0
  41. package/lib/base/errorMessages.d.ts +56 -0
  42. package/lib/base/errorMessages.js +70 -0
  43. package/lib/base/errorMessages.js.map +1 -0
  44. package/lib/base/factory.d.ts +58 -0
  45. package/lib/base/factory.js +167 -0
  46. package/lib/base/factory.js.map +1 -0
  47. package/lib/base/functions.d.ts +117 -0
  48. package/lib/base/functions.js +152 -0
  49. package/lib/base/functions.js.map +1 -0
  50. package/lib/base/index.d.ts +44 -0
  51. package/lib/base/index.js +64 -0
  52. package/lib/base/index.js.map +1 -0
  53. package/lib/base/logFormatter.d.ts +50 -0
  54. package/lib/base/logFormatter.js +105 -0
  55. package/lib/base/logFormatter.js.map +1 -0
  56. package/lib/base/tools.d.ts +316 -0
  57. package/lib/base/tools.js +666 -0
  58. package/lib/base/tools.js.map +1 -0
  59. package/lib/cli.d.ts +28 -0
  60. package/lib/cli.js +254 -0
  61. package/lib/cli.js.map +1 -0
  62. package/lib/dev.d.ts +27 -0
  63. package/lib/dev.js +200 -0
  64. package/lib/dev.js.map +1 -0
  65. package/lib/index.d.ts +32 -0
  66. package/lib/index.js +49 -0
  67. package/lib/index.js.map +1 -0
  68. package/lib/interfaces/events.d.ts +67 -0
  69. package/lib/interfaces/events.js +44 -0
  70. package/lib/interfaces/events.js.map +1 -0
  71. package/lib/interfaces/index.d.ts +38 -0
  72. package/lib/interfaces/index.js +59 -0
  73. package/lib/interfaces/index.js.map +1 -0
  74. package/lib/interfaces/logging.d.ts +106 -0
  75. package/lib/interfaces/logging.js +39 -0
  76. package/lib/interfaces/logging.js.map +1 -0
  77. package/lib/interfaces/metrics.d.ts +365 -0
  78. package/lib/interfaces/metrics.js +46 -0
  79. package/lib/interfaces/metrics.js.map +1 -0
  80. package/lib/interfaces/observable-types.d.ts +63 -0
  81. package/lib/interfaces/observable-types.js +49 -0
  82. package/lib/interfaces/observable-types.js.map +1 -0
  83. package/lib/interfaces/observable.d.ts +297 -0
  84. package/lib/interfaces/observable.js +29 -0
  85. package/lib/interfaces/observable.js.map +1 -0
  86. package/lib/interfaces/options.d.ts +164 -0
  87. package/lib/interfaces/options.js +56 -0
  88. package/lib/interfaces/options.js.map +1 -0
  89. package/lib/interfaces/plugins.d.ts +143 -0
  90. package/lib/interfaces/plugins.js +45 -0
  91. package/lib/interfaces/plugins.js.map +1 -0
  92. package/lib/interfaces/result.d.ts +129 -0
  93. package/lib/interfaces/result.js +162 -0
  94. package/lib/interfaces/result.js.map +1 -0
  95. package/lib/interfaces/schema-events.d.ts +378 -0
  96. package/lib/interfaces/schema-events.js +247 -0
  97. package/lib/interfaces/schema-events.js.map +1 -0
  98. package/lib/interfaces/schema-types.d.ts +407 -0
  99. package/lib/interfaces/schema-types.js +581 -0
  100. package/lib/interfaces/schema-types.js.map +1 -0
  101. package/lib/interfaces/service.d.ts +48 -0
  102. package/lib/interfaces/service.js +29 -0
  103. package/lib/interfaces/service.js.map +1 -0
  104. package/lib/interfaces/tools.d.ts +65 -0
  105. package/lib/interfaces/tools.js +50 -0
  106. package/lib/interfaces/tools.js.map +1 -0
  107. package/lib/plugins/config-default/index.d.ts +59 -0
  108. package/lib/plugins/config-default/index.js +197 -0
  109. package/lib/plugins/config-default/index.js.map +1 -0
  110. package/lib/plugins/config-default/interfaces.d.ts +92 -0
  111. package/lib/plugins/config-default/interfaces.js +36 -0
  112. package/lib/plugins/config-default/interfaces.js.map +1 -0
  113. package/lib/plugins/events-default/events/broadcast.d.ts +36 -0
  114. package/lib/plugins/events-default/events/broadcast.js +85 -0
  115. package/lib/plugins/events-default/events/broadcast.js.map +1 -0
  116. package/lib/plugins/events-default/events/emit.d.ts +38 -0
  117. package/lib/plugins/events-default/events/emit.js +104 -0
  118. package/lib/plugins/events-default/events/emit.js.map +1 -0
  119. package/lib/plugins/events-default/events/emitAndReturn.d.ts +36 -0
  120. package/lib/plugins/events-default/events/emitAndReturn.js +100 -0
  121. package/lib/plugins/events-default/events/emitAndReturn.js.map +1 -0
  122. package/lib/plugins/events-default/events/emitStreamAndReceiveStream.d.ts +38 -0
  123. package/lib/plugins/events-default/events/emitStreamAndReceiveStream.js +134 -0
  124. package/lib/plugins/events-default/events/emitStreamAndReceiveStream.js.map +1 -0
  125. package/lib/plugins/events-default/events/index.d.ts +30 -0
  126. package/lib/plugins/events-default/events/index.js +38 -0
  127. package/lib/plugins/events-default/events/index.js.map +1 -0
  128. package/lib/plugins/events-default/index.d.ts +57 -0
  129. package/lib/plugins/events-default/index.js +86 -0
  130. package/lib/plugins/events-default/index.js.map +1 -0
  131. package/lib/plugins/observable-default/index.d.ts +43 -0
  132. package/lib/plugins/observable-default/index.js +151 -0
  133. package/lib/plugins/observable-default/index.js.map +1 -0
  134. package/lib/schemas/config-default.json +34 -0
  135. package/lib/schemas/config-default.plugin.json +36 -0
  136. package/lib/schemas/events-default.json +18 -0
  137. package/lib/schemas/events-default.plugin.json +17 -0
  138. package/lib/schemas/observable-default.json +33 -0
  139. package/lib/schemas/observable-default.plugin.json +24 -0
  140. package/lib/scripts/bsb-client-cli.d.ts +21 -0
  141. package/lib/scripts/bsb-client-cli.js +701 -0
  142. package/lib/scripts/bsb-client-cli.js.map +1 -0
  143. package/lib/scripts/bsb-plugin-cli.d.ts +15 -0
  144. package/lib/scripts/bsb-plugin-cli.js +547 -0
  145. package/lib/scripts/bsb-plugin-cli.js.map +1 -0
  146. package/lib/scripts/export-schemas.d.ts +17 -0
  147. package/lib/scripts/export-schemas.js +205 -0
  148. package/lib/scripts/export-schemas.js.map +1 -0
  149. package/lib/scripts/extract-schemas-from-source.d.ts +23 -0
  150. package/lib/scripts/extract-schemas-from-source.js +604 -0
  151. package/lib/scripts/extract-schemas-from-source.js.map +1 -0
  152. package/lib/scripts/generate-client-types.d.ts +22 -0
  153. package/lib/scripts/generate-client-types.js +537 -0
  154. package/lib/scripts/generate-client-types.js.map +1 -0
  155. package/lib/scripts/generate-plugin-json.d.ts +17 -0
  156. package/lib/scripts/generate-plugin-json.js +219 -0
  157. package/lib/scripts/generate-plugin-json.js.map +1 -0
  158. package/lib/serviceBase/config.d.ts +83 -0
  159. package/lib/serviceBase/config.js +236 -0
  160. package/lib/serviceBase/config.js.map +1 -0
  161. package/lib/serviceBase/events.d.ts +91 -0
  162. package/lib/serviceBase/events.js +519 -0
  163. package/lib/serviceBase/events.js.map +1 -0
  164. package/lib/serviceBase/index.d.ts +33 -0
  165. package/lib/serviceBase/index.js +50 -0
  166. package/lib/serviceBase/index.js.map +1 -0
  167. package/lib/serviceBase/observable.d.ts +249 -0
  168. package/lib/serviceBase/observable.js +551 -0
  169. package/lib/serviceBase/observable.js.map +1 -0
  170. package/lib/serviceBase/plugins.d.ts +48 -0
  171. package/lib/serviceBase/plugins.js +184 -0
  172. package/lib/serviceBase/plugins.js.map +1 -0
  173. package/lib/serviceBase/serviceBase.d.ts +228 -0
  174. package/lib/serviceBase/serviceBase.js +420 -0
  175. package/lib/serviceBase/serviceBase.js.map +1 -0
  176. package/lib/serviceBase/services.d.ts +63 -0
  177. package/lib/serviceBase/services.js +346 -0
  178. package/lib/serviceBase/services.js.map +1 -0
  179. package/lib/tests.d.ts +27 -0
  180. package/lib/tests.js +44 -0
  181. package/lib/tests.js.map +1 -0
  182. package/package.json +91 -0
@@ -0,0 +1,666 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Tools = void 0;
4
+ // THIS FILE IS SUBJECT TO COPYRIGHT FROM THE SOURCE - https://github.com/BetterCorp/Node-Tools.git
5
+ // @bettercorp/tools
6
+ const interfaces_1 = require("../interfaces");
7
+ /**
8
+ * Just a bunch of utility functions - some are used within the framework, others are just general purpose.
9
+ * You can use any of these functions instead of writing your own or importing from an additional library.
10
+ *
11
+ * This class only has static methods, so don't going creating instances of it.
12
+ *
13
+ * If you want to use it, like for isNullOrUndefined, you can just call it directly on the class: `Tools.isNullOrUndefined(value)`.
14
+ * @category Tools
15
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html | API: Tools}
16
+ */
17
+ class Tools {
18
+ /**
19
+ * @hidden
20
+ */
21
+ constructor() {
22
+ throw new Error("This class is not meant to be instantiated");
23
+ }
24
+ /**
25
+ * Predefined regular expressions for common string cleaning operations.
26
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#regexes | API: Tools#regexes}
27
+ */
28
+ static regexes = {
29
+ exhard: /(?![A-Za-z0-9])[\W_]/g,
30
+ hard: /(?![,-:~_])[\W]/g,
31
+ soft: /(?![,-:~ +_.@])[\W]/g,
32
+ url: /(?![,-:~ +_.@\/\?=&%])[\W]/g,
33
+ ip: /(?![.0-9:%/])[\W_]/g,
34
+ email: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/g,
35
+ };
36
+ /**
37
+ * Clean and sanitize a string by removing unwanted characters based on specified strength.
38
+ * @param objectToClean - The object/string to clean
39
+ * @param maxLimit - Maximum character limit (default: 255)
40
+ * @param strength - Cleaning strength or custom regex (default: CleanStringStrength.hard)
41
+ * @param returnNullAndUndefined - Whether to return null/undefined for those values (default: false)
42
+ * @param customRegex - Custom regex when using CleanStringStrength.custom
43
+ * @returns The cleaned string, or null/undefined if returnNullAndUndefined is true
44
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#cleanString | API: Tools#cleanString}
45
+ */
46
+ static cleanString(objectToClean, maxLimit = 255, strength = interfaces_1.CleanStringStrength.hard, returnNullAndUndefined = false, customRegex) {
47
+ let regx = Tools.regexes.hard;
48
+ if (strength.test !== undefined) {
49
+ regx = strength;
50
+ }
51
+ else {
52
+ switch (strength) {
53
+ case interfaces_1.CleanStringStrength.exhard:
54
+ regx = Tools.regexes.exhard;
55
+ break;
56
+ case interfaces_1.CleanStringStrength.soft:
57
+ regx = Tools.regexes.soft;
58
+ break;
59
+ case interfaces_1.CleanStringStrength.url:
60
+ regx = Tools.regexes.url;
61
+ break;
62
+ case interfaces_1.CleanStringStrength.ip:
63
+ regx = Tools.regexes.ip;
64
+ break;
65
+ case interfaces_1.CleanStringStrength.email:
66
+ regx = Tools.regexes.email;
67
+ break;
68
+ case interfaces_1.CleanStringStrength.custom:
69
+ if (Tools.isUndefined(customRegex)) {
70
+ throw "No custom regex provided!";
71
+ }
72
+ regx = customRegex;
73
+ break;
74
+ }
75
+ }
76
+ let data = `${objectToClean}`
77
+ .trim()
78
+ .replace(regx, "")
79
+ .trim()
80
+ .substring(0, maxLimit ?? 255);
81
+ if (data === "undefined") {
82
+ return returnNullAndUndefined === true ? undefined : "";
83
+ }
84
+ if (data === "null") {
85
+ return returnNullAndUndefined === true ? null : "";
86
+ }
87
+ return data;
88
+ }
89
+ /**
90
+ * Automatically capitalize the first letter of each word in a string.
91
+ * @param data - The string to capitalize
92
+ * @returns The string with each word capitalized
93
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#autoCapitalizeWords | API: Tools#autoCapitalizeWords}
94
+ */
95
+ static autoCapitalizeWords(data) {
96
+ const words = data.split(" ");
97
+ for (let i = 0; i < words.length; i++) {
98
+ words[i] = words[i][0].toUpperCase() + words[i].substring(1);
99
+ }
100
+ return words.join(" ");
101
+ }
102
+ /**
103
+ * Get the string keys from an enum object, filtering out numeric keys.
104
+ * @param obj - The enum object
105
+ * @returns Array of string keys
106
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#enumKeys | API: Tools#enumKeys}
107
+ */
108
+ static enumKeys(obj) {
109
+ return Object.keys(obj)
110
+ .filter((k) => Number.isNaN(+k));
111
+ }
112
+ /**
113
+ * @hidden
114
+ */
115
+ static _flattenObject(obj) {
116
+ // CREDITS: https://gist.github.com/penguinboy/762197
117
+ let tempA = {};
118
+ for (let i in obj) {
119
+ if (Tools.isObject(obj[i]) || Tools.isArray(obj[i])) {
120
+ let tempB = this._flattenObject(obj[i]);
121
+ for (let j in tempB) {
122
+ tempA[i + "." + j] = tempB[j];
123
+ }
124
+ }
125
+ else {
126
+ tempA[i] = obj[i];
127
+ }
128
+ }
129
+ return tempA;
130
+ }
131
+ /**
132
+ * Flatten a nested object into a single level with dot notation keys.
133
+ * @param obj - The object to flatten
134
+ * @returns The flattened object
135
+ * @throws Error if the input is not a valid object
136
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#flattenObject | API: Tools#flattenObject}
137
+ */
138
+ static flattenObject(obj) {
139
+ if (!this.isObject(obj)) {
140
+ throw "Not a valid object!";
141
+ }
142
+ return this._flattenObject(obj);
143
+ }
144
+ /**
145
+ * Get hierarchical availability of objects based on key-parent relationships.
146
+ * @param listOfObjects - Array of objects to search through
147
+ * @param key - The key property name
148
+ * @param parentkey - The parent key property name
149
+ * @param value - The value to match against
150
+ * @returns Array of matching objects including hierarchical children
151
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#hierachialGetAvailibility | API: Tools#hierachialGetAvailibility}
152
+ */
153
+ static hierachialGetAvailibility(listOfObjects, key, parentkey, value) {
154
+ let listToReturn = [];
155
+ for (let thisType of listOfObjects) {
156
+ if (thisType[key] === value) {
157
+ listToReturn.push(thisType);
158
+ }
159
+ else if (thisType[parentkey] === value) {
160
+ for (let iItem of this.hierachialGetAvailibility(listOfObjects, key, parentkey, thisType[key])) {
161
+ listToReturn.push(iItem);
162
+ }
163
+ }
164
+ }
165
+ return listToReturn;
166
+ }
167
+ /**
168
+ * Decode a base64 data URL string and extract the image type and data.
169
+ * @param dataString - Base64 data URL string (e.g., "data:image/png;base64,...")
170
+ * @returns Object with type and data properties, or Error if invalid
171
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#decodeBase64Image | API: Tools#decodeBase64Image}
172
+ */
173
+ static decodeBase64Image(dataString) {
174
+ let matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/), response = {};
175
+ if (this.isNullOrUndefined(matches) || matches.length !== 3) {
176
+ return new Error("Invalid input string");
177
+ }
178
+ response.type = matches[1];
179
+ response.data = Buffer.from(matches[2], "base64");
180
+ return response;
181
+ }
182
+ static GetValueFromObjectBasedOnStringPathSearcher(workingObj, stringToGet) {
183
+ if (this.isNullOrUndefined(workingObj)) {
184
+ return null;
185
+ }
186
+ if (this.isNullOrUndefined(stringToGet)) {
187
+ return null;
188
+ }
189
+ // new version? requires more tests
190
+ /*return stringToGet
191
+ .replace(/\[([^[\]]*)]/g, ".$1.")
192
+ .split(".")
193
+ .filter((prop) => prop !== "")
194
+ .reduce(
195
+ (prev, next) => (prev instanceof Object ? prev[next] : undefined),
196
+ workingObj
197
+ );*/
198
+ let splitted = stringToGet.split(".", 2);
199
+ if (splitted.length === 1) {
200
+ if (splitted[0] === "*") {
201
+ let data = [];
202
+ for (let iI of Object.keys(workingObj)) {
203
+ if (this.isArray(workingObj[iI])) {
204
+ for (let iX of workingObj[iI]) {
205
+ data.push({
206
+ _GVRef: iI,
207
+ ...iX,
208
+ });
209
+ }
210
+ }
211
+ else {
212
+ data.push({
213
+ _GVRef: iI,
214
+ ...workingObj[iI],
215
+ });
216
+ }
217
+ }
218
+ return data;
219
+ }
220
+ return workingObj[splitted[0]];
221
+ }
222
+ return this.GetValueFromObjectBasedOnStringPath(workingObj[splitted[0]], stringToGet.replace(splitted[0] + ".", ""));
223
+ }
224
+ /**
225
+ * Get a value from a nested object using a string path (e.g., "user.profile.name").
226
+ * Supports comma-separated paths for concatenation and "*" wildcard for all properties.
227
+ * @param workingObj - The object to search in
228
+ * @param stringToGet - Dot-notation path string or comma-separated paths
229
+ * @returns The value at the specified path, or null if not found
230
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#GetValueFromObjectBasedOnStringPath | API: Tools#GetValueFromObjectBasedOnStringPath}
231
+ */
232
+ static GetValueFromObjectBasedOnStringPath(workingObj, stringToGet) {
233
+ if (this.isNullOrUndefined(stringToGet)) {
234
+ return null;
235
+ }
236
+ let finalString = "";
237
+ let splitObj = stringToGet.split(",");
238
+ if (splitObj.length === 1) {
239
+ let retData = this.GetValueFromObjectBasedOnStringPathSearcher(workingObj, stringToGet);
240
+ return this.isNullOrUndefined(retData)
241
+ ? retData
242
+ : JSON.parse(JSON.stringify(retData));
243
+ }
244
+ for (let val of splitObj) {
245
+ if (this.isNullOrUndefined(stringToGet)) {
246
+ continue;
247
+ }
248
+ let retData = this.GetValueFromObjectBasedOnStringPathSearcher(workingObj, val);
249
+ let data = this.isNullOrUndefined(retData)
250
+ ? retData
251
+ : JSON.parse(JSON.stringify(retData));
252
+ if (this.isUndefined(data)) {
253
+ finalString += val;
254
+ }
255
+ else {
256
+ finalString += data;
257
+ }
258
+ }
259
+ return finalString;
260
+ }
261
+ /**
262
+ * Merge two objects deeply, with the second object taking precedence.
263
+ * @param src - Source object to merge into
264
+ * @param against - Object to merge from (takes precedence)
265
+ * @param initialMigration - Whether to clone objects before merging (default: true)
266
+ * @param referenceKey - Optional reference key for merge operations
267
+ * @returns The merged object
268
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#mergeObjects | API: Tools#mergeObjects}
269
+ */
270
+ static mergeObjects(src, against, initialMigration = true, referenceKey) {
271
+ if (!src) {
272
+ return against;
273
+ }
274
+ if (!against) {
275
+ return src;
276
+ }
277
+ if (this.isNullOrUndefined(initialMigration) || initialMigration === true) {
278
+ let clonedObj1 = JSON.parse(JSON.stringify(src));
279
+ let obj2String = JSON.stringify(against);
280
+ let clonedObj2 = JSON.parse(obj2String);
281
+ return this.mergeObjects(clonedObj1, clonedObj2, false);
282
+ }
283
+ if (this.isArray(src) && this.isArray(against)) {
284
+ for (let item of against) {
285
+ src.push(item);
286
+ }
287
+ return src;
288
+ }
289
+ for (let prop of Object.keys(against)) {
290
+ let srcProp = src[prop];
291
+ let againstProp = against[prop];
292
+ if (this.isObject(againstProp) && !this.isNullOrUndefined(srcProp)) {
293
+ src[prop] = this.mergeObjects(srcProp, againstProp, false);
294
+ }
295
+ else {
296
+ src[prop] = againstProp;
297
+ }
298
+ }
299
+ return src;
300
+ }
301
+ /**
302
+ * Replace placeholders in a string with values from an object using {key} syntax.
303
+ * @param obj - Object containing replacement values
304
+ * @param str - String with placeholders (e.g., "Hello {name}")
305
+ * @returns String with placeholders replaced by object values
306
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#StringReplaceWithObject | API: Tools#StringReplaceWithObject}
307
+ */
308
+ static StringReplaceWithObject(obj, str) {
309
+ let strToReplace = str;
310
+ if (strToReplace.indexOf("{") >= 0) {
311
+ let strSplt = strToReplace.split("{");
312
+ let strSplt2 = strSplt[1].split("}");
313
+ let newVal = this.GetValueFromObjectBasedOnStringPath(obj, strSplt2[0]);
314
+ strToReplace =
315
+ strSplt[0] +
316
+ newVal +
317
+ strSplt2.splice(1)
318
+ .join("}") +
319
+ (strSplt.length > 2 ? "{" : "") +
320
+ strSplt.splice(2)
321
+ .join("{");
322
+ strToReplace = this.StringReplaceWithObject(obj, strToReplace);
323
+ }
324
+ return strToReplace;
325
+ }
326
+ /**
327
+ * Convert milliseconds to a human-readable time string.
328
+ * @param time - Time in milliseconds
329
+ * @returns Human-readable time string (e.g., "5 minutes", "2 hours")
330
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#getTimeFromMilliseconds | API: Tools#getTimeFromMilliseconds}
331
+ */
332
+ static getTimeFromMilliseconds(time) {
333
+ if (time < 1000) {
334
+ return `${time} milliseconds`;
335
+ }
336
+ let seconds = time / 1000;
337
+ if (seconds < 60) {
338
+ return `${seconds} seconds`;
339
+ }
340
+ const minutes = seconds / 60;
341
+ if (minutes < 60) {
342
+ return `${minutes} minutes`;
343
+ }
344
+ const hours = minutes / 60;
345
+ if (hours < 60) {
346
+ return `${hours} hours`;
347
+ }
348
+ return `${hours / 24} days`;
349
+ }
350
+ /**
351
+ * Create a delay/sleep for the specified number of milliseconds.
352
+ * @param time - Time to delay in milliseconds (default: 1000)
353
+ * @returns Promise that resolves after the specified time
354
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#delay | API: Tools#delay}
355
+ */
356
+ static delay(time = 1000) {
357
+ return new Promise((resolve, reject) => {
358
+ setTimeout(resolve, time);
359
+ });
360
+ }
361
+ /**
362
+ * Wait with delays while checking a condition, throwing an error on timeout.
363
+ * @param checkFunc - Function that returns true while waiting should continue
364
+ * @param rejectFunc - Function to call on timeout (before throwing)
365
+ * @param time - Delay between checks in milliseconds (default: 1000)
366
+ * @param timeout - Maximum number of check attempts (default: 10)
367
+ * @throws "Timeout!" when the timeout is exceeded
368
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#waitDelayThenThrow | API: Tools#waitDelayThenThrow}
369
+ */
370
+ static async waitDelayThenThrow(checkFunc, rejectFunc, time = 1000, timeout = 10) {
371
+ let count = 0;
372
+ const causeTimeout = () => {
373
+ count = timeout + 1;
374
+ };
375
+ while (checkFunc(causeTimeout)) {
376
+ count++;
377
+ if (count > timeout && rejectFunc) {
378
+ rejectFunc("Timeout!");
379
+ }
380
+ if (count > timeout) {
381
+ throw "Timeout!";
382
+ }
383
+ await this.delay(time);
384
+ }
385
+ }
386
+ /**
387
+ * Check if a value is a simple primitive type (string, number, or boolean).
388
+ * @param value - The value to check
389
+ * @returns True if the value is a string, number, or boolean
390
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isSimpleType | API: Tools#isSimpleType}
391
+ */
392
+ static isSimpleType(value) {
393
+ return (Tools.isBoolean(value) || Tools.isNumber(value) || Tools.isString(value));
394
+ }
395
+ /**
396
+ * Type guard to check if a value is a string.
397
+ * @param value - The value to check
398
+ * @returns True if the value is a string
399
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isString | API: Tools#isString}
400
+ */
401
+ static isString(value) {
402
+ return typeof value === "string" || value instanceof String;
403
+ }
404
+ /**
405
+ * Type guard to check if a value is a Date object.
406
+ * @param value - The value to check
407
+ * @param matchString - Currently unused parameter for potential string date matching
408
+ * @returns True if the value is a Date instance
409
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isDate | API: Tools#isDate}
410
+ */
411
+ static isDate(value, matchString = true) {
412
+ return value instanceof Date; /*
413
+ ? true
414
+ : matchString
415
+ ? this.dateTimeRegex.test(`${value}`)
416
+ : false*/
417
+ }
418
+ /**
419
+ * Type guard to check if a value is an array.
420
+ * @param value - The value to check
421
+ * @returns True if the value is an array
422
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isArray | API: Tools#isArray}
423
+ */
424
+ static isArray(value) {
425
+ return (!Tools.isNullOrUndefined(value) &&
426
+ Tools.TypeofObjectConstructor(value, "array") &&
427
+ !Tools.isNullOrUndefined(value.length));
428
+ }
429
+ /**
430
+ * Type guard to check if a value is a function.
431
+ * @param value - The value to check
432
+ * @returns True if the value is a function
433
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isFunction | API: Tools#isFunction}
434
+ */
435
+ static isFunction(value) {
436
+ return typeof value === "function";
437
+ }
438
+ /**
439
+ * Type guard to check if a value is a symbol.
440
+ * @param value - The value to check
441
+ * @returns True if the value is a symbol
442
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isSymbol | API: Tools#isSymbol}
443
+ */
444
+ static isSymbol(value) {
445
+ return typeof value === "symbol";
446
+ }
447
+ /**
448
+ * Type guard to check if a value is a valid number (not NaN).
449
+ * @param value - The value to check
450
+ * @returns True if the value is a number and not NaN
451
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isNumber | API: Tools#isNumber}
452
+ */
453
+ static isNumber(value) {
454
+ return typeof value === "number" && !isNaN(value);
455
+ }
456
+ /**
457
+ * Check if a value can be parsed as a valid number and return the parsed result.
458
+ * @param value - The value to check and parse
459
+ * @returns Object with status (true if valid) and value (the parsed number)
460
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isStringNumber | API: Tools#isStringNumber}
461
+ */
462
+ static isStringNumber(value) {
463
+ if (Tools.isNumber(value)) {
464
+ return { status: true, value: value };
465
+ }
466
+ try {
467
+ const valueAsString = `${value}`;
468
+ if (valueAsString.split(".").length > 2) {
469
+ return { status: false };
470
+ }
471
+ if (valueAsString.split(",").length > 2) {
472
+ return { status: false };
473
+ }
474
+ if (!/^[0-9 ,.\-]{1,}$/g.test(valueAsString)) {
475
+ return { status: false };
476
+ }
477
+ let nValue = Number.parseFloat(valueAsString);
478
+ if (Tools.isNumber(nValue)) {
479
+ return { status: true, value: nValue };
480
+ }
481
+ }
482
+ catch (EIgnore) {
483
+ }
484
+ return { status: false };
485
+ }
486
+ /**
487
+ * Type guard to check if a value is a boolean.
488
+ * @param value - The value to check
489
+ * @returns True if the value is a boolean
490
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isBoolean | API: Tools#isBoolean}
491
+ */
492
+ static isBoolean(value) {
493
+ return typeof value === "boolean";
494
+ }
495
+ /**
496
+ * Type guard to check if a value is undefined.
497
+ * @param value - The value to check
498
+ * @returns True if the value is undefined
499
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isUndefined | API: Tools#isUndefined}
500
+ */
501
+ static isUndefined(value) {
502
+ return typeof value === "undefined";
503
+ }
504
+ /**
505
+ * Type guard to check if a value is null.
506
+ * @param value - The value to check
507
+ * @returns True if the value is null
508
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isNull | API: Tools#isNull}
509
+ */
510
+ static isNull(value) {
511
+ if (value === null) {
512
+ return true;
513
+ }
514
+ return false;
515
+ }
516
+ /**
517
+ * Type guard to check if a value is a plain object (not array, null, etc.).
518
+ * @param value - The value to check
519
+ * @returns True if the value is a plain object
520
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isObject | API: Tools#isObject}
521
+ */
522
+ static isObject(value) {
523
+ return Tools.TypeofObjectConstructor(value, "object");
524
+ }
525
+ /**
526
+ * Type guard to check object constructor type (array or object).
527
+ * @param value - The value to check
528
+ * @param type - The type to check for ("array" or "object")
529
+ * @returns True if the value matches the specified constructor type
530
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#TypeofObjectConstructor | API: Tools#TypeofObjectConstructor}
531
+ */
532
+ static TypeofObjectConstructor(value, type) {
533
+ if (Tools.isNullOrUndefined(value)) {
534
+ return false;
535
+ }
536
+ if (type === "array") {
537
+ return typeof value === "object" && value.constructor === Array;
538
+ }
539
+ if (type === "object") {
540
+ return typeof value === "object" && value.constructor === Object;
541
+ }
542
+ return false;
543
+ }
544
+ /**
545
+ * Type guard to check if a value is a plain object with string keys.
546
+ * @param value - The value to check
547
+ * @returns True if the value is a plain object
548
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isPlainObject | API: Tools#isPlainObject}
549
+ */
550
+ static isPlainObject(value) {
551
+ return Tools.isObject(value);
552
+ }
553
+ /**
554
+ * Type guard to check if a value is null or undefined.
555
+ * @param value - The value to check
556
+ * @returns True if the value is null or undefined
557
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#isNullOrUndefined | API: Tools#isNullOrUndefined}
558
+ */
559
+ static isNullOrUndefined(value) {
560
+ if (Tools.isUndefined(value)) {
561
+ return true;
562
+ }
563
+ if (Tools.isNull(value)) {
564
+ return true;
565
+ }
566
+ return false;
567
+ }
568
+ /**
569
+ * Generate a random integer between min and max (inclusive).
570
+ * @param min - Minimum value (inclusive)
571
+ * @param max - Maximum value (inclusive)
572
+ * @returns Random integer between min and max
573
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#genRandomNumber | API: Tools#genRandomNumber}
574
+ */
575
+ static genRandomNumber(min, max) {
576
+ return Math.floor(Math.random() * (+max - +min)) + +min;
577
+ }
578
+ /**
579
+ * Clamp a number between a minimum and maximum value.
580
+ * @param min - Minimum allowed value
581
+ * @param max - Maximum allowed value
582
+ * @param value - Value to clamp
583
+ * @returns The clamped value
584
+ * @throws Error if min is greater than max
585
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#clampNumber | API: Tools#clampNumber}
586
+ */
587
+ static clampNumber(min, max, value) {
588
+ if (min > max) {
589
+ throw new Error("min cannot be greater than max");
590
+ }
591
+ return value < min ? min : value > max ? max : value;
592
+ }
593
+ /**
594
+ * Sleep/delay execution for the specified number of milliseconds.
595
+ * @param milliseconds - Time to sleep in milliseconds (default: 1000)
596
+ * @returns Promise that resolves after the specified time
597
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#sleep | API: Tools#sleep}
598
+ */
599
+ static async sleep(milliseconds = 1000) {
600
+ await new Promise((r) => setTimeout(r, milliseconds));
601
+ }
602
+ /**
603
+ * Collection of utility functions for working with arrays.
604
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#arrays | API: Tools#arrays}
605
+ */
606
+ static arrays = {
607
+ /**
608
+ * Asynchronously map over an array with async callback functions.
609
+ * @param arr - The array to map over
610
+ * @param asyncCallback - Async function to call for each item
611
+ * @returns Promise resolving to the mapped array
612
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#arrays | API: Tools#arrays}
613
+ */
614
+ mapAsync: async (arr, asyncCallback) => {
615
+ return await Promise.all(arr.map(async (item) => {
616
+ return await asyncCallback(item);
617
+ }));
618
+ },
619
+ /**
620
+ * Group array items by a key generated from a function.
621
+ * @param groupFunc - Function that returns a string key for grouping
622
+ * @param list - Array to group
623
+ * @returns Object with keys as group names and values as arrays of grouped items
624
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#arrays | API: Tools#arrays}
625
+ */
626
+ groupListBy: (groupFunc, list) => {
627
+ return list.reduce((prev, next) => ({
628
+ ...prev,
629
+ [groupFunc(next)]: [
630
+ ...(prev[groupFunc(next)] || []),
631
+ next,
632
+ ],
633
+ }), {});
634
+ },
635
+ /**
636
+ * Collect array items into groups using a grouping function, returning only the grouped arrays.
637
+ * @param groupFunc - Function that returns a string key for grouping
638
+ * @param list - Array to collect
639
+ * @returns Array of arrays where each sub-array contains grouped items
640
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#arrays | API: Tools#arrays}
641
+ */
642
+ collectListBy: (groupFunc, list) => {
643
+ return Object.values(Tools.arrays.groupListBy(groupFunc, list));
644
+ },
645
+ /**
646
+ * Get the first item in the array.
647
+ * @param list - The array to get the first item from
648
+ * @returns The first item or undefined if array is empty
649
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#arrays | API: Tools#arrays}
650
+ */
651
+ head: (list) => {
652
+ return list[0];
653
+ },
654
+ /**
655
+ * Get the last item in the array.
656
+ * @param list - The array to get the last item from
657
+ * @returns The last item or undefined if array is empty
658
+ * @see {@link https://bsbcode.dev/languages/nodejs/types/classes/Tools.html#arrays | API: Tools#arrays}
659
+ */
660
+ tail: (list) => {
661
+ return list[list.length - 1];
662
+ },
663
+ };
664
+ }
665
+ exports.Tools = Tools;
666
+ //# sourceMappingURL=tools.js.map