@bemoje/profiler 2.0.0 → 2.2.0

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