@bemoje/profiler 2.2.0 → 2.2.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.
package/lib/index.js CHANGED
@@ -1 +1,1142 @@
1
- export * from './Profiler/Profiler';
1
+ import { inspect } from 'util';
2
+ import { isSymbol, isFunction } from 'es-toolkit/predicate';
3
+ import { isAsyncFunction } from 'util/types';
4
+ import { round } from 'es-toolkit/math';
5
+ import colors from 'ansi-colors';
6
+ import memoizee from 'memoizee';
7
+ import { ms } from 'enhanced-ms';
8
+
9
+ var __defProp = Object.defineProperty;
10
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
11
+ var FunctionProfiler = class _FunctionProfiler {
12
+ static {
13
+ __name(this, "FunctionProfiler");
14
+ }
15
+ id;
16
+ static instances = [];
17
+ calls = 0;
18
+ totalTimeNs;
19
+ minTimeNs;
20
+ maxTimeNs;
21
+ constructor(id) {
22
+ this.id = id;
23
+ _FunctionProfiler.instances.push(this);
24
+ }
25
+ /**
26
+ * Average execution time in nanoseconds
27
+ */
28
+ get avgTimeNs() {
29
+ if (!this.calls || !this.totalTimeNs) {
30
+ return void 0;
31
+ }
32
+ return Math.floor(this.totalTimeNs / this.calls);
33
+ }
34
+ /**
35
+ * Get the result of the profiling
36
+ */
37
+ getResult() {
38
+ return {
39
+ calls: this.calls,
40
+ totalTimeUs: this.totalTimeNs ? this.nsToUs(this.totalTimeNs) : void 0,
41
+ avgTimeUs: this.avgTimeNs ? this.nsToUs(this.avgTimeNs) : void 0,
42
+ minTimeUs: this.minTimeNs == null ? this.minTimeNs : this.nsToUs(this.minTimeNs),
43
+ maxTimeUs: this.maxTimeNs == null ? this.maxTimeNs : this.nsToUs(this.maxTimeNs)
44
+ };
45
+ }
46
+ /**
47
+ * @see IFunctionSpyStrategy.onInvoke
48
+ */
49
+ onInvoke() {
50
+ return process.hrtime.bigint();
51
+ }
52
+ /**
53
+ * @see IFunctionSpyStrategy.onReturn
54
+ */
55
+ onReturn(t0, retval) {
56
+ this.add(t0, process.hrtime.bigint());
57
+ return retval;
58
+ }
59
+ /**
60
+ * Add a new time measurement
61
+ */
62
+ add(t0, t1) {
63
+ const elapsed = Number(t1 - t0);
64
+ this.calls++;
65
+ this.totalTimeNs = (this.totalTimeNs ?? 0) + elapsed;
66
+ this.minTimeNs = Math.min(this.minTimeNs ?? elapsed, elapsed);
67
+ this.maxTimeNs = Math.max(this.maxTimeNs ?? elapsed, elapsed);
68
+ }
69
+ /**
70
+ * Nanoseconds to microseconds
71
+ */
72
+ nsToUs(ns) {
73
+ return Math.round(ns / 1e3);
74
+ }
75
+ [inspect.custom]() {
76
+ return this.getResult();
77
+ }
78
+ toJSON() {
79
+ return this.getResult();
80
+ }
81
+ };
82
+
83
+ // ../object/src/setNonEnumerable.ts
84
+ function setNonEnumerable(object, ...properties) {
85
+ for (const prop of properties) {
86
+ Object.defineProperty(object, prop, {
87
+ enumerable: false
88
+ });
89
+ }
90
+ return object;
91
+ }
92
+ __name(setNonEnumerable, "setNonEnumerable");
93
+
94
+ // src/internal/FunctionIdentifier/AbstractFunctionIdentifier.ts
95
+ var AbstractFunctionIdentifier = class {
96
+ static {
97
+ __name(this, "AbstractFunctionIdentifier");
98
+ }
99
+ target;
100
+ constructor(target) {
101
+ this.target = target;
102
+ setNonEnumerable(this, "target");
103
+ }
104
+ toJSON() {
105
+ return this.name;
106
+ }
107
+ [inspect.custom]() {
108
+ return this.name;
109
+ }
110
+ };
111
+ var AbstractMethodIdentifier = class extends AbstractFunctionIdentifier {
112
+ static {
113
+ __name(this, "AbstractMethodIdentifier");
114
+ }
115
+ key;
116
+ type;
117
+ constructor(target, key, type = "method") {
118
+ super(target), this.key = key, this.type = type;
119
+ setNonEnumerable(this, "type", "key");
120
+ }
121
+ keytoString() {
122
+ return isSymbol(this.key) ? `[${this.key.description}]` : this.key;
123
+ }
124
+ get methodName() {
125
+ if (this.type === "method") {
126
+ return `${this.keytoString()}()`;
127
+ }
128
+ if (this.type === "get") {
129
+ return this.keytoString();
130
+ }
131
+ return `${this.keytoString()}[set]`;
132
+ }
133
+ get name() {
134
+ return this.parentName + (isSymbol(this.key) ? "" : ".") + this.methodName;
135
+ }
136
+ };
137
+
138
+ // src/internal/FunctionIdentifier/ModuleMethodIdentifier.ts
139
+ var ModuleMethodIdentifier = class extends AbstractMethodIdentifier {
140
+ static {
141
+ __name(this, "ModuleMethodIdentifier");
142
+ }
143
+ parentName;
144
+ constructor(parentName, target, key, type = "method") {
145
+ super(target, key, type), this.parentName = parentName;
146
+ setNonEnumerable(this, "parentName");
147
+ }
148
+ get targetType() {
149
+ return "module";
150
+ }
151
+ };
152
+
153
+ // src/internal/ProfilerFactory/ModuleMethodProfilerFactory.ts
154
+ var ModuleMethodProfilerFactory = class {
155
+ static {
156
+ __name(this, "ModuleMethodProfilerFactory");
157
+ }
158
+ moduleName;
159
+ target;
160
+ constructor(moduleName, target) {
161
+ this.moduleName = moduleName;
162
+ this.target = target;
163
+ }
164
+ createProfiler(key, methodType) {
165
+ return new FunctionProfiler(new ModuleMethodIdentifier(this.moduleName, this.target, key, methodType));
166
+ }
167
+ };
168
+
169
+ // ../fn/src/setNameAndLength.ts
170
+ function setNameAndLength(source, target, lengthDelta = 0) {
171
+ return Object.defineProperties(target, {
172
+ name: {
173
+ configurable: true,
174
+ value: source.name
175
+ },
176
+ length: {
177
+ configurable: true,
178
+ value: source.length + lengthDelta
179
+ }
180
+ });
181
+ }
182
+ __name(setNameAndLength, "setNameAndLength");
183
+ function functionSpy(func, spy, options = {}) {
184
+ if (options.async === false) {
185
+ return wrapSync(func, spy, options);
186
+ } else if (options.async || isAsyncFunction(func)) {
187
+ return wrapAsync(func, spy, options);
188
+ } else {
189
+ return wrapMaybeAsync(func, spy, options);
190
+ }
191
+ }
192
+ __name(functionSpy, "functionSpy");
193
+ function wrapMaybeAsync(func, spy, options = {}) {
194
+ const ignore = options.ignore;
195
+ if (ignore && ignore(func, spy)) {
196
+ return func;
197
+ }
198
+ return setNameAndLength(func, function(...args) {
199
+ if (ignore && ignore(func, spy, this)) {
200
+ return func.apply(this, args);
201
+ }
202
+ const data = spy.onInvoke(this, args);
203
+ const retval = func.apply(this, args);
204
+ return retval instanceof Promise ? retval.then((retval2) => {
205
+ return spy.onReturn(data, retval2);
206
+ }) : spy.onReturn(data, retval);
207
+ });
208
+ }
209
+ __name(wrapMaybeAsync, "wrapMaybeAsync");
210
+ function wrapSync(func, spy, options = {}) {
211
+ const ignore = options.ignore;
212
+ if (ignore && ignore(func, spy)) {
213
+ return func;
214
+ }
215
+ return setNameAndLength(func, function(...args) {
216
+ if (ignore && ignore(func, spy, this)) {
217
+ return func.apply(this, args);
218
+ }
219
+ const data = spy.onInvoke(this, args);
220
+ const retval = func.apply(this, args);
221
+ return spy.onReturn(data, retval);
222
+ });
223
+ }
224
+ __name(wrapSync, "wrapSync");
225
+ function wrapAsync(func, spy, options = {}) {
226
+ const ignore = options.ignore;
227
+ if (ignore && ignore(func, spy)) {
228
+ return func;
229
+ }
230
+ return setNameAndLength(func, async function(...args) {
231
+ if (ignore && ignore(func, spy, this)) {
232
+ return await func.apply(this, args);
233
+ }
234
+ const data = spy.onInvoke(this, args);
235
+ const retval = await func.apply(this, args);
236
+ return spy.onReturn(data, retval);
237
+ });
238
+ }
239
+ __name(wrapAsync, "wrapAsync");
240
+
241
+ // ../fn/src/setName.ts
242
+ function setName(name, target) {
243
+ return Object.defineProperty(target, "name", {
244
+ value: typeof name === "string" ? name : name.name,
245
+ configurable: true,
246
+ enumerable: false
247
+ });
248
+ }
249
+ __name(setName, "setName");
250
+ function wrapMethods(target, strat) {
251
+ for (const [key, type, des] of iterateMethods(target)) {
252
+ if (strat.filter && !strat.filter(target, key, type, des)) {
253
+ continue;
254
+ }
255
+ switch (type) {
256
+ case "method": {
257
+ if (!strat.onMethod) {
258
+ continue;
259
+ }
260
+ const orig = des.value;
261
+ const wrapped = strat.onMethod(target, key, orig);
262
+ if (!wrapped) {
263
+ continue;
264
+ }
265
+ Object.defineProperty(target, key, {
266
+ value: setNameAndLength(orig, wrapped),
267
+ configurable: des.configurable,
268
+ enumerable: des.enumerable
269
+ });
270
+ break;
271
+ }
272
+ case "get": {
273
+ if (!strat.onGetter) {
274
+ continue;
275
+ }
276
+ const orig = des.get;
277
+ const wrapped = strat.onGetter(target, key, orig);
278
+ if (!wrapped) {
279
+ continue;
280
+ }
281
+ Object.defineProperty(target, key, {
282
+ get: setNameAndLength(orig, wrapped),
283
+ configurable: des.configurable,
284
+ enumerable: des.enumerable
285
+ });
286
+ break;
287
+ }
288
+ case "set": {
289
+ if (!strat.onSetter) {
290
+ continue;
291
+ }
292
+ const orig = des.set;
293
+ const wrapped = strat.onSetter(target, key, orig);
294
+ if (!wrapped) {
295
+ continue;
296
+ }
297
+ Object.defineProperty(target, key, {
298
+ set: setNameAndLength(orig, wrapped),
299
+ configurable: des.configurable,
300
+ enumerable: des.enumerable
301
+ });
302
+ break;
303
+ }
304
+ }
305
+ }
306
+ return target;
307
+ }
308
+ __name(wrapMethods, "wrapMethods");
309
+ function* iterateMethods(target) {
310
+ for (const key of Reflect.ownKeys(target)) {
311
+ const des = Object.getOwnPropertyDescriptor(target, key);
312
+ if (!des || des.configurable === false) {
313
+ continue;
314
+ }
315
+ if (isFunction(des.value)) {
316
+ yield [
317
+ key,
318
+ "method",
319
+ des
320
+ ];
321
+ } else {
322
+ if (isFunction(des.get)) {
323
+ yield [
324
+ key,
325
+ "get",
326
+ des
327
+ ];
328
+ }
329
+ if (isFunction(des.set)) {
330
+ yield [
331
+ key,
332
+ "set",
333
+ des
334
+ ];
335
+ }
336
+ }
337
+ }
338
+ }
339
+ __name(iterateMethods, "iterateMethods");
340
+
341
+ // src/internal/FunctionProfiler/profilerWrap.ts
342
+ function profilerWrap(func, profiler) {
343
+ const ignore = /* @__PURE__ */ __name(() => {
344
+ return !Profiler.enabled;
345
+ }, "ignore");
346
+ return profiler.id.type === "get" || profiler.id.type === "set" ? functionSpy(func, profiler, {
347
+ ignore,
348
+ async: false
349
+ }) : functionSpy(func, profiler, {
350
+ ignore
351
+ });
352
+ }
353
+ __name(profilerWrap, "profilerWrap");
354
+
355
+ // src/internal/ProfilerWrapMethodsStrategy/ProfilerWrapMethodsStrategy.ts
356
+ var ProfilerWrapMethodsStrategy = class {
357
+ static {
358
+ __name(this, "ProfilerWrapMethodsStrategy");
359
+ }
360
+ profilerFactory;
361
+ ignoreKeys;
362
+ constructor(profilerFactory, ignoreKeys) {
363
+ this.profilerFactory = profilerFactory;
364
+ this.ignoreKeys = new Set(ignoreKeys);
365
+ }
366
+ filter(target, key) {
367
+ if (key === "constructor") {
368
+ return false;
369
+ }
370
+ if (this.ignoreKeys.has(key)) {
371
+ return false;
372
+ }
373
+ return true;
374
+ }
375
+ onMethod(target, key, method) {
376
+ return profilerWrap(method, this.profilerFactory.createProfiler(key, "method"));
377
+ }
378
+ onGetter(target, key, getter) {
379
+ return profilerWrap(getter, this.profilerFactory.createProfiler(key, "get"));
380
+ }
381
+ onSetter(target, key, setter) {
382
+ return profilerWrap(setter, this.profilerFactory.createProfiler(key, "set"));
383
+ }
384
+ };
385
+
386
+ // src/internal/FunctionIdentifier/PrototypeMethodIdentifier.ts
387
+ var PrototypeMethodIdentifier = class extends AbstractMethodIdentifier {
388
+ static {
389
+ __name(this, "PrototypeMethodIdentifier");
390
+ }
391
+ get targetType() {
392
+ return "prototype";
393
+ }
394
+ get parentName() {
395
+ return `${this.target.constructor.name}.${this.targetType}`;
396
+ }
397
+ };
398
+
399
+ // src/internal/ProfilerFactory/PrototypeMethodProfilerFactory.ts
400
+ var PrototypeMethodProfilerFactory = class {
401
+ static {
402
+ __name(this, "PrototypeMethodProfilerFactory");
403
+ }
404
+ target;
405
+ constructor(target) {
406
+ this.target = target;
407
+ }
408
+ createProfiler(key, methodType) {
409
+ return new FunctionProfiler(new PrototypeMethodIdentifier(this.target, key, methodType));
410
+ }
411
+ };
412
+
413
+ // src/internal/FunctionIdentifier/StandaloneFunctionIdentifier.ts
414
+ var StandaloneFunctionIdentifier = class extends AbstractFunctionIdentifier {
415
+ static {
416
+ __name(this, "StandaloneFunctionIdentifier");
417
+ }
418
+ get targetType() {
419
+ return "standalone";
420
+ }
421
+ get type() {
422
+ return "function";
423
+ }
424
+ get name() {
425
+ return `${this.target.name}()`;
426
+ }
427
+ };
428
+
429
+ // src/internal/FunctionIdentifier/StaticMethodIdentifier.ts
430
+ var StaticMethodIdentifier = class extends AbstractMethodIdentifier {
431
+ static {
432
+ __name(this, "StaticMethodIdentifier");
433
+ }
434
+ get targetType() {
435
+ return "static";
436
+ }
437
+ get parentName() {
438
+ return this.target.name;
439
+ }
440
+ };
441
+
442
+ // src/internal/ProfilerFactory/StaticMethodProfilerFactory.ts
443
+ var StaticMethodProfilerFactory = class {
444
+ static {
445
+ __name(this, "StaticMethodProfilerFactory");
446
+ }
447
+ target;
448
+ constructor(target) {
449
+ this.target = target;
450
+ }
451
+ createProfiler(key, methodType) {
452
+ return new FunctionProfiler(new StaticMethodIdentifier(this.target, key, methodType));
453
+ }
454
+ };
455
+
456
+ // ../number/src/NumberFormatter.ts
457
+ var locales = /* @__PURE__ */ new Map([
458
+ [
459
+ "en-US",
460
+ [
461
+ ",",
462
+ "."
463
+ ]
464
+ ],
465
+ [
466
+ "da-DK",
467
+ [
468
+ ".",
469
+ ","
470
+ ]
471
+ ]
472
+ ]);
473
+ var NumberFormatter = class {
474
+ static {
475
+ __name(this, "NumberFormatter");
476
+ }
477
+ // The number of decimals to round to.
478
+ precision;
479
+ // The character to use as thousand separator.
480
+ thousandSeparator = ",";
481
+ // The character to use as decimal separator.
482
+ decimalSeparator = ".";
483
+ /**
484
+ * Create a new number formatter.
485
+ * @param precision The number of decimals to round to.
486
+ */
487
+ constructor(precision = 2) {
488
+ this.precision = precision;
489
+ }
490
+ /**
491
+ * Set separator strings for a given locale.
492
+ */
493
+ static defineLocale(locale, thousandSeparator, decimalSeparator) {
494
+ locales.set(locale, [
495
+ thousandSeparator,
496
+ decimalSeparator
497
+ ]);
498
+ }
499
+ /**
500
+ * Returns a copy of the locales map.
501
+ */
502
+ static getLocales() {
503
+ const result = /* @__PURE__ */ new Map();
504
+ for (const entry of locales.entries()) {
505
+ result.set(entry[0], [
506
+ entry[1][0],
507
+ entry[1][1]
508
+ ]);
509
+ }
510
+ return result;
511
+ }
512
+ /**
513
+ * Set the locale for the number formatter.
514
+ */
515
+ locale(locale) {
516
+ const sep = locales.get(locale);
517
+ if (!sep) {
518
+ throw new Error(`Invalid locale: ${locale}. Valid: ${Array.from(locales.keys())}}.`);
519
+ }
520
+ this.thousandSeparator = sep[0];
521
+ this.decimalSeparator = sep[1];
522
+ return this;
523
+ }
524
+ /**
525
+ * Format a number to a string.
526
+ */
527
+ format(number) {
528
+ const negative = number >= 0 ? "" : "-";
529
+ const split = Math.abs(round(number, this.precision)).toString().split(".");
530
+ const decimals = this.precision ? this.decimalSeparator + (split[1] || "").padEnd(this.precision, "0") : "";
531
+ let result = "";
532
+ for (let i = 0; i < split[0].length; i++) {
533
+ if (i % 3 === 0 && i !== 0) {
534
+ result = this.thousandSeparator + result;
535
+ }
536
+ result = split[0][split[0].length - i - 1] + result;
537
+ }
538
+ return negative + result + decimals;
539
+ }
540
+ /**
541
+ * Parse a formatted string to a number.
542
+ */
543
+ parse(string) {
544
+ string = string.replaceAll(this.thousandSeparator, "").replace(this.decimalSeparator, ".").replaceAll(/[^\d.-]/g, "").split(".").map((s) => {
545
+ return parseInt(s);
546
+ }).join(".");
547
+ const n = Number(string);
548
+ return n;
549
+ }
550
+ };
551
+
552
+ // ../decorators/src/assertDescriptorValueIsFunction.ts
553
+ function assertDescriptorValueIsFunction(key, descriptor) {
554
+ if (!(typeof descriptor.value === "function" && descriptor.value !== Function.prototype)) {
555
+ throw new TypeError(`"value" not a function for ${key} with descriptor: ${JSON.stringify(descriptor)}.`);
556
+ }
557
+ }
558
+ __name(assertDescriptorValueIsFunction, "assertDescriptorValueIsFunction");
559
+
560
+ // ../map/src/mapGetOrDefault.ts
561
+ function mapGetOrDefault(map, key, factory) {
562
+ let value = map.get(key);
563
+ if (value !== void 0 || map.has(key)) {
564
+ return value;
565
+ }
566
+ value = factory(key, map);
567
+ map.set(key, value);
568
+ return value;
569
+ }
570
+ __name(mapGetOrDefault, "mapGetOrDefault");
571
+
572
+ // ../map/src/TimeoutWeakMap.ts
573
+ var TimeoutWeakMap = class {
574
+ static {
575
+ __name(this, "TimeoutWeakMap");
576
+ }
577
+ timeoutMs;
578
+ wmap = /* @__PURE__ */ new WeakMap();
579
+ /**
580
+ * @param timeoutMs Default timeout in milliseconds for entries
581
+ */
582
+ constructor(timeoutMs) {
583
+ this.timeoutMs = timeoutMs;
584
+ }
585
+ /**
586
+ * Retrieves the value for the given key and refreshes its timeout.
587
+ *
588
+ * @param key The key to retrieve
589
+ * @returns The value if found, undefined otherwise
590
+ */
591
+ get(key) {
592
+ const vt = this.wmap.get(key);
593
+ if (!vt) {
594
+ return void 0;
595
+ }
596
+ const [value, timeout] = vt;
597
+ timeout.refresh();
598
+ return value;
599
+ }
600
+ /**
601
+ * Sets a key-value pair with an optional custom timeout.
602
+ *
603
+ * @param key The key to set
604
+ * @param value The value to associate with the key
605
+ * @param timeoutMs Optional timeout override for this entry
606
+ * @returns This instance for chaining
607
+ */
608
+ set(key, value, timeoutMs) {
609
+ this.wmap.set(key, [
610
+ value,
611
+ setTimeout(() => {
612
+ this.delete(key);
613
+ }, timeoutMs ?? this.timeoutMs).unref()
614
+ ]);
615
+ return this;
616
+ }
617
+ /**
618
+ * Removes a key-value pair and clears its timeout.
619
+ *
620
+ * @param key The key to delete
621
+ * @returns True if the key existed and was deleted, false otherwise
622
+ */
623
+ delete(key) {
624
+ const vt = this.wmap.get(key);
625
+ if (!vt) {
626
+ return false;
627
+ }
628
+ const timeout = vt[1];
629
+ clearTimeout(timeout);
630
+ return this.wmap.delete(key);
631
+ }
632
+ /**
633
+ * Checks if a key exists in the map.
634
+ * Does not refresh the timeout.
635
+ *
636
+ * @param key The key to check
637
+ * @returns True if the key exists, false otherwise
638
+ */
639
+ has(key) {
640
+ return this.wmap.has(key);
641
+ }
642
+ /**
643
+ * Loads multiple key-value pairs into the map.
644
+ *
645
+ * @param entries Iterable of key-value pairs to load
646
+ * @param timeoutMs Optional timeout override for all entries
647
+ * @returns This instance for chaining
648
+ */
649
+ load(entries, timeoutMs) {
650
+ for (const [key, value] of entries) {
651
+ this.set(key, value, timeoutMs);
652
+ }
653
+ return this;
654
+ }
655
+ /**
656
+ * Updates an existing value or creates a new one using an update function.
657
+ *
658
+ * @param key The key to update
659
+ * @param update Function that receives the current value and returns the new value
660
+ * @returns This instance for chaining
661
+ */
662
+ update(key, update) {
663
+ return this.set(key, update(this.get(key), key, this));
664
+ }
665
+ /**
666
+ * Gets a value or creates it using a factory function if it doesn't exist.
667
+ * Refreshes timeout if the value exists.
668
+ *
669
+ * @param key The key to get or create
670
+ * @param factory Function to create the value if it doesn't exist
671
+ * @param timeoutMs Optional timeout override for new entries
672
+ * @returns The existing or newly created value
673
+ */
674
+ getOrDefault(key, factory, timeoutMs) {
675
+ const vt = this.wmap.get(key);
676
+ if (vt) {
677
+ const [value, timeout] = vt;
678
+ timeout.refresh();
679
+ return value;
680
+ } else {
681
+ const value = factory(key, this);
682
+ this.set(key, value, timeoutMs);
683
+ return value;
684
+ }
685
+ }
686
+ };
687
+ function memoizeSync(arg = {}) {
688
+ const opts = typeof arg === "object" ? arg : {
689
+ maxAge: typeof arg === "number" ? arg : ms(arg)
690
+ };
691
+ return /* @__PURE__ */ __name(function decorator(target, key, descriptor) {
692
+ if (!descriptor) {
693
+ throw new TypeError("descriptor is undefined");
694
+ }
695
+ const orig = descriptor.value;
696
+ assertDescriptorValueIsFunction(key, descriptor);
697
+ const options = {
698
+ length: false,
699
+ ...opts
700
+ };
701
+ if (opts.instancesShareCache) {
702
+ Reflect.deleteProperty(options, "instancesShareCache");
703
+ descriptor.value = memoizee(orig, options);
704
+ } else {
705
+ const wmap = /* @__PURE__ */ new WeakMap();
706
+ descriptor.value = function(...args) {
707
+ const memoized = mapGetOrDefault(wmap, this, () => {
708
+ return memoizee(orig, options);
709
+ });
710
+ return memoized.apply(this, args);
711
+ };
712
+ }
713
+ return descriptor;
714
+ }, "decorator");
715
+ }
716
+ __name(memoizeSync, "memoizeSync");
717
+ function lazyProp(targetOrTimeout, key, descriptor) {
718
+ if (typeof targetOrTimeout === "number" || typeof targetOrTimeout === "string") {
719
+ const maxAge = typeof targetOrTimeout === "number" ? targetOrTimeout : ms(targetOrTimeout);
720
+ return createLazyPropDecorator(new TimeoutWeakMap(maxAge));
721
+ } else {
722
+ const decorator = createLazyPropDecorator(/* @__PURE__ */ new WeakMap());
723
+ return decorator(targetOrTimeout, key, descriptor);
724
+ }
725
+ }
726
+ __name(lazyProp, "lazyProp");
727
+ function createLazyPropDecorator(map) {
728
+ return function(target, key, descriptor) {
729
+ const { get, value } = descriptor;
730
+ if (isFunction(get)) {
731
+ descriptor.get = function() {
732
+ return mapGetOrDefault(map, this, () => {
733
+ return get.call(this);
734
+ });
735
+ };
736
+ return descriptor;
737
+ }
738
+ if (isFunction(value)) {
739
+ return memoizeSync()(target, key, descriptor);
740
+ }
741
+ throw new TypeError('neither "get" nor "value" are functions');
742
+ };
743
+ }
744
+ __name(createLazyPropDecorator, "createLazyPropDecorator");
745
+
746
+ // ../table/src/TableFormatter.ts
747
+ function _ts_decorate(decorators, target, key, desc) {
748
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
749
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
750
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
751
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
752
+ }
753
+ __name(_ts_decorate, "_ts_decorate");
754
+ function _ts_metadata(k, v) {
755
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
756
+ }
757
+ __name(_ts_metadata, "_ts_metadata");
758
+ var TableFormatter = class _TableFormatter {
759
+ static {
760
+ __name(this, "TableFormatter");
761
+ }
762
+ static defaults = {
763
+ columnSeparator: " | ",
764
+ headerRowSeparator: "-",
765
+ grayOutRow: void 0,
766
+ color: {
767
+ separator: colors.dim.gray,
768
+ columnHeader: colors.cyan,
769
+ rowHeader: /* @__PURE__ */ __name((s) => {
770
+ return s;
771
+ }, "rowHeader"),
772
+ string: colors.green,
773
+ positiveNumber: colors.yellow,
774
+ negativeNumber: colors.yellow,
775
+ booleanTrue: colors.magenta,
776
+ booleanFalse: colors.magenta
777
+ }
778
+ };
779
+ table;
780
+ options;
781
+ constructor(table, options) {
782
+ this.table = table;
783
+ this.options = this.handleOptions(options);
784
+ }
785
+ get numberColumnPrecisions() {
786
+ return this.table.reduce((acc, row) => {
787
+ return row.map((cell, c) => {
788
+ if (typeof cell !== "number") {
789
+ return;
790
+ }
791
+ if (Number.isInteger(cell)) {
792
+ return 0;
793
+ }
794
+ const digits = cell.toString().split(".")[1].length;
795
+ return Math.max(acc[c] || 0, digits);
796
+ });
797
+ }, []);
798
+ }
799
+ get stringsTable() {
800
+ return this.table.map((row) => {
801
+ return row.map((cell, c) => {
802
+ return this.cellToString(cell, c);
803
+ });
804
+ });
805
+ }
806
+ get columnWidths() {
807
+ return this.stringsTable.reduce((acc, row) => {
808
+ return row.map((cell, c) => {
809
+ return Math.max(acc[c] || 0, cell.length);
810
+ });
811
+ }, []);
812
+ }
813
+ get tableWidth() {
814
+ const separatorsWidth = (this.columnWidths.length - 1) * this.options.columnSeparator.length;
815
+ const columnsWidth = this.columnWidths.reduce((acc, width) => {
816
+ return acc + width;
817
+ }, 0);
818
+ return columnsWidth + separatorsWidth;
819
+ }
820
+ get columnSeparatorFormatted() {
821
+ return this.options.color.separator(this.options.columnSeparator);
822
+ }
823
+ get headerRowSeparatorLineFormatted() {
824
+ return this.options.color.separator("".padEnd(this.tableWidth, this.options.headerRowSeparator));
825
+ }
826
+ get formattedRows() {
827
+ const result = this.stringsTable.map((row, r) => {
828
+ return row.map((cell, c) => {
829
+ return this.formatCell(cell, c, r);
830
+ });
831
+ });
832
+ if (!this.options.color || !this.options.grayOutRow) {
833
+ return result;
834
+ }
835
+ return result.map((row, r) => {
836
+ if (!this.options.grayOutRow(this.table[r])) {
837
+ return row;
838
+ }
839
+ return row.map((cell) => {
840
+ return this.options.color.separator(colors.stripColor(cell));
841
+ });
842
+ });
843
+ }
844
+ get formattedLines() {
845
+ const lines = this.formattedRows.map((row) => {
846
+ return row.join(this.columnSeparatorFormatted);
847
+ });
848
+ lines.splice(1, 0, this.headerRowSeparatorLineFormatted);
849
+ const headersLine = lines[0];
850
+ lines.push(this.headerRowSeparatorLineFormatted);
851
+ lines.push(headersLine);
852
+ return lines;
853
+ }
854
+ toString() {
855
+ return this.formattedLines.join("\n");
856
+ }
857
+ handleOptions(options = {}) {
858
+ options = {
859
+ ...options
860
+ };
861
+ if (!options.columnSeparator) {
862
+ options.columnSeparator = _TableFormatter.defaults.columnSeparator;
863
+ }
864
+ if (!options.headerRowSeparator) {
865
+ options.headerRowSeparator = _TableFormatter.defaults.headerRowSeparator;
866
+ }
867
+ options.color = options.color ? options.color === true ? _TableFormatter.defaults.color : {
868
+ ..._TableFormatter.defaults.color,
869
+ ...options.color
870
+ } : defaultColorsNoop;
871
+ return options;
872
+ }
873
+ cellToString(cell, c) {
874
+ if (cell == null) {
875
+ return "";
876
+ } else if (typeof cell === "string") {
877
+ return cell;
878
+ } else if (typeof cell === "boolean") {
879
+ return cell.toString();
880
+ } else if (typeof cell === "number") {
881
+ return new NumberFormatter(this.numberColumnPrecisions[c] ?? 0).format(cell);
882
+ } else if (Array.isArray(cell)) {
883
+ return `[${cell.join(", ")}]`;
884
+ } else {
885
+ throw new TypeError(`Unexpected cell value type: ${typeof cell}`);
886
+ }
887
+ }
888
+ formatCell(cell, c, r) {
889
+ const originalCell = this.table[r][c];
890
+ if (originalCell == null) {
891
+ return this.formatNil(cell, c);
892
+ } else if (typeof originalCell === "string") {
893
+ return this.formatString(cell, r, c);
894
+ } else if (typeof originalCell === "boolean") {
895
+ return this.formatBoolean(cell, c);
896
+ } else if (typeof originalCell === "number") {
897
+ return this.formatNumber(cell, originalCell, c);
898
+ } else if (Array.isArray(originalCell)) {
899
+ return this.formatString(cell, r, c);
900
+ } else {
901
+ throw new TypeError(`Unexpected cell value type: ${typeof originalCell}`);
902
+ }
903
+ }
904
+ formatNil(cell, c) {
905
+ return this.alignLeft(cell, c);
906
+ }
907
+ formatString(cell, r, c) {
908
+ cell = this.alignLeft(cell, c);
909
+ if (this.isColumnHeader(r)) {
910
+ return this.options.color.columnHeader(cell);
911
+ }
912
+ if (this.isRowHeader(c)) {
913
+ return this.options.color.rowHeader(cell);
914
+ }
915
+ return this.options.color.string(cell);
916
+ }
917
+ formatBoolean(cell, c) {
918
+ const padded = this.alignLeft(cell, c);
919
+ if (cell === "true") {
920
+ return this.options.color.booleanTrue(padded);
921
+ }
922
+ if (cell === "false") {
923
+ return this.options.color.booleanFalse(padded);
924
+ }
925
+ throw new Error(`Unexpected boolean representation: ${cell}`);
926
+ }
927
+ formatNumber(cell, originalCell, c) {
928
+ cell = this.alignRight(cell, c);
929
+ if ((originalCell ?? 0) < 0) {
930
+ return this.options.color.negativeNumber(cell);
931
+ }
932
+ return this.options.color.positiveNumber(cell);
933
+ }
934
+ alignLeft(cell, c) {
935
+ return cell.padEnd(this.columnWidths[c], " ");
936
+ }
937
+ alignRight(cell, c) {
938
+ return cell.padStart(this.columnWidths[c], " ");
939
+ }
940
+ isColumnHeader(r) {
941
+ return r === 0;
942
+ }
943
+ isRowHeader(c) {
944
+ return c === 0;
945
+ }
946
+ };
947
+ _ts_decorate([
948
+ lazyProp,
949
+ _ts_metadata("design:type", Array),
950
+ _ts_metadata("design:paramtypes", [])
951
+ ], TableFormatter.prototype, "numberColumnPrecisions", null);
952
+ _ts_decorate([
953
+ lazyProp,
954
+ _ts_metadata("design:type", Array),
955
+ _ts_metadata("design:paramtypes", [])
956
+ ], TableFormatter.prototype, "stringsTable", null);
957
+ _ts_decorate([
958
+ lazyProp,
959
+ _ts_metadata("design:type", Array),
960
+ _ts_metadata("design:paramtypes", [])
961
+ ], TableFormatter.prototype, "columnWidths", null);
962
+ _ts_decorate([
963
+ lazyProp,
964
+ _ts_metadata("design:type", Number),
965
+ _ts_metadata("design:paramtypes", [])
966
+ ], TableFormatter.prototype, "tableWidth", null);
967
+ _ts_decorate([
968
+ lazyProp,
969
+ _ts_metadata("design:type", void 0),
970
+ _ts_metadata("design:paramtypes", [])
971
+ ], TableFormatter.prototype, "columnSeparatorFormatted", null);
972
+ _ts_decorate([
973
+ lazyProp,
974
+ _ts_metadata("design:type", void 0),
975
+ _ts_metadata("design:paramtypes", [])
976
+ ], TableFormatter.prototype, "headerRowSeparatorLineFormatted", null);
977
+ _ts_decorate([
978
+ lazyProp,
979
+ _ts_metadata("design:type", Array),
980
+ _ts_metadata("design:paramtypes", [])
981
+ ], TableFormatter.prototype, "formattedRows", null);
982
+ _ts_decorate([
983
+ lazyProp,
984
+ _ts_metadata("design:type", void 0),
985
+ _ts_metadata("design:paramtypes", [])
986
+ ], TableFormatter.prototype, "formattedLines", null);
987
+ var defaultColorsNoop = {
988
+ separator: /* @__PURE__ */ __name((s) => {
989
+ return s;
990
+ }, "separator"),
991
+ columnHeader: /* @__PURE__ */ __name((s) => {
992
+ return s;
993
+ }, "columnHeader"),
994
+ rowHeader: /* @__PURE__ */ __name((s) => {
995
+ return s;
996
+ }, "rowHeader"),
997
+ string: /* @__PURE__ */ __name((s) => {
998
+ return s;
999
+ }, "string"),
1000
+ positiveNumber: /* @__PURE__ */ __name((s) => {
1001
+ return s;
1002
+ }, "positiveNumber"),
1003
+ negativeNumber: /* @__PURE__ */ __name((s) => {
1004
+ return s;
1005
+ }, "negativeNumber"),
1006
+ booleanTrue: /* @__PURE__ */ __name((s) => {
1007
+ return s;
1008
+ }, "booleanTrue"),
1009
+ booleanFalse: /* @__PURE__ */ __name((s) => {
1010
+ return s;
1011
+ }, "booleanFalse")
1012
+ };
1013
+ var Profiler = class _Profiler {
1014
+ static {
1015
+ __name(this, "Profiler");
1016
+ }
1017
+ static enabled = true;
1018
+ static get data() {
1019
+ return FunctionProfiler.instances.slice();
1020
+ }
1021
+ /**
1022
+ *
1023
+ */
1024
+ static class(targetOrOptions, options) {
1025
+ if (isFunction(targetOrOptions)) {
1026
+ const target = targetOrOptions;
1027
+ _Profiler.classStatic(target, options?.ignoreStaticKeys);
1028
+ _Profiler.classPrototype(target, options?.ignorePrototypeKeys);
1029
+ return target;
1030
+ } else {
1031
+ return (target) => {
1032
+ return _Profiler.class(target, targetOrOptions);
1033
+ };
1034
+ }
1035
+ }
1036
+ static classStatic(target, ignoreKeys) {
1037
+ if (_Profiler.enabled) {
1038
+ wrapMethods(target, new ProfilerWrapMethodsStrategy(new StaticMethodProfilerFactory(target), [
1039
+ ...ignoreKeys ?? [],
1040
+ ...target.profiler?.ignoreStaticKeys ?? []
1041
+ ]));
1042
+ }
1043
+ return target;
1044
+ }
1045
+ static classPrototype(target, ignoreKeys) {
1046
+ if (_Profiler.enabled) {
1047
+ wrapMethods(target.prototype, new ProfilerWrapMethodsStrategy(new PrototypeMethodProfilerFactory(target.prototype), [
1048
+ ...ignoreKeys ?? [],
1049
+ ...target.profiler?.ignorePrototypeKeys ?? []
1050
+ ]));
1051
+ }
1052
+ return target;
1053
+ }
1054
+ static module(target, moduleName, ignoreKeys) {
1055
+ if (_Profiler.enabled) {
1056
+ wrapMethods(target, new ProfilerWrapMethodsStrategy(new ModuleMethodProfilerFactory(moduleName, target), ignoreKeys));
1057
+ }
1058
+ return target;
1059
+ }
1060
+ static fn(nameOrFunc, maybeFunc) {
1061
+ const func = isFunction(nameOrFunc) ? nameOrFunc : setName(nameOrFunc, maybeFunc);
1062
+ if (!func.name) {
1063
+ throw new Error(`Function must have a name:
1064
+ ${func.toString()}`);
1065
+ }
1066
+ if (_Profiler.enabled) {
1067
+ return profilerWrap(func, new FunctionProfiler(new StandaloneFunctionIdentifier(func)));
1068
+ }
1069
+ return func;
1070
+ }
1071
+ static getResults(options) {
1072
+ const results = _Profiler.data.map((profiler) => {
1073
+ return [
1074
+ profiler.id.name,
1075
+ profiler.getResult()
1076
+ ];
1077
+ });
1078
+ const sortkey1 = options?.sortBy ?? "calls";
1079
+ const sortValue1 = /* @__PURE__ */ __name((entry) => {
1080
+ return entry[1][sortkey1] ?? -1;
1081
+ }, "sortValue1");
1082
+ const sortKey2 = sortkey1 === "calls" ? "totalTimeUs" : "calls";
1083
+ const sortValue2 = /* @__PURE__ */ __name((entry) => {
1084
+ return entry[1][sortKey2] ?? -1;
1085
+ }, "sortValue2");
1086
+ return results.sort((a, b) => {
1087
+ const comparision = sortValue1(a) - sortValue1(b);
1088
+ if (comparision !== 0) {
1089
+ return comparision;
1090
+ }
1091
+ return sortValue2(a) - sortValue2(b);
1092
+ });
1093
+ }
1094
+ static printResults(options) {
1095
+ let entries = this.getResults(options);
1096
+ if (options?.update) {
1097
+ entries = options.update(entries);
1098
+ }
1099
+ const headers = [
1100
+ "Execution time (microseconds)",
1101
+ "calls",
1102
+ "total",
1103
+ "avg",
1104
+ "min",
1105
+ "max"
1106
+ ];
1107
+ const rows = entries.map(([method, stats]) => {
1108
+ return [
1109
+ method,
1110
+ stats.calls,
1111
+ stats.totalTimeUs,
1112
+ stats.avgTimeUs,
1113
+ stats.minTimeUs,
1114
+ stats.maxTimeUs
1115
+ ];
1116
+ });
1117
+ const table = [
1118
+ headers,
1119
+ ...rows
1120
+ ];
1121
+ const formatter = new TableFormatter(table, {
1122
+ color: !options?.noColor,
1123
+ grayOutRow: /* @__PURE__ */ __name((row) => {
1124
+ return row[1] === 0;
1125
+ }, "grayOutRow")
1126
+ });
1127
+ console.log();
1128
+ formatter.formattedLines.forEach((line) => {
1129
+ return console.log(line);
1130
+ });
1131
+ console.log();
1132
+ }
1133
+ static [inspect.custom](depth, options = {}) {
1134
+ options.compact = true;
1135
+ return Object.fromEntries(this.getResults());
1136
+ }
1137
+ static toJSON() {
1138
+ return this.getResults();
1139
+ }
1140
+ };
1141
+
1142
+ export { Profiler };