@creejs/commons-lang 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1532 @@
1
+ /**
2
+ * @module LangUtils
3
+ * @description Language utility functions
4
+ */
5
+
6
+ var LangUtils = {
7
+ constructorName,
8
+ defaults,
9
+ extend,
10
+ extends: extend,
11
+ equals,
12
+ isBrowser,
13
+ isNode
14
+ };
15
+
16
+ /**
17
+ * Gets the constructor name of a value.
18
+ * @param {*} value - The value to check.
19
+ * @returns {string|undefined} The constructor name, or undefined if value has no constructor.
20
+ */
21
+ function constructorName (value) {
22
+ return value?.constructor?.name
23
+ }
24
+
25
+ /**
26
+ * Assigns default values from source objects to target object for undefined properties.
27
+ * @param {Object<string, any>} target - The target object to assign defaults to
28
+ * @param {...Object<string, any>} sources - Source objects containing default values
29
+ * @returns {Object<string, any>} The modified target object with defaults applied
30
+ * @throws {TypeError} If target is null or undefined
31
+ */
32
+ function defaults (target, ...sources) {
33
+ if (target == null) {
34
+ throw new TypeError('"target" must not be null or undefined')
35
+ }
36
+ for (const source of sources) {
37
+ if (source == null) {
38
+ continue
39
+ }
40
+ for (const key in source) {
41
+ if (target[key] === undefined) {
42
+ target[key] = source[key];
43
+ }
44
+ }
45
+ }
46
+ return target
47
+ }
48
+
49
+ /**
50
+ * Extends a target object with properties from one or more source objects.
51
+ * @param {Object<string, any>} target - The target object to extend (must not be null/undefined)
52
+ * @param {...Object<string, any>} sources - One or more source objects to copy properties from
53
+ * @returns {Object<string, any>} The modified target object
54
+ * @throws {TypeError} If target is null or undefined
55
+ */
56
+ function extend (target, ...sources) {
57
+ if (target == null) {
58
+ throw new TypeError('"target" must not be null or undefined')
59
+ }
60
+ for (const source of sources) {
61
+ if (source == null) {
62
+ continue
63
+ }
64
+ for (const key in source) {
65
+ target[key] = source[key];
66
+ }
67
+ }
68
+ return target
69
+ }
70
+
71
+ /**
72
+ * Compares two values for equality
73
+ * 1. First checks strict equality (===),
74
+ * 2. then checks if either value has an `equals` method and uses it.
75
+ * @param {*} value1 - First value to compare
76
+ * @param {*} value2 - Second value to compare
77
+ * @returns {boolean} True if values are equal, false otherwise
78
+ */
79
+ function equals (value1, value2) {
80
+ if (value1 === value2) {
81
+ return true
82
+ }
83
+ if (typeof value1?.equals === 'function') {
84
+ return value1.equals(value2)
85
+ }
86
+ if (typeof value2?.equals === 'function') {
87
+ return value2.equals(value1)
88
+ }
89
+ return false
90
+ }
91
+
92
+ /**
93
+ * Check if the current environment is a browser
94
+ * @returns {boolean}
95
+ */
96
+ function isBrowser () {
97
+ return typeof window !== 'undefined' && typeof document !== 'undefined'
98
+ }
99
+
100
+ /**
101
+ * Check if the current environment is a nodejs
102
+ * @returns {boolean}
103
+ */
104
+ function isNode () {
105
+ return !isBrowser()
106
+ }
107
+
108
+ /**
109
+ * @module TypeUtils
110
+ * @description Utility functions for type checking and validation.
111
+ */
112
+ var TypeUtils = {
113
+ isArray,
114
+ isBoolean,
115
+ isBuffer,
116
+ isFunction,
117
+ isInstance,
118
+ isIterable,
119
+ isDate,
120
+ isError,
121
+ isMap,
122
+ isWeakMap,
123
+ isNumber,
124
+ isPositive,
125
+ isNegative,
126
+ isNil,
127
+ isNullOrUndefined,
128
+ isNull,
129
+ isUndefined,
130
+ isPlainObject: isPlainObject$1,
131
+ isObject,
132
+ isPromise,
133
+ isRegExp,
134
+ isSet,
135
+ isWeakSet,
136
+ isStream,
137
+ isString,
138
+ isSymbol,
139
+ isPrimitive
140
+ };
141
+ /**
142
+ * Checks if the given value is an array.
143
+ * @param {*} value - The value to check.
144
+ * @returns {boolean} True if the value is an array, false otherwise.
145
+ */
146
+ function isArray (value) {
147
+ return Array.isArray(value)
148
+ }
149
+
150
+ /**
151
+ * Checks if the given value is a boolean.
152
+ * @param {*} value - The value to check.
153
+ * @returns {boolean} True if the value is a boolean, false otherwise.
154
+ */
155
+ function isBoolean (value) {
156
+ return typeof value === 'boolean'
157
+ }
158
+
159
+ /**
160
+ * Checks if the given value is a Buffer.
161
+ * @param {*} value - The value to check.
162
+ * @returns {boolean} True if the value is a Buffer, false otherwise.
163
+ */
164
+ function isBuffer (value) {
165
+ return value != null && Buffer.isBuffer(value)
166
+ }
167
+
168
+ /**
169
+ * Checks if the given value is a Date.
170
+ * @param {*} value - The value to check.
171
+ * @returns {boolean} True if the value is a Date, false otherwise.
172
+ */
173
+ function isDate (value) {
174
+ return value != null && value instanceof Date
175
+ }
176
+
177
+ /**
178
+ * Checks if the given value is an instance of Error.
179
+ * @param {*} value - The value to check.
180
+ * @returns {boolean} True if the value is an Error, false otherwise.
181
+ */
182
+ function isError (value) {
183
+ return value != null && value instanceof Error
184
+ }
185
+
186
+ /**
187
+ * Checks if the given value is a function.
188
+ * @param {*} value - The value to check.
189
+ * @returns {boolean} True if the value is a function, false otherwise.
190
+ */
191
+ function isFunction (value) {
192
+ return typeof value === 'function'
193
+ }
194
+
195
+ /**
196
+ * Checks if a value is a class instance (non-null and not a plain object).
197
+ * @param {*} value - The value to check.
198
+ * @returns {boolean} True if the value is a class instance, false otherwise.
199
+ */
200
+ function isInstance (value) {
201
+ return value != null && typeof value === 'object' && !isPlainObject$1(value)
202
+ }
203
+
204
+ /**
205
+ * Checks if a value is isIterable
206
+ * @param {*} value - The value to check.
207
+ * @returns {boolean} True if the value is isIterable, false otherwise.
208
+ */
209
+ function isIterable (value) {
210
+ return value != null && typeof value[Symbol.iterator] === 'function'
211
+ }
212
+
213
+ /**
214
+ * Checks if a value is Map
215
+ * @param {*} value - The value to check.
216
+ * @returns {boolean} True if the value is Map, otherwise false.
217
+ */
218
+ function isMap (value) {
219
+ return value != null && typeof value === 'object' && value.constructor === Map
220
+ }
221
+
222
+ /**
223
+ * Checks if a value is WeakMap
224
+ * @param {*} value - The value to check.
225
+ * @returns {boolean} True if the value is WeakMap, otherwise false.
226
+ */
227
+ function isWeakMap (value) {
228
+ return value != null && typeof value === 'object' && value.constructor === WeakMap
229
+ }
230
+
231
+ /**
232
+ * Checks if a value is null or undefined.
233
+ * 1. value == null
234
+ * 2. return true, if value is null or undefined
235
+ * @param {*} value - The value to check.
236
+ * @returns {boolean} True if the value is null or undefined, otherwise false.
237
+ */
238
+ function isNil (value) {
239
+ return value == null
240
+ }
241
+
242
+ /**
243
+ * Checks if a value is null or undefined.
244
+ * 1. same with isNil()
245
+ * @param {*} value - The value to check.
246
+ * @returns {boolean} True if the value is null or undefined, otherwise false.
247
+ */
248
+ function isNullOrUndefined (value) {
249
+ return value == null
250
+ }
251
+
252
+ /**
253
+ * check that a value is a positive number.
254
+ * @param {number} value - The value to check.
255
+ * @returns {boolean}
256
+ */
257
+ function isPositive (value) {
258
+ if (!isNumber(value)) {
259
+ return false
260
+ }
261
+ return value > 0
262
+ }
263
+
264
+ /**
265
+ * check that a value is a Negative number.
266
+ * @param {number} value - The value to check.
267
+ */
268
+ function isNegative (value) {
269
+ if (!isNumber(value)) {
270
+ return false
271
+ }
272
+ return value < 0
273
+ }
274
+
275
+ /**
276
+ * Checks if the given value is exactly null.
277
+ * @param {*} value - The value to check.
278
+ * @returns {boolean} True if the value is null, false otherwise.
279
+ */
280
+ function isNull (value) {
281
+ return value === null
282
+ }
283
+
284
+ /**
285
+ * Checks if a value is exactly undefined.
286
+ * @param {*} value - The value to check.
287
+ * @returns {boolean} True if the value is undefined, false otherwise.
288
+ */
289
+ function isUndefined (value) {
290
+ return value === undefined
291
+ }
292
+
293
+ /**
294
+ * Checks if a value is a number.
295
+ * @param {*} value - The value to check.
296
+ * @returns {boolean} True if the value is a number, false otherwise.
297
+ */
298
+ function isNumber (value) {
299
+ return value != null && typeof value === 'number'
300
+ }
301
+
302
+ /**
303
+ * Checks if a value is an object (and not null).
304
+ * @param {*} value - The value to check
305
+ * @returns {boolean} True if the value is an object (not null), false otherwise
306
+ */
307
+ function isObject (value) {
308
+ return value != null && typeof value === 'object'
309
+ }
310
+
311
+ /**
312
+ * Checks if a value is a plain object (created by the Object constructor).
313
+ * @param {*} value - The value to check.
314
+ * @returns {boolean} True if the value is a plain object, false otherwise.
315
+ */
316
+ function isPlainObject$1 (value) {
317
+ return value !== null && typeof value === 'object' && (value.constructor === Object || value.constructor === undefined)
318
+ }
319
+
320
+ /**
321
+ * check if value is primitive: string, number, boolean
322
+ * 1. null/undefined returns false
323
+ * @param {*} value
324
+ * @returns {boolean}
325
+ */
326
+ function isPrimitive (value) {
327
+ return value !== null && (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
328
+ }
329
+
330
+ /**
331
+ * Checks if a value is a Promise.
332
+ * @param {*} value - The value to check.
333
+ * @returns {boolean} True if the value is a Promise, false otherwise.
334
+ */
335
+ function isPromise (value) {
336
+ return value != null && typeof value.then === 'function'
337
+ }
338
+
339
+ /**
340
+ * Checks if a RegExp
341
+ * @param {*} value - The value to check.
342
+ * @returns {boolean} True if the value is RegExp, otherwise false.
343
+ */
344
+ function isRegExp (value) {
345
+ return value != null && typeof value === 'object' && value.constructor === RegExp
346
+ }
347
+
348
+ /**
349
+ * Checks if a Set
350
+ * @param {*} value - The value to check.
351
+ * @returns {boolean} True if the value is Set, otherwise false.
352
+ */
353
+ function isSet (value) {
354
+ return value != null && typeof value === 'object' && value.constructor === Set
355
+ }
356
+
357
+ /**
358
+ * Checks if a WeakSet
359
+ * @param {*} value - The value to check.
360
+ * @returns {boolean} True if the value is WeakSet, otherwise false.
361
+ */
362
+ function isWeakSet (value) {
363
+ return value != null && typeof value === 'object' && value.constructor === WeakSet
364
+ }
365
+
366
+ /**
367
+ * Check if the value is a string
368
+ * @param {*} value
369
+ * @return {boolean}
370
+ */
371
+ function isStream (value) {
372
+ return value != null && typeof value.pipe === 'function'
373
+ }
374
+
375
+ /**
376
+ * Check if the value is a string
377
+ * @param {*} value
378
+ * @return {boolean}
379
+ */
380
+ function isString (value) {
381
+ return value != null && typeof value === 'string'
382
+ }
383
+
384
+ /**
385
+ * Checks if the given value is a Symbol.
386
+ * @param {*} value - The value to check.
387
+ * @returns {boolean} True if the value is a Symbol, false otherwise.
388
+ */
389
+ function isSymbol (value) {
390
+ return value != null && typeof value === 'symbol'
391
+ }
392
+
393
+ // 3rd
394
+ // internal
395
+ // owned
396
+ /**
397
+ * @module TypeAssert
398
+ * @description Type assertion utility functions for validating data types and throwing errors for invalid types.
399
+ */
400
+ var TypeAssert = {
401
+ assertNumber,
402
+ assertPositive,
403
+ assertNegative,
404
+ assertBoolean,
405
+ assertObject,
406
+ assertPlainObject,
407
+ assertSymbol,
408
+ assertFunction,
409
+ assertInstance,
410
+ assertPromise,
411
+ assertNil,
412
+ assertNotNil,
413
+ assertNull,
414
+ assertNotNull,
415
+ assertUndefined,
416
+ assertString,
417
+ assertArray,
418
+ assertStringOrSymbol
419
+ };
420
+ /**
421
+ * if value is not Array, throw error
422
+ * @param {*} value
423
+ * @param {string} [paramName] - The name of the parameter to check
424
+ * @returns {void}
425
+ * @throws {Error}
426
+ */
427
+ function assertArray (value, paramName) {
428
+ if (!Array.isArray(value)) {
429
+ throw new Error(`${paramName ? paramName + '' : ' '}Not Array: type=${typeof value} value=${JSON.stringify(value)}`)
430
+ }
431
+ }
432
+ /**
433
+ * if value is not a string, throw error
434
+ * @param {*} value
435
+ * @param {string} [paramName] - The name of the parameter to check
436
+ * @returns {void}
437
+ * @throws {Error}
438
+ */
439
+ function assertString (value, paramName) {
440
+ if (!isString(value)) {
441
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not String: type=${typeof value} value=${JSON.stringify(value)}`)
442
+ }
443
+ }
444
+ /**
445
+ * if value is not a Number, throw error
446
+ * @param {*} value
447
+ * @param {string} [paramName] - The name of the parameter to check
448
+ * @returns {void}
449
+ * @throws {Error}
450
+ */
451
+ function assertNumber (value, paramName) {
452
+ if (!isNumber(value)) {
453
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not Number: type=${typeof value} value=${JSON.stringify(value)}`)
454
+ }
455
+ }
456
+
457
+ /**
458
+ * Asserts that a value is a positive number.
459
+ * @param {number} value - The value to check.
460
+ * @param {string} [paramName] - Optional name of the parameter for error message.
461
+ * @throws {Error} If the value is not a number or is less than or equal to zero.
462
+ */
463
+ function assertPositive (value, paramName) {
464
+ if (!isPositive(value)) {
465
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not Positive: ${value}`)
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Asserts that a value is a Negative number.
471
+ * @param {number} value - The value to check.
472
+ * @param {string} [paramName] - Optional name of the parameter for error message.
473
+ * @throws {Error} If the value is not a number or is less than or equal to zero.
474
+ */
475
+ function assertNegative (value, paramName) {
476
+ if (!isNegative(value)) {
477
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not Negative: ${value}`)
478
+ }
479
+ }
480
+
481
+ /**
482
+ * if value is not a string, throw error
483
+ * @param {*} value
484
+ * @param {string} [paramName] - The name of the parameter to check
485
+ * @returns {void}
486
+ * @throws {Error}
487
+ */
488
+ function assertBoolean (value, paramName) {
489
+ if (!isBoolean(value)) {
490
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not Boolean: type=${typeof value} value=${JSON.stringify(value)}`)
491
+ }
492
+ }
493
+ /**
494
+ * if value is not a Object, throw error
495
+ * @param {*} value
496
+ * @param {string} [paramName] - The name of the parameter to check
497
+ * @returns {void}
498
+ * @throws {Error}
499
+ */
500
+ function assertObject (value, paramName) {
501
+ if (!isObject(value)) {
502
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not Object: type=${typeof value} value=${JSON.stringify(value)}`)
503
+ }
504
+ }
505
+ /**
506
+ * if value is not a PlainObject, throw error
507
+ * @param {*} value
508
+ * @param {string} [paramName] - The name of the parameter to check
509
+ * @returns {void}
510
+ * @throws {Error}
511
+ */
512
+ function assertPlainObject (value, paramName) {
513
+ if (!isPlainObject$1(value)) {
514
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not PlainObject: type=${typeof value} value=${JSON.stringify(value)}`)
515
+ }
516
+ }
517
+ /**
518
+ * if value is not a Symbol, throw error
519
+ * @param {*} value
520
+ * @param {string} [paramName] - The name of the parameter to check@param {string} [paramName] - The name of the parameter to check
521
+ * @returns {void}
522
+ * @throws {Error}
523
+ */
524
+ function assertSymbol (value, paramName) {
525
+ if (!isSymbol(value)) {
526
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not Symbol: type=${typeof value} value=${JSON.stringify(value)}`)
527
+ }
528
+ }
529
+ /**
530
+ * if value is not a Function, throw error
531
+ * @param {*} value
532
+ * @param {string} [paramName] - The name of the parameter to check
533
+ * @returns {void}
534
+ * @throws {Error}
535
+ */
536
+ function assertFunction (value, paramName) {
537
+ if (!isFunction(value)) {
538
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not Function: type=${typeof value} value=${JSON.stringify(value)}`)
539
+ }
540
+ }
541
+ /**
542
+ * if value is not a Class instance, throw error
543
+ * @param {*} value
544
+ * @param {string} [paramName] - The name of the parameter to check
545
+ * @returns {void}
546
+ * @throws {Error}
547
+ */
548
+ function assertInstance (value, paramName) {
549
+ if (!isInstance(value)) {
550
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not Class Instance: type=${typeof value} value=${JSON.stringify(value)}`)
551
+ }
552
+ }
553
+ /**
554
+ * if value is not a string, throw error
555
+ * @param {*} value
556
+ * @param {string} [paramName] - The name of the parameter to check
557
+ * @returns {void}
558
+ * @throws {Error}
559
+ */
560
+ function assertPromise (value, paramName) {
561
+ if (!isPromise(value)) {
562
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not Promise: type=${typeof value} value=${JSON.stringify(value)}`)
563
+ }
564
+ }
565
+ /**
566
+ * if value is not a Null or Undefined, throw error
567
+ * @param {*} value
568
+ * @param {string} [paramName] - The name of the parameter to check
569
+ * @returns {void}
570
+ * @throws {Error}
571
+ */
572
+ function assertNil (value, paramName) {
573
+ if (!isNil(value)) {
574
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Neither Null nor Undefined: type=${typeof value} value=${JSON.stringify(value)}`)
575
+ }
576
+ }
577
+
578
+ /**
579
+ * Asserts that the given value is not nil.
580
+ * @param {*} value - The value to check
581
+ * @param {string} [paramName] - The name of the parameter to check
582
+ * @throws {Error} Throws an error if the value is nil
583
+ */
584
+ function assertNotNil (value, paramName) {
585
+ if (isNil(value)) {
586
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Should Not Nil`)
587
+ }
588
+ }
589
+
590
+ /**
591
+ * if value is not a Null, throw error
592
+ * @param {*} value
593
+ * @param {string} [paramName] - The name of the parameter to check
594
+ * @returns {void}
595
+ * @throws {Error}
596
+ */
597
+ function assertNull (value, paramName) {
598
+ if (!isNull(value)) {
599
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not Null: type=${typeof value} value=${JSON.stringify(value)}`)
600
+ }
601
+ }
602
+
603
+ /**
604
+ * Asserts that the given value is not null.
605
+ * @param {*} value - The value to check
606
+ * @param {string} [paramName] - The name of the parameter to check
607
+ * @throws {Error} Throws an error if the value is null
608
+ */
609
+ function assertNotNull (value, paramName) {
610
+ if (isNull(value)) {
611
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Should Not Null`)
612
+ }
613
+ }
614
+ /**
615
+ * if value is not a Undefined, throw error
616
+ * @param {*} value
617
+ * @param {string} [paramName] - The name of the parameter to check
618
+ * @returns {void}
619
+ * @throws {Error}
620
+ */
621
+ function assertUndefined (value, paramName) {
622
+ if (!isUndefined(value)) {
623
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not Undefined: type=${typeof value} value=${JSON.stringify(value)}`)
624
+ }
625
+ }
626
+
627
+ /**
628
+ * Asserts that the given value is either a string or a symbol.
629
+ * @param {*} value - The value to check.
630
+ * @param {string} [paramName] - Optional parameter name for error message.
631
+ * @throws {Error} Throws an error if the value is not a string or symbol.
632
+ */
633
+ function assertStringOrSymbol (value, paramName) {
634
+ if (!isString(value) && !isSymbol(value)) {
635
+ throw new Error(`${paramName ? '"' + paramName + '" ' : ' '}Not String or Symbol: type=${typeof value} value=${JSON.stringify(value)}`)
636
+ }
637
+ }
638
+
639
+ // 3rd
640
+ // internal
641
+ // owned
642
+
643
+ /**
644
+ * @module StringUtils
645
+ * @description Utility functions for string manipulation, validation, and transformation.
646
+ */
647
+ var StringUtils = {
648
+ isEmpty,
649
+ assertNotEmpty,
650
+ isBlank,
651
+ assertNotBlank,
652
+ capitalize,
653
+ decapitalize,
654
+ splitWithFixedLength,
655
+ split,
656
+ findMarkerPositions,
657
+ findMarkerPositionsRegex,
658
+ substringBefore,
659
+ substringBeforeLast,
660
+ substringAfter,
661
+ substringAfterLast,
662
+ substringBetween,
663
+ substringBetweenGreedy,
664
+ substringsBetween
665
+ };
666
+
667
+ /**
668
+ * Checks if a string is null, undefined, or length is 0.
669
+ * @param {string} str
670
+ * @returns {boolean}
671
+ * @throws {Error} If `str` is not null or undefined, and not a string.
672
+ */
673
+ function isEmpty (str) {
674
+ if (str == null) {
675
+ return true
676
+ }
677
+ assertString(str);
678
+ return str.length === 0
679
+ }
680
+
681
+ /**
682
+ * Asserts that the given string is not empty.
683
+ * @param {string} str - The string to check.
684
+ * @throws {Error} Throws an error if the string is empty.
685
+ */
686
+ function assertNotEmpty (str) {
687
+ if (isEmpty(str)) {
688
+ throw new Error(`Empty String: ${str}`)
689
+ }
690
+ }
691
+
692
+ /**
693
+ * Checks if a string is null, undefined, or consists only of whitespace.
694
+ * @param {string} str - The string to check.
695
+ * @returns {boolean} True if the string is blank, false otherwise.
696
+ * @throws {Error} If `str` is not null or undefined, and not a string.
697
+ */
698
+ function isBlank (str) {
699
+ if (str == null) {
700
+ return true
701
+ }
702
+ assertString(str);
703
+ return str.trim().length === 0
704
+ }
705
+
706
+ /**
707
+ * Asserts that the given string is not blank.
708
+ * @param {string} str - The string to check.
709
+ * @throws {Error} Throws an error if the string is blank.
710
+ */
711
+ function assertNotBlank (str) {
712
+ if (isBlank(str)) {
713
+ throw new Error(`Blank String: ${str}`)
714
+ }
715
+ }
716
+
717
+ /**
718
+ * Capitalizes the first character of a string.
719
+ * @param {string} str - The string to capitalize.
720
+ * @returns {string} The capitalized string or original if unchanged.
721
+ */
722
+ function capitalize (str) {
723
+ assertString(str);
724
+ if (str.length === 0) {
725
+ return str
726
+ }
727
+ const char0 = str.charAt(0);
728
+ const upperChar = char0.toUpperCase();
729
+ return char0 === upperChar ? str : upperChar + str.slice(1)
730
+ }
731
+
732
+ /**
733
+ * Converts the first character of a string to lowercase.
734
+ * If the string is null or empty, returns it unchanged.
735
+ * @param {string} str - The input string to decapitalize.
736
+ * @returns {string} The decapitalized string or original if unchanged.
737
+ */
738
+ function decapitalize (str) {
739
+ assertString(str);
740
+ if (str.length === 0) {
741
+ return str
742
+ }
743
+ const char0 = str.charAt(0);
744
+ const lowerChar = char0.toLowerCase();
745
+ return char0 === lowerChar ? str : lowerChar + str.slice(1)
746
+ }
747
+
748
+ /**
749
+ * Splits a string into chunks of fixed length, padding the last chunk if needed.
750
+ * 1. if str is empty, returns an empty array "[]"
751
+ * 2. if length is less than string length, returns an array with the string padded with "padding" as the only element
752
+ * 3. the last chunk is padded with "padding" if needed
753
+ * @param {string} str - The string to split.
754
+ * @param {number} length - The desired length of each chunk.
755
+ * @param {string} [padding=' '] - The padding character for the last chunk.
756
+ * @returns {string[]} An array of string chunks with fixed length.
757
+ * @throws {Error} If `str` is not a string or `length` is not a number.
758
+ */
759
+ function splitWithFixedLength (str, length, padding = ' ') {
760
+ assertString(str);
761
+ assertNumber(length);
762
+ assertString(padding);
763
+ if (str.length === 0) {
764
+ return []
765
+ }
766
+ if (length <= 0) {
767
+ throw new Error('length muse >=0')
768
+ }
769
+ if (str.length < length) {
770
+ return [str.padEnd(length, padding)]
771
+ }
772
+ const chunks = [];
773
+ for (let i = 0; i < str.length; i += length) {
774
+ const splitted = str.substring(i, i + length);
775
+ chunks.push(splitted.padEnd(length, padding));
776
+ }
777
+ return chunks
778
+ }
779
+
780
+ /**
781
+ * Splits a string into chunks using the specified markers.
782
+ * 1. If no markers are provided, defaults to comma (',').
783
+ * 2. null/undefined values are ignored
784
+ * 3. empty array "[]" returned, if string does not include any markers
785
+ * @param {string} str - The string to split.
786
+ * @param {...string} markers - The markers to split the string by.
787
+ * @returns {Array<string>} An array of string chunks.
788
+ * @throws {Error} If the input is not a string.
789
+ */
790
+ function split (str, ...markers) {
791
+ assertString(str);
792
+ const strLength = str.length;
793
+ if (strLength === 0) {
794
+ return []
795
+ }
796
+ const workingMarkers = [...markers];
797
+ if (markers.length === 0) {
798
+ markers.push(',');
799
+ }
800
+ const markerPostionPairs = findMarkerPositionsRegex(str, ...workingMarkers);
801
+ if (markerPostionPairs.length === 0) {
802
+ return []
803
+ }
804
+ const chunks = [];
805
+ let chunk = '';
806
+ let startIndex = 0;
807
+ for (const { marker, index: endIndex } of markerPostionPairs) {
808
+ chunk = str.substring(startIndex, endIndex);
809
+ chunks.push(chunk);
810
+ startIndex = endIndex + marker.length;
811
+ }
812
+ // add rested into chunks
813
+ chunk = str.substring(startIndex);
814
+ chunks.push(chunk);
815
+ return chunks
816
+ }
817
+
818
+ /**
819
+ * Finds all positions of markers in a string.
820
+ * 1. use loop to iterate over markers
821
+ * 2. use sting.indexOf to find position of each marker
822
+ * @param {string} str - The input string to search in.
823
+ * @param {...string} markers - The markers to search for.
824
+ * @returns {Array<{marker: string, index: number}>} Array of objects containing marker and its index.
825
+ * @throws {Error} If `str` is not a string or no markers are provided.
826
+ */
827
+ function findMarkerPositions (str, ...markers) {
828
+ assertString(str);
829
+ if (markers.length === 0) {
830
+ throw new Error('At least one marker must be provided')
831
+ }
832
+
833
+ const positions = [];
834
+ for (const marker of new Set(markers)) { // filter duplicated markers
835
+ if (isEmpty(marker)) { // 'abc'.indexOf('') === 0
836
+ continue
837
+ }
838
+ assertString(marker);
839
+ let index = str.indexOf(marker);
840
+ while (index !== -1) {
841
+ positions.push({ marker, index });
842
+ index = str.indexOf(marker, index + marker.length);
843
+ }
844
+ }
845
+ // Sort positions by index in ascending order
846
+ positions.sort((p1, p2) => p1.index - p2.index);
847
+ return positions
848
+ }
849
+
850
+ /**
851
+ * Finds all positions of markers in a string.
852
+ * 1. Finds all positions of markers in a string using regular expressions.
853
+ * 2. Each marker is included as a separate capture group in a single regex.
854
+ * @param {string} str - The input string to search in.
855
+ * @param {...string} markers - The markers to search for.
856
+ * @returns {Array<{marker: string, index: number}>} Array of objects containing marker and its index.
857
+ * @throws {Error} If `str` is not a string or no markers are provided.
858
+ */
859
+ function findMarkerPositionsRegex (str, ...markers) {
860
+ assertString(str);
861
+ if (markers.length === 0) {
862
+ throw new Error('At least one marker must be provided')
863
+ }
864
+
865
+ // filter duplicated, empty markers
866
+ // Escape special regex characters in markers
867
+ const escapedMarkers = [...new Set(markers.filter(v => v != null))].map(marker => {
868
+ assertString(marker);
869
+ return marker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
870
+ });
871
+
872
+ // Create regex pattern with each marker as a separate capture group
873
+ // Format: (marker1)|(marker2)|(marker3)...
874
+ const pattern = new RegExp(escapedMarkers.map(m => `(${m})`).join('|'), 'g');
875
+
876
+ const positions = [];
877
+ let match = null;
878
+
879
+ // Find all matches
880
+ while ((match = pattern.exec(str)) !== null) {
881
+ // Determine which marker was matched by checking which capture group has a value
882
+ for (let i = 1; i < match.length; i++) {
883
+ if (match[i]) {
884
+ positions.push({
885
+ marker: markers[i - 1], // Use the original marker, not the escaped version
886
+ index: match.index
887
+ });
888
+ break // Only one group will match for each exec call
889
+ }
890
+ }
891
+
892
+ // Avoid infinite loops with zero-width matches
893
+ if (match[0].length === 0) {
894
+ pattern.lastIndex++;
895
+ }
896
+ }
897
+
898
+ return positions
899
+ }
900
+
901
+ /**
902
+ * Returns the substring before the first occurrence of a marker.
903
+ * @param {string} str - The input string to search in.
904
+ * @param {string} marker - The string to search for.
905
+ * @returns {string | undefined} The substring before the marker, or undefined if marker not found.
906
+ * @throws {Error} If either input is not a string.
907
+ */
908
+ function substringBefore (str, marker) {
909
+ assertString(str);
910
+ assertString(marker);
911
+ if (str.length === 0 || marker.length === 0) {
912
+ return
913
+ }
914
+ const index = str.indexOf(marker);
915
+ if (index === -1) {
916
+ return undefined
917
+ }
918
+ return str.substring(0, index)
919
+ }
920
+
921
+ /**
922
+ * Returns the substring before the last occurrence of a marker.
923
+ * @param {string} str
924
+ * @param {string} marker
925
+ * @returns {string | undefined}The substring before the last marker, or undefined if marker not found.
926
+ * @throws {Error} If either input is not a string.
927
+ */
928
+ function substringBeforeLast (str, marker) {
929
+ assertString(str);
930
+ assertString(marker);
931
+ if (str.length === 0 || marker.length === 0) {
932
+ return
933
+ }
934
+ const index = str.lastIndexOf(marker);
935
+ if (index === -1) {
936
+ return
937
+ }
938
+ return str.substring(0, index)
939
+ }
940
+
941
+ /**
942
+ * Returns the substring after the first occurrence of the specified marker.
943
+ * If the marker is not found, returns an empty string.
944
+ *
945
+ * @param {string} str - The string to search in
946
+ * @param {string} marker - The string to search for
947
+ * @returns {string | undefined} The substring after the marker, or undefined if not found
948
+ */
949
+ function substringAfter (str, marker) {
950
+ assertString(str);
951
+ assertString(marker);
952
+ if (str.length === 0 || marker.length === 0) {
953
+ return
954
+ }
955
+ const index = str.indexOf(marker);
956
+ if (index === -1) {
957
+ return
958
+ }
959
+ return str.substring(index + marker.length)
960
+ }
961
+
962
+ /**
963
+ * Returns the substring after the last occurrence of a marker in a string.
964
+ * @param {string} str - The input string to search in.
965
+ * @param {string} marker - The marker to search for.
966
+ * @returns {string|undefined} The substring after the last marker, or undefined if marker not found.
967
+ */
968
+ function substringAfterLast (str, marker) {
969
+ assertString(str);
970
+ assertString(marker);
971
+ if (str.length === 0 || marker.length === 0) {
972
+ return
973
+ }
974
+ const index = str.lastIndexOf(marker);
975
+ if (index === -1) {
976
+ return
977
+ }
978
+ return str.substring(index + marker.length)
979
+ }
980
+
981
+ /**
982
+ * Extracts the substring between the specified start and end markers in a string.
983
+ * 1. NOT Greedy, substring between the FIRST startMarker and FIRST endMarker
984
+ * 2. undefined returned, if Not Found neither startMarker nor endMarker
985
+ * @param {string} str - The input string to search within
986
+ * @param {string} startMarker - The starting marker string
987
+ * @param {string} endMarker - The ending marker string
988
+ * @returns {string|undefined} The substring between markers, or undefined if markers not found
989
+ * @throws {Error} If any input is not a string.
990
+ */
991
+ function substringBetween (str, startMarker, endMarker) {
992
+ assertNotEmpty(str);
993
+ assertNotEmpty(startMarker);
994
+ assertNotEmpty(endMarker);
995
+ const startIndex = str.indexOf(startMarker);
996
+ if (startIndex === -1) {
997
+ return
998
+ }
999
+ const endIndex = str.indexOf(endMarker, startIndex + startMarker.length);
1000
+ if (endIndex === -1) {
1001
+ return
1002
+ }
1003
+ return str.substring(startIndex + startMarker.length, endIndex)
1004
+ }
1005
+
1006
+ /**
1007
+ * Extracts the substring between the first occurrence of `startMarker` and the last occurrence of `endMarker` in `str`.
1008
+ * 1. Greedy, substring between the FIRST startMarker and LAST endMarker
1009
+ * 2. undefined returned, if Not Found neither startMarker nor endMarker
1010
+ * @param {string} str - The input string to search.
1011
+ * @param {string} startMarker - The starting marker.
1012
+ * @param {string} endMarker - The ending marker.
1013
+ * @returns {string|undefined} The substring between markers, or `undefined` if markers are not found.
1014
+ * @throws {Error} If any input is not a string.
1015
+ */
1016
+ function substringBetweenGreedy (str, startMarker, endMarker) {
1017
+ assertNotEmpty(str);
1018
+ assertNotEmpty(startMarker);
1019
+ assertNotEmpty(endMarker);
1020
+ const startIndex = str.indexOf(startMarker);
1021
+ if (startIndex === -1) {
1022
+ return
1023
+ }
1024
+ const endIndex = str.lastIndexOf(endMarker);
1025
+ if (endIndex === -1 || endIndex <= startIndex) {
1026
+ return
1027
+ }
1028
+ return str.substring(startIndex + startMarker.length, endIndex)
1029
+ }
1030
+
1031
+ /**
1032
+ * Extracts all substrings between specified start and end markers in a string.
1033
+ * 1. NOT Greedy
1034
+ * @param {string} str - The input string to search within
1035
+ * @param {string} startMarker - The substring marking the start of extraction
1036
+ * @param {string} endMarker - The substring marking the end of extraction
1037
+ * @returns {string[]} Array of all found substrings between markers, empty array "[]" returned if not found
1038
+ * @throws {Error} If any input is not a string
1039
+ */
1040
+ function substringsBetween (str, startMarker, endMarker) {
1041
+ assertNotEmpty(str);
1042
+ assertNotEmpty(startMarker);
1043
+ assertNotEmpty(endMarker);
1044
+ const substrings = [];
1045
+ let start = 0;
1046
+ while (true) {
1047
+ const index = str.indexOf(startMarker, start);
1048
+ if (index === -1) {
1049
+ break
1050
+ }
1051
+ const endIndex = str.indexOf(endMarker, index + startMarker.length);
1052
+ if (endIndex === -1) {
1053
+ break
1054
+ }
1055
+ substrings.push(str.substring(index + startMarker.length, endIndex));
1056
+ start = endIndex + endMarker.length;
1057
+ }
1058
+ return substrings
1059
+ }
1060
+
1061
+ /**
1062
+ * Executes a task silently, suppressing any errors or rejections.
1063
+ * @param {Function} task - The export function to execute.
1064
+ * @returns {Promise<*>|*} The return value of the task, or a Promise if the task is asynchronous.
1065
+ */
1066
+ function quiet (task) {
1067
+ assertFunction(task);
1068
+ try {
1069
+ const rtnVal = task();
1070
+ if (isPromise(rtnVal)) {
1071
+ return rtnVal.catch(() => {
1072
+ // do nothing
1073
+ })
1074
+ }
1075
+ return rtnVal
1076
+ } catch (e) {
1077
+ // do nothing
1078
+ }
1079
+ }
1080
+
1081
+ /**
1082
+ * Executes a task quietly, capturing any errors and passing them to the errorKeeper.
1083
+ * 1. Handles both synchronous and asynchronous (Promise) tasks.
1084
+ * @param {Function} task - The export function to execute.
1085
+ * @param {Error[]} errorKeeper - The array to store any caught errors.
1086
+ * @returns {Promise<*>|*} The return value of the task, or a Promise if the task is asynchronous.
1087
+ */
1088
+ function quietKeepError (task, errorKeeper) {
1089
+ assertFunction(task);
1090
+ assertArray(errorKeeper);
1091
+ try {
1092
+ const rtnVal = task();
1093
+ if (isPromise(rtnVal)) {
1094
+ // @ts-ignore
1095
+ return rtnVal.catch(e => errorKeeper.push(e))
1096
+ }
1097
+ return rtnVal
1098
+ } catch (e) {
1099
+ // @ts-ignore
1100
+ errorKeeper.push(e);
1101
+ }
1102
+ }
1103
+ var ExecUtils = {
1104
+ quiet,
1105
+ quietKeepError
1106
+ };
1107
+
1108
+ // @ts-nocheck
1109
+
1110
+ /**
1111
+ * @module PromiseUtils
1112
+ * @description Promise utility functions for enhanced promise handling, including timeout, delay, parallel execution, and series execution.
1113
+ */
1114
+ var PromiseUtils = {
1115
+ defer,
1116
+ delay,
1117
+ timeout,
1118
+ allSettled,
1119
+ returnValuePromised,
1120
+ series,
1121
+ seriesAllSettled,
1122
+ parallel,
1123
+ parallelAllSettled
1124
+ };
1125
+
1126
+ /**
1127
+ * Creates a "Deferred" Object with Timeout support
1128
+ * 1. timeout=-1, it means no timeout check
1129
+ * @param {number} [timeout=-1] - Timeout duration in milliseconds
1130
+ * @param {string} [timeoutMessage]
1131
+ * @returns {{promise: Promise<*>, reject: function, resolve: function}}
1132
+ */
1133
+ function defer (timeout = -1, timeoutMessage) {
1134
+ assertNumber(timeout);
1135
+ const rtnVal = {};
1136
+
1137
+ let timerHandler;
1138
+ if (timeout >= 0) {
1139
+ rtnVal.timerHandler = timerHandler = setTimeout(() => {
1140
+ clearTimeout(timerHandler); // must clear it
1141
+ rtnVal.timerCleared = true; // easy to check in test case
1142
+ rtnVal.reject(new Error(timeoutMessage ?? `Promise Timeout: ${timeout}ms`));
1143
+ }, timeout);
1144
+ rtnVal.timerHandler = timerHandler;
1145
+ }
1146
+
1147
+ rtnVal.promise = new Promise((resolve, reject) => {
1148
+ rtnVal.resolve = (...args) => {
1149
+ if (timerHandler != null) {
1150
+ clearTimeout(timerHandler); // must clear it
1151
+ rtnVal.timerCleared = true; // easy to check in test case
1152
+ }
1153
+ rtnVal.resolved = true;
1154
+ resolve(...args);
1155
+ };
1156
+
1157
+ rtnVal.reject = (err) => {
1158
+ if (timerHandler != null) {
1159
+ clearTimeout(timerHandler); // must clear it
1160
+ rtnVal.timerCleared = true; // easy to check in test case
1161
+ }
1162
+ rtnVal.rejected = true;
1163
+ reject(err);
1164
+ };
1165
+ });
1166
+ rtnVal.promise.cancel = () => {
1167
+ if (timerHandler != null) {
1168
+ clearTimeout(timerHandler); // must clear it
1169
+ rtnVal.timerCleared = true; // easy to check in test case
1170
+ }
1171
+ rtnVal.rejected = true; // easy to check in test case
1172
+ rtnVal.canceled = rtnVal.promise.canceled = true; // easy to check in test case
1173
+ rtnVal.reject(new Error('Cancelled'));
1174
+ };
1175
+ return rtnVal
1176
+ }
1177
+
1178
+ /**
1179
+ * Creates a timeout wrapper around a promise that rejects if the promise doesn't resolve within the given time.
1180
+ * @param {Promise<*>} promise - The promise to wrap with a timeout
1181
+ * @param {number} [time=1] - Timeout duration in milliseconds
1182
+ * @param {string} [message=`Promise Timeout: ${time}ms`] - Custom rejection message
1183
+ * @returns {Promise<*>} A new promise that either resolves with the original promise's value, rejects with original promise's error or timeout error
1184
+ * @throws {TypeError} If input is not a promise or timeout is not a number
1185
+ */
1186
+ function timeout (promise, time, message) {
1187
+ assertPromise(promise);
1188
+
1189
+ time = time ?? 1;
1190
+ assertNumber(time);
1191
+
1192
+ const deferred = defer(time, message);
1193
+ const startTs = Date.now();
1194
+ promise.then((...args) => { // original promise settled, but timeout
1195
+ const elapsed = Date.now() - startTs;
1196
+ if (elapsed <= time) {
1197
+ deferred.resolve(...args);
1198
+ } else {
1199
+ deferred.reject(new Error(message ?? `Promise Timeout: ${time}ms`));
1200
+ }
1201
+ }).catch((err) => {
1202
+ // prevent double reject
1203
+ !deferred.resolved && !deferred.rejected && deferred.reject(err);
1204
+ });
1205
+ return deferred.promise
1206
+ }
1207
+
1208
+ /**
1209
+ * Excutes All promises in parallel and returns an array of results.
1210
+ *
1211
+ * Why:
1212
+ * 1. Promise.allSettled() returns
1213
+ * * { status: 'fulfilled', value: any } when promise fulfills
1214
+ * * { status: 'rejected', reason: any } when promise rejects
1215
+ * 2. It's NOT convenient to use Promise.allSettled() to get the results of all promises.
1216
+ * * the data structure is not consistent when fullfilled or rejected
1217
+ * * have to check "string" type of status to know sucess or failure
1218
+ * @param {Promise} promises
1219
+ * @returns {Array<{ok: boolean, result: any}>}
1220
+ */
1221
+ async function allSettled (promises) {
1222
+ assertArray(promises);
1223
+ const results = await Promise.allSettled(promises);
1224
+ const rtnVal = [];
1225
+ for (const result of results) {
1226
+ if (result.status === 'fulfilled') {
1227
+ rtnVal.push({ ok: true, result: result.value });
1228
+ }
1229
+ if (result.status === 'rejected') {
1230
+ rtnVal.push({ ok: false, result: result.reason });
1231
+ }
1232
+ }
1233
+ return rtnVal
1234
+ }
1235
+
1236
+ /**
1237
+ * Execute the task Function, and ensure it returns a Promise.
1238
+ * @param {function} task
1239
+ * @returns {Promise<*>}
1240
+ */
1241
+ function returnValuePromised (task) {
1242
+ try {
1243
+ const taskRtnVal = task();
1244
+ if (isPromise(taskRtnVal)) {
1245
+ return taskRtnVal
1246
+ }
1247
+ return Promise.resolve(taskRtnVal)
1248
+ } catch (e) {
1249
+ return Promise.reject(e)
1250
+ }
1251
+ }
1252
+
1253
+ /**
1254
+ * Delays a promise by a specified time.
1255
+ * 1. delay(), wait 1ms
1256
+ * 2. delay(1000), wait 1000ms
1257
+ * 3. delay(promise), after promise settled, wait 1000ms
1258
+ * 4. delay(promise, 2000), after promise settled, wait 2000ms
1259
+ *
1260
+ * @param {Promise<*>|number|undefined} [promise] - The input promise to delay
1261
+ * @param {number|undefined} [ms] - Minimum delay in milliseconds (default: 1)
1262
+ * @returns {Promise} A new promise that settles after the delay period
1263
+ */
1264
+ function delay (promise, ms) {
1265
+ if (isNumber(promise)) {
1266
+ ms = promise;
1267
+ promise = Promise.resolve();
1268
+ } else if (promise == null && ms == null) {
1269
+ ms = 1;
1270
+ promise = Promise.resolve();
1271
+ }
1272
+ promise != null && assertPromise(promise);
1273
+ ms = ms ?? 1000;
1274
+ assertNumber(ms);
1275
+ const deferred = defer();
1276
+ const startTs = Date.now();
1277
+ promise
1278
+ .then((...args) => {
1279
+ const escaped = Date.now() - startTs;
1280
+ if (escaped < ms) {
1281
+ setTimeout(() => deferred.resolve(...args), ms - escaped);
1282
+ } else {
1283
+ deferred.resolve(...args);
1284
+ }
1285
+ })
1286
+ .catch((err) => {
1287
+ const escaped = Date.now() - startTs;
1288
+ if (escaped < ms) {
1289
+ setTimeout(() => deferred.reject(err), ms - escaped);
1290
+ } else {
1291
+ deferred.reject(err);
1292
+ }
1293
+ });
1294
+ return deferred.promise
1295
+ }
1296
+
1297
+ /**
1298
+ * Fast-Fail mode to execute Tasks(functions) in series (one after another) and returns their results in order.
1299
+ * 1. export function are executed one by one
1300
+ * 2. Fast Fail: if any tasks fail, the whole chain is rejected with the first error
1301
+ * 3. if an element is not function, rejects the whole chain with Error(Not Function)
1302
+ * @param {Function[]} promises
1303
+ * @returns {Promise<Array>} Promise that resolves with an array of results in the same order as input tasks
1304
+ */
1305
+ async function series (tasks) {
1306
+ assertArray(tasks);
1307
+ const results = [];
1308
+ for (const task of tasks) {
1309
+ assertFunction(task);
1310
+ results.push(await task());
1311
+ }
1312
+ return results
1313
+ }
1314
+
1315
+ /**
1316
+ * AllSettled Mode to execute Tasks(functions) in series (one after another) and returns their results in order.
1317
+ * 1. tasks are executed one by one
1318
+ * 2. Each result is an object with `ok` (boolean) and `result` (resolved value or error).
1319
+ * 3. if a task is not Function, rejects the whole chain with Error(Not Function)
1320
+ * @param {Function[]} tasks
1321
+ * @returns {Promise<Array<{ok: boolean, result: *}>>}
1322
+ */
1323
+ async function seriesAllSettled (tasks) {
1324
+ assertArray(tasks);
1325
+ const results = [];
1326
+ for (const task of tasks) {
1327
+ assertFunction(task);
1328
+ try {
1329
+ results.push({ ok: true, result: await task() });
1330
+ } catch (err) {
1331
+ results.push({ ok: false, result: err });
1332
+ }
1333
+ }
1334
+ return results
1335
+ }
1336
+
1337
+ /**
1338
+ * FastFail Mode to Execute tasks in parallel with a maximum concurrency limit
1339
+ * 1. tasks are executed in parallel with a maximum concurrency limit
1340
+ * 2. rejects whole chain with the first error, when first task fails
1341
+ * @param {Function[]} tasks
1342
+ * @param {number} [maxParallel=5]
1343
+ * @returns {Promise<Array>} Array of resolved values from all promises
1344
+ * @throws {TypeError} If input is not an array of export function or maxParallel is not a number
1345
+ */
1346
+ async function parallel (tasks, maxParallel = 5) {
1347
+ assertArray(tasks);
1348
+ assertNumber(maxParallel);
1349
+ if (maxParallel <= 0) {
1350
+ throw new Error(`Invalid maxParallel: ${maxParallel}, should > 0`)
1351
+ }
1352
+ tasks.forEach((task) => assertFunction(task));
1353
+ const rtnVal = [];
1354
+ // once for all, run all tasks
1355
+ if (tasks.length <= maxParallel) {
1356
+ const resultsForBatch = await Promise.all(tasks.map(task => returnValuePromised(task)));
1357
+ rtnVal.push(...resultsForBatch);
1358
+ return rtnVal
1359
+ }
1360
+ // run group by MaxParallel
1361
+ const tasksToRun = [];
1362
+ for (const task of tasks) {
1363
+ assertFunction(task);
1364
+ tasksToRun.push(task);
1365
+ if (tasksToRun.length >= maxParallel) {
1366
+ const resultsForBatch = await Promise.all(tasksToRun.map(task => returnValuePromised(task)));
1367
+ rtnVal.push(...resultsForBatch);
1368
+ tasksToRun.length = 0;
1369
+ }
1370
+ }
1371
+ // Run all rested
1372
+ if (tasksToRun.length > 0 && tasksToRun.length < maxParallel) {
1373
+ const resultsForBatch = await Promise.all(tasksToRun.map(task => returnValuePromised(task)));
1374
+ rtnVal.push(...resultsForBatch);
1375
+ }
1376
+ return rtnVal
1377
+ }
1378
+
1379
+ /**
1380
+ * AllSettled Mode to execute tasks in parallel with a maximum concurrency limit
1381
+ * 1. tasks are executed in parallel with a maximum concurrency limit
1382
+ * 2. all tasks will be executed, even some of them failed.
1383
+ * @param {Function[]} tasks
1384
+ * @param {number} [maxParallel=5] - Maximum number of tasks to run in parallel
1385
+ * @returns {Promise<Array>} Array of resolved values from all promises
1386
+ * @throws {TypeError} If input is not an array of export function or maxParallel is not a number
1387
+ */
1388
+ async function parallelAllSettled (tasks, maxParallel = 5) {
1389
+ assertArray(tasks);
1390
+ assertNumber(maxParallel);
1391
+ if (maxParallel <= 0) {
1392
+ throw new Error(`Invalid maxParallel: ${maxParallel}, should > 0`)
1393
+ }
1394
+ tasks.forEach((task) => assertFunction(task));
1395
+ const rtnVal = [];
1396
+ // once for all, run all promises
1397
+ if (tasks.length <= maxParallel) {
1398
+ const resultsForBatch = await allSettled(tasks.map(task => returnValuePromised(task)));
1399
+ rtnVal.push(...resultsForBatch);
1400
+ return rtnVal
1401
+ }
1402
+ // run group by MaxParallel
1403
+ const tasksToRun = [];
1404
+ for (const task of tasks) {
1405
+ assertFunction(task);
1406
+ tasksToRun.push(task);
1407
+ if (tasksToRun.length >= maxParallel) {
1408
+ const resultsForBatch = await allSettled(tasksToRun.map(task => returnValuePromised(task)));
1409
+ rtnVal.push(...resultsForBatch);
1410
+ tasksToRun.length = 0;
1411
+ }
1412
+ }
1413
+ // Run all rested
1414
+ if (tasksToRun.length > 0 && tasksToRun.length < maxParallel) {
1415
+ const resultsForBatch = await allSettled(tasksToRun.map(task => returnValuePromised(task)));
1416
+ rtnVal.push(...resultsForBatch);
1417
+ }
1418
+ return rtnVal
1419
+ }
1420
+
1421
+ // owned
1422
+
1423
+ const { isPlainObject } = TypeUtils;
1424
+
1425
+ /**
1426
+ * @module ClassProxyUtils
1427
+ */
1428
+ var ClassProxyUtils = {
1429
+ proxy: proxy$1,
1430
+ newProxyInstance
1431
+ };
1432
+
1433
+ /**
1434
+ * Creates a Proxy Class for given class.
1435
+ * @template {object} T
1436
+ * @param {Function} cls - The class to proxycls - The class to proxy
1437
+ * @param {ProxyHandler<T>} [propertyHandler = {}] - Proxy Property Handler
1438
+ * @param {boolean} [sealed=true] - Whether to seal the instance
1439
+ * @returns {Function} A proxied classA proxied instance of the class
1440
+ */
1441
+ function proxy$1 (cls, propertyHandler, sealed = true) {
1442
+ if (typeof cls !== 'function') {
1443
+ throw new TypeError(`Not Class: type=${typeof cls}, value=${JSON.stringify(cls)}`)
1444
+ }
1445
+ if (propertyHandler != null) {
1446
+ if (!isPlainObject(propertyHandler)) {
1447
+ throw new TypeError(`Not PropertyHandler: type=${typeof propertyHandler}, value=${JSON.stringify(propertyHandler)}`)
1448
+ }
1449
+ const { get, set } = propertyHandler;
1450
+ if (get != null && typeof get !== 'function') {
1451
+ throw new TypeError(`Not PropertyHandler.get: type=${typeof get}, value=${JSON.stringify(get)}`)
1452
+ }
1453
+ if (set != null && typeof set !== 'function') {
1454
+ throw new TypeError(`Not PropertyHandler.set: type=${typeof set}, value=${JSON.stringify(set)}`)
1455
+ }
1456
+ }
1457
+ const construcHandler = {
1458
+ /**
1459
+ * Creates a proxied instance of a class, optionally sealing it.
1460
+ * @param {Function} constructor - The class constructor to instantiate.
1461
+ * @param {any[]} args - Arguments to pass to the constructor.
1462
+ * @param {Function} [newTarget] - The constructor that was originally called by `new`.
1463
+ * @returns {Proxy} A proxied instance of the constructed class.
1464
+ */
1465
+ construct (constructor, args, newTarget) {
1466
+ const clsInstance = Reflect.construct(constructor, args);
1467
+ return new Proxy(sealed ? Object.preventExtensions(clsInstance) : clsInstance, propertyHandler ?? {})
1468
+ }
1469
+ };
1470
+ return new Proxy(cls, construcHandler)
1471
+ }
1472
+
1473
+ /**
1474
+ * Creates a proxied instance of a class with custom property handling.
1475
+ * @template {object} T
1476
+ * @param {Function} cls - The class to proxy
1477
+ * @param {any[]} args - Arguments to pass to the constructor
1478
+ * @param {ProxyHandler<T>} propertyHandler - Handler for property access/mutation
1479
+ * @param {boolean} [sealed=true] - Whether the proxy should be sealed
1480
+ * @returns {T} Proxied class instance
1481
+ */
1482
+ function newProxyInstance (cls, args, propertyHandler, sealed = true) {
1483
+ const proxyCls = proxy$1(cls, propertyHandler, sealed);
1484
+ return Reflect.construct(proxyCls, args ?? [])
1485
+ }
1486
+
1487
+ /**
1488
+ * @module InstanceProxyUtils
1489
+ */
1490
+
1491
+ /**
1492
+ * Creates a proxy wrapper around an object instance with optional property handler.
1493
+ * @template {object} T
1494
+ * @param {T} instance - The target object to proxy
1495
+ * @param {ProxyHandler<T>} [propertyHandler] - Optional proxy handler for property access
1496
+ * @param {boolean} [sealed=true] - Whether to prevent extensions on the target object
1497
+ * @returns {T} The proxied object instance
1498
+ * @throws {TypeError} If instance is not an object
1499
+ */
1500
+ function proxy (instance, propertyHandler, sealed = true) {
1501
+ if (isNil(instance) || !isObject(instance) || isArray(instance)) {
1502
+ throw new TypeError(`Not Object: type=${typeof instance}, value=${JSON.stringify(instance)}`)
1503
+ }
1504
+ return new Proxy(sealed ? Object.preventExtensions(instance) : instance, propertyHandler ?? {})
1505
+ }
1506
+
1507
+ var InstanceProxyUtils = {
1508
+ proxy
1509
+ };
1510
+
1511
+ /**
1512
+ * @module Lang
1513
+ * @description Core language utilities for type checking, string manipulation, and common operations.
1514
+ */
1515
+
1516
+
1517
+ var index = {
1518
+ LangUtils,
1519
+ StringUtils,
1520
+ TypeUtils,
1521
+ TypeAssert,
1522
+ ExecUtils,
1523
+ PromiseUtils,
1524
+ Lang: LangUtils,
1525
+ Type: TypeUtils,
1526
+ Exec: ExecUtils,
1527
+ ClassProxyUtils,
1528
+ InstanceProxyUtils
1529
+ };
1530
+
1531
+ export { ClassProxyUtils, ExecUtils as Exec, ExecUtils, InstanceProxyUtils, LangUtils as Lang, LangUtils, PromiseUtils, StringUtils, TypeUtils as Type, TypeAssert, TypeUtils, index as default };
1532
+ //# sourceMappingURL=index-dev.js.map