-
-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathmetautil.mjs
More file actions
1132 lines (987 loc) · 27.1 KB
/
Copy pathmetautil.mjs
File metadata and controls
1132 lines (987 loc) · 27.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// error.js
class Error extends globalThis.Error {
constructor(message, options = {}) {
super(message);
const hasOptions = typeof options === 'object';
const { code, cause } = hasOptions ? options : { code: options };
this.code = code;
this.cause = cause;
}
}
class DomainError extends Error {
constructor(code, options = {}) {
const hasCode = typeof code !== 'object';
const opt = hasCode ? { ...options, code } : code;
super('Domain error', opt);
}
toError(errors) {
const { code, cause } = this;
const message = errors[this.code] || this.message;
return new Error(message, { code, cause });
}
}
const isError = (err) => err?.constructor?.name?.includes('Error') || false;
// strings.js
const replace = (str, substr, newstr) => {
if (substr === '') return str;
let src = str;
let res = '';
do {
const index = src.indexOf(substr);
if (index === -1) return res + src;
const start = src.substring(0, index);
src = src.substring(index + substr.length, src.length);
res += start + newstr;
} while (true);
};
const between = (s, prefix, suffix) => {
let i = s.indexOf(prefix);
if (i === -1) return '';
s = s.substring(i + prefix.length);
if (suffix) {
i = s.indexOf(suffix);
if (i === -1) return '';
s = s.substring(0, i);
}
return s;
};
const split = (s, separator) => {
const i = s.indexOf(separator);
if (i < 0) return [s, ''];
return [s.slice(0, i), s.slice(i + separator.length)];
};
const inRange = (x, min, max) => x >= min && x <= max;
const isFirstUpper = (s) => !!s && inRange(s[0], 'A', 'Z');
const isFirstLower = (s) => !!s && inRange(s[0], 'a', 'z');
const isFirstLetter = (s) => isFirstUpper(s) || isFirstLower(s);
const toLowerCamel = (s) => s.charAt(0).toLowerCase() + s.slice(1);
const toUpperCamel = (s) => s.charAt(0).toUpperCase() + s.slice(1);
const toLower = (s) => s.toLowerCase();
const toCamel = (separator) => (s) => {
const words = s.split(separator);
const first = words.length > 0 ? words.shift().toLowerCase() : '';
return first + words.map(toLower).map(toUpperCamel).join('');
};
const spinalToCamel = toCamel('-');
const snakeToCamel = toCamel('_');
const isConstant = (s) => s === s.toUpperCase();
const fileExt = (fileName) => {
const dot = fileName.lastIndexOf('.');
const slash = fileName.lastIndexOf('/');
if (slash > dot) return '';
return fileName.substring(dot + 1, fileName.length).toLowerCase();
};
const trimLines = (s) => {
const chunks = s.split('\n').map((d) => d.trim());
return chunks.filter((d) => d !== '').join('\n');
};
// array.js
const sample = (array, random = Math.random) => {
const index = Math.floor(random() * array.length);
return array[index];
};
const shuffle = (array, random = Math.random) => {
// Based on the algorithm described here:
// https://en.wikipedia.org/wiki/Fisher-Yates_shuffle
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
};
const projection = (source, fields) => {
const entries = [];
for (const key of fields) {
if (Object.hasOwn(source, key)) {
const value = source[key];
entries.push([key, value]);
}
}
return Object.fromEntries(entries);
};
// async.js
const toBool = [() => true, () => false];
const timeout = (msec, signal = null) =>
new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`Timeout of ${msec}ms reached`, 'ETIMEOUT'));
}, msec);
if (!signal) return;
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new Error('Timeout aborted'));
});
});
const delay = (msec, signal = null) =>
new Promise((resolve, reject) => {
const timer = setTimeout(resolve, msec);
if (!signal) return;
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new Error('Delay aborted'));
});
});
const timeoutify = (promise, msec) =>
new Promise((resolve, reject) => {
let timer = setTimeout(() => {
timer = null;
reject(new Error(`Timeout of ${msec}ms reached`, 'ETIMEOUT'));
}, msec);
promise.then(resolve, reject).finally(() => {
if (timer) clearTimeout(timer);
});
});
// datetime.js
const DURATION_UNITS = {
d: 86400, // days
h: 3600, // hours
m: 60, // minutes
s: 1, // seconds
};
const duration = (s) => {
if (typeof s === 'number') return s;
if (typeof s !== 'string') return 0;
let result = 0;
const parts = s.split(' ');
for (const part of parts) {
const unit = part.slice(-1);
const value = parseInt(part.slice(0, -1));
const mult = DURATION_UNITS[unit];
if (!isNaN(value) && mult) result += value * mult;
}
return result * 1000;
};
const twoDigit = (n) => n.toString().padStart(2, '0');
const nowDate = (date = new Date()) => {
const yyyy = date.getUTCFullYear().toString();
const mm = twoDigit(date.getUTCMonth() + 1);
const dd = twoDigit(date.getUTCDate());
return `${yyyy}-${mm}-${dd}`;
};
const nowDateTimeUTC = (date = new Date(), timeSep = ':') => {
const yyyy = date.getUTCFullYear().toString();
const mm = twoDigit(date.getUTCMonth() + 1);
const dd = twoDigit(date.getUTCDate());
const hh = twoDigit(date.getUTCHours());
const min = twoDigit(date.getUTCMinutes());
const ss = twoDigit(date.getUTCSeconds());
return `${yyyy}-${mm}-${dd}T${hh}${timeSep}${min}${timeSep}${ss}`;
};
const MONTHS = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
const NAME_LEN = 3;
const parseMonth = (s) => {
const name = s.substring(0, NAME_LEN);
const i = MONTHS.indexOf(name);
return i >= 0 ? i + 1 : -1;
};
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const parseDay = (s) => {
const name = s.substring(0, NAME_LEN);
const i = DAYS.indexOf(name);
return i >= 0 ? i + 1 : -1;
};
const ORDINAL = ['st', 'nd', 'rd', 'th'];
const isOrdinal = (s) => ORDINAL.some((d) => s.endsWith(d));
const YEAR_LEN = 4;
const parseEvery = (s = '') => {
let YY = -1;
let MM = -1;
let DD = -1;
let wd = -1;
let hh = -1;
let mm = -1;
let ms = 0;
const parts = s.split(' ');
for (const part of parts) {
if (part.includes(':')) {
const hm = split(part, ':');
const h = hm[0];
const m = hm[1];
if (h !== '') hh = parseInt(h);
mm = m === '' ? 0 : parseInt(m);
continue;
}
if (isOrdinal(part)) {
DD = parseInt(part);
continue;
}
if (part.length === YEAR_LEN) {
YY = parseInt(part);
continue;
}
if (MM === -1) {
MM = parseMonth(part);
if (MM > -1) continue;
}
if (wd === -1) {
wd = parseDay(part);
if (wd > -1) continue;
}
const unit = part.slice(-1);
const mult = DURATION_UNITS[unit];
if (typeof mult === 'number') {
const value = parseInt(part);
if (!isNaN(value)) ms += value * mult;
}
}
return { YY, MM, DD, wd, hh, mm, ms: ms > 0 ? ms * 1000 : -1 };
};
const nextEvent = (ev, d = new Date()) => {
let ms = 0;
const Y = d.getUTCFullYear();
const M = d.getUTCMonth() + 1;
const D = d.getUTCDate();
const w = d.getUTCDay() + 1;
const h = d.getUTCHours();
const m = d.getUTCMinutes();
const iY = ev.YY > -1;
const iM = ev.MM > -1;
const iD = ev.DD > -1;
const iw = ev.wd > -1;
const ih = ev.hh > -1;
const im = ev.mm > -1;
const ims = ev.ms > -1;
if (iY && ev.YY !== Y) return ev.YY < Y ? -1 : 0;
if (iM && ev.MM !== M) return ev.MM < M ? -1 : 0;
if (iD && ev.DD !== D) return ev.DD < D ? -1 : 0;
if (iw && ev.wd !== w) return 0;
if (ih && (ev.hh < h || (ev.hh === h && im && ev.mm < m))) return -1;
if (ih) ms += (ev.hh - h) * DURATION_UNITS.h;
if (im) ms += (ev.mm - m) * DURATION_UNITS.m;
ms *= 1000;
if (ims) ms += ev.ms;
return ms;
};
// objects.js
const makePrivate = (instance) => {
const iface = {};
const fields = Object.keys(instance);
for (const fieldName of fields) {
const field = instance[fieldName];
if (isConstant(fieldName)) {
iface[fieldName] = field;
} else if (typeof field === 'function') {
const boundMethod = field.bind(instance);
iface[fieldName] = boundMethod;
instance[fieldName] = boundMethod;
}
}
return iface;
};
const protect = (allowMixins, ...namespaces) => {
for (const namespace of namespaces) {
const names = Object.keys(namespace);
for (const name of names) {
const target = namespace[name];
if (!allowMixins.includes(name)) Object.freeze(target);
}
}
};
const jsonParse = (data) => {
if (data === null || data === undefined) return null;
if (data.length === 0) return null;
try {
return JSON.parse(data);
} catch {
return null;
}
};
const isHashObject = (o) =>
typeof o === 'object' && o !== null && !Array.isArray(o);
const flatObject = (source, fields = []) => {
const target = {};
for (const entry of Object.entries(source)) {
const key = entry[0];
const value = entry[1];
if (!isHashObject(value)) {
target[key] = value;
continue;
}
if (fields.length > 0 && !fields.includes(key)) {
target[key] = { ...value };
continue;
}
for (const childEntry of Object.entries(value)) {
const childKey = childEntry[0];
const childValue = childEntry[1];
const combined = `${key}${toUpperCamel(childKey)}`;
if (source[combined] !== undefined) {
const error = `Can not combine keys: key "${combined}" already exists`;
throw new Error(error);
}
target[combined] = childValue;
}
}
return target;
};
const unflatObject = (source, fields) => {
const result = {};
for (const entry of Object.entries(source)) {
const key = entry[0];
const value = entry[1];
const prefix = fields.find((name) => key.startsWith(name));
if (prefix) {
if (Object.hasOwn(source, prefix)) {
throw new Error(`Can not combine keys: key "${prefix}" already exists`);
}
const newKey = key.substring(prefix.length).toLowerCase();
const section = result[prefix];
if (section) section[newKey] = value;
else result[prefix] = { [newKey]: value };
continue;
}
result[key] = value;
}
return result;
};
const getSignature = (method) => {
const src = method.toString();
const signature = between(src, '({', '})');
if (signature === '') return [];
return signature.split(',').map((s) => s.trim());
};
const namespaceByPath = (namespace, path) => {
const parts = split(path, '.');
const key = parts[0];
const rest = parts[1];
const step = namespace[key];
if (!step) return null;
if (rest === '') return step;
return namespaceByPath(step, rest);
};
const serializeArguments = (fields, args) => {
if (!fields) return '';
const data = {};
for (const par of fields) {
data[par] = args[par];
}
return JSON.stringify(data);
};
const firstKey = (obj) => Object.keys(obj).find(isFirstLetter);
const isInstanceOf = (obj, constrName) => obj?.constructor?.name === constrName;
// collector.js
class Collector {
done = false;
data = {};
keys = [];
count = 0;
exact = true;
reassign = false;
timeout = 0;
defaults = {};
validate = null;
#fulfill = null;
#reject = null;
#cause = null;
#controller = null;
#signal = null;
#timeout = null;
constructor(keys, options = {}) {
const { exact = true, reassign = false } = options;
const { timeout = 0, defaults = {}, validate } = options;
if (validate) this.validate = validate;
this.keys = keys;
if (exact === false) this.exact = false;
if (reassign === false) this.reassign = reassign;
if (typeof defaults === 'object') this.defaults = defaults;
this.#controller = new AbortController();
this.#signal = this.#controller.signal;
if (typeof timeout === 'number' && timeout > 0) {
this.#timeout = AbortSignal.timeout(timeout);
this.#signal = AbortSignal.any([this.#signal, this.#timeout]);
this.#signal.addEventListener('abort', () => {
if (Object.keys(this.defaults).length > 0) this.#default();
if (this.done) return;
this.fail(this.#signal.reason);
});
}
}
#default() {
for (const entry of Object.entries(this.defaults)) {
const key = entry[0];
const value = entry[1];
if (this.data[key] === undefined) this.set(key, value);
}
}
get signal() {
return this.#signal;
}
set(key, value) {
if (this.done) return;
const expected = this.keys.includes(key);
if (!expected && this.exact) {
this.fail(new Error(`Unexpected key: ${key}`));
return;
}
const has = this.data[key] !== undefined;
if (has && !this.reassign) {
const error = new Error('Collector reassign mode is off');
return void this.fail(error);
}
if (!has && expected) this.count++;
this.data[key] = value;
if (this.count === this.keys.length) {
this.done = true;
this.#timeout = null;
if (this.#fulfill) this.#fulfill(this.data);
}
}
take(key, fn, ...args) {
fn(...args, (error, data) => {
if (error) this.fail(error);
else this.set(key, data);
});
}
wait(key, fn, ...args) {
const promise = fn instanceof Promise ? fn : fn(...args);
promise.then(
(data) => this.set(key, data),
(error) => this.fail(error),
);
}
collect(sources) {
for (const entry of Object.entries(sources)) {
const key = entry[0];
const collector = entry[1];
collector.then(
(data) => this.set(key, data),
(error) => this.fail(error),
);
}
}
fail(error) {
this.done = true;
this.#timeout = null;
const cause = error || new Error('Collector aborted');
this.#cause = cause;
this.#controller.abort();
if (this.#reject) this.#reject(cause);
}
abort() {
this.fail();
}
then(onFulfilled, onRejected = null) {
return new Promise((resolve, reject) => {
this.#fulfill = resolve;
this.#reject = reject;
if (!this.done) return;
if (this.validate) {
try {
this.validate(this.data);
} catch (error) {
this.#cause = error;
}
}
if (this.#cause) reject(this.#cause);
else resolve(this.data);
}).then(onFulfilled, onRejected);
}
}
const collect = (keys, options) => new Collector(keys, options);
// events.js
const DONE = { done: true, value: undefined };
class EventIterator {
#resolvers = [];
#emitter = null;
#eventName = '';
#listener = null;
#onerror = null;
#done = false;
constructor(emitter, eventName) {
this.#emitter = emitter;
this.#eventName = eventName;
this.#listener = (value) => {
const resolvers = this.#resolvers;
this.#resolvers = [];
for (const resolver of resolvers) {
resolver.resolve({ done: this.#done, value });
}
};
emitter.on(eventName, this.#listener);
this.#onerror = (error) => {
const resolvers = this.#resolvers;
this.#resolvers = [];
for (const resolver of resolvers) {
resolver.reject(error);
}
this.#finalize();
};
emitter.on('error', this.#onerror);
}
next() {
return new Promise((resolve, reject) => {
if (this.#done) return void resolve(DONE);
this.#resolvers.push({ resolve, reject });
});
}
#finalize() {
if (this.#done) return;
this.#done = true;
this.#emitter.off(this.#eventName, this.#listener);
this.#emitter.off('error', this.#onerror);
for (const resolver of this.#resolvers) {
resolver.resolve(DONE);
}
this.#resolvers.length = 0;
}
async return() {
this.#finalize();
return DONE;
}
async throw() {
this.#finalize();
return DONE;
}
}
class EventIterable {
#emitter = null;
#eventName = '';
constructor(emitter, eventName) {
this.#emitter = emitter;
this.#eventName = eventName;
}
[Symbol.asyncIterator]() {
return new EventIterator(this.#emitter, this.#eventName);
}
}
class Emitter {
#events = new Map();
#maxListeners = 10;
constructor(options = {}) {
this.#maxListeners = options.maxListeners ?? 10;
}
emit(eventName, value) {
const event = this.#events.get(eventName);
if (!event) {
if (eventName !== 'error') return Promise.resolve();
throw new Error('Unhandled error');
}
const listeners = event.on.slice();
const promises = listeners.map(async (fn) => fn(value));
if (event.once.size > 0) {
const len = event.on.length;
const remaining = new Array(len);
let index = 0;
for (let i = 0; i < len; i++) {
const listener = event.on[i];
if (!event.once.has(listener)) remaining[index++] = listener;
}
if (index === 0) {
this.#events.delete(eventName);
} else {
remaining.length = index;
this.#events.set(eventName, { on: remaining, once: new Set() });
}
}
return Promise.all(promises).then(() => undefined);
}
#addListener(eventName, listener, once) {
let event = this.#events.get(eventName);
if (!event) {
const on = [listener];
event = { on, once: once ? new Set(on) : new Set() };
this.#events.set(eventName, event);
} else {
if (event.on.includes(listener)) {
throw new Error('Duplicate listeners detected');
}
event.on.push(listener);
if (once) event.once.add(listener);
}
if (event.on.length > this.#maxListeners) {
throw new Error(
`MaxListenersExceededWarning: Possible memory leak. ` +
`Current maxListeners is ${this.#maxListeners}.`,
);
}
}
on(eventName, listener) {
this.#addListener(eventName, listener, false);
}
once(eventName, listener) {
this.#addListener(eventName, listener, true);
}
off(eventName, listener) {
if (!listener) return void this.#events.delete(eventName);
const event = this.#events.get(eventName);
if (!event) return;
const index = event.on.indexOf(listener);
if (index > -1) event.on.splice(index, 1);
event.once.delete(listener);
}
toPromise(eventName) {
return new Promise((resolve) => {
this.once(eventName, resolve);
});
}
toAsyncIterable(eventName) {
return new EventIterable(this, eventName);
}
clear(eventName) {
if (!eventName) return void this.#events.clear();
this.#events.delete(eventName);
}
listeners(eventName) {
if (!eventName) throw new Error('Expected eventName');
const event = this.#events.get(eventName);
return event ? event.on : [];
}
listenerCount(eventName) {
if (!eventName) throw new Error('Expected eventName');
const event = this.#events.get(eventName);
return event ? event.on.length : 0;
}
eventNames() {
return Array.from(this.#events.keys());
}
}
// http.js
const parseHost = (host) => {
if (!host) return 'no-host-name-in-http-headers';
const portOffset = host.indexOf(':');
if (portOffset > -1) return host.substring(0, portOffset);
return host;
};
const parseParams = (params) => Object.fromEntries(new URLSearchParams(params));
const parseCookies = (cookie) => {
const values = [];
const items = cookie.split(';');
for (const item of items) {
const pair = item.split('=');
const key = pair[0];
const val = pair[1] === undefined ? '' : pair[1];
values.push([key.trim(), val.trim()]);
}
return Object.fromEntries(values);
};
const parseRange = (range) => {
if (!range || !range.includes('=')) return {};
const bytes = range.split('=').pop();
if (!bytes || !range.includes('-')) return {};
const bounds = bytes.split('-').map((n) => parseInt(n));
const start = bounds[0];
const end = bounds[1];
if (isNaN(start)) return isNaN(end) ? {} : { tail: end };
return isNaN(end) ? { start } : { start, end };
};
// pool.js
class Pool {
constructor(options = {}) {
this.items = [];
this.free = [];
this.queue = [];
this.timeout = options.timeout || 0;
this.current = 0;
this.size = 0;
this.available = 0;
}
async next(exclusive = false) {
if (this.size === 0) return null;
if (this.available === 0) {
return new Promise((resolve, reject) => {
const waiting = { resolve, timer: null };
waiting.timer = setTimeout(() => {
waiting.resolve = null;
this.queue.shift();
reject(new Error('Pool next item timeout'));
}, this.timeout);
this.queue.push(waiting);
});
}
let item = null;
let free = false;
let attempts = 0;
do {
item = this.items[this.current];
free = this.free[this.current];
this.current++;
if (this.current === this.size) this.current = 0;
if (++attempts > this.size) return null;
} while (!item || !free);
if (exclusive) {
const index = this.items.indexOf(item);
this.free[index] = false;
this.available--;
}
return item;
}
add(item) {
if (this.items.includes(item)) throw new Error('Pool: add duplicates');
this.size++;
this.available++;
this.items.push(item);
this.free.push(true);
}
async capture() {
return this.next(true);
}
release(item) {
const index = this.items.indexOf(item);
if (index < 0) throw new Error('Pool: release unexpected item');
if (this.free[index]) throw new Error('Pool: release not captured');
if (this.queue.length > 0) {
const { resolve, timer } = this.queue.shift();
clearTimeout(timer);
if (resolve) return void setTimeout(resolve, 0, item);
}
this.free[index] = true;
this.available++;
}
isFree(item) {
const index = this.items.indexOf(item);
if (index < 0) return false;
return this.free[index];
}
}
// result.js
const NO_DEFAULT = Symbol('NoDefault');
class Result {
#value = null;
#error = null;
constructor(value = null, error = null) {
if (value !== null) this.#value = value;
if (error !== null) this.#error = error;
}
static ok(value = null) {
return new Result(value, null);
}
static fail(error) {
return new Result(null, error);
}
static from(fn) {
try {
return Result.ok(fn());
} catch (error) {
return Result.fail(error);
}
}
static async fromAsync(fn) {
try {
return Result.ok(await fn());
} catch (error) {
return Result.fail(error);
}
}
get value() {
return this.#value;
}
get error() {
return this.#error;
}
get ok() {
return this.#error === null;
}
unwrap(defaultValue = NO_DEFAULT) {
if (this.#error === null) return this.#value;
if (defaultValue === NO_DEFAULT) throw this.#error;
return defaultValue;
}
map(fn) {
if (this.#error !== null) return this;
return Result.from(() => fn(this.#value));
}
}
// semaphore.js
class Semaphore {
constructor({ concurrency, size = 0, timeout = 0 }) {
this.concurrency = concurrency;
this.counter = concurrency;
this.timeout = timeout;
this.size = size;
this.queue = [];
this.empty = true;
}
async enter() {
return new Promise((resolve, reject) => {
if (this.counter > 0) {
this.counter--;
this.empty = false;
return void resolve();
}
if (this.queue.length >= this.size) {
return void reject(new Error('Semaphore queue is full'));
}
const waiting = { resolve, timer: null };
waiting.timer = setTimeout(() => {
waiting.resolve = null;
this.queue.shift();
const { counter, concurrency } = this;
this.empty = this.queue.length === 0 && counter === concurrency;
reject(new Error('Semaphore timeout'));
}, this.timeout);
this.queue.push(waiting);
this.empty = false;
});
}
leave() {
if (this.queue.length === 0) {
this.counter++;
this.empty = this.counter === this.concurrency;
return;
}
const { resolve, timer } = this.queue.shift();
clearTimeout(timer);
if (resolve) setTimeout(resolve, 0);
const { counter, concurrency } = this;
this.empty = this.queue.length === 0 && counter === concurrency;
}
}
// units.js
const SIZE_UNITS = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const bytesToSize = (bytes) => {
if (bytes === 0) return '0';
const exp = Math.floor(Math.log(bytes) / Math.log(1000));
const size = bytes / 1000 ** exp;
const short = Math.round(size);
const unit = exp === 0 ? '' : ` ${SIZE_UNITS[exp - 1]}`;
return short.toString() + unit;
};
const UNIT_SIZES = {
yb: 24, // yottabyte
zb: 21, // zettabyte
eb: 18, // exabyte
pb: 15, // petabyte
tb: 12, // terabyte
gb: 9, // gigabyte
mb: 6, // megabyte
kb: 3, // kilobyte
};
const sizeToBytes = (size) => {
const length = size.length;