@bemoje/monorepo 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.d.ts +636 -0
  2. package/index.mjs +2330 -0
  3. package/package.json +50 -0
package/index.mjs ADDED
@@ -0,0 +1,2330 @@
1
+ import { mapValues, cloneDeep } from 'es-toolkit/object';
2
+ import colors2 from 'ansi-colors';
3
+ import { inspect, promisify } from 'util';
4
+ import { isObjectLike, omit } from 'es-toolkit/compat';
5
+ import { DefaultMap, MultiSet } from 'mnemonist';
6
+ import fs from 'fs';
7
+ import { isFunction } from 'es-toolkit/predicate';
8
+ import memoizee from 'memoizee';
9
+ import { ms } from 'enhanced-ms';
10
+ import path2 from 'upath';
11
+ import { builtinModules } from 'module';
12
+ import strip from 'strip-comments';
13
+ import { difference, union } from 'es-toolkit/array';
14
+ import { exec } from 'child_process';
15
+ import fs3, { readJsonSync } from 'fs-extra/esm';
16
+ import { resolveModuleName, createCompilerHost } from 'typescript';
17
+ import fs2 from 'fs-extra';
18
+ import onetime from 'onetime';
19
+ import walkdir from 'walkdir';
20
+ import { glob, globSync } from 'glob';
21
+
22
+ var __defProp = Object.defineProperty;
23
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
24
+
25
+ // ../composition/src/View.ts
26
+ var TARGET_SYMBOL = /* @__PURE__ */ Symbol("target");
27
+ var View = class {
28
+ static {
29
+ __name(this, "View");
30
+ }
31
+ [TARGET_SYMBOL];
32
+ constructor(target) {
33
+ this[TARGET_SYMBOL] = target;
34
+ }
35
+ get [Symbol.toStringTag]() {
36
+ return this.constructor.name;
37
+ }
38
+ get target() {
39
+ return this[TARGET_SYMBOL];
40
+ }
41
+ };
42
+
43
+ // ../is/src/isConstructor.ts
44
+ function isConstructor(value) {
45
+ if (typeof value !== "function") {
46
+ return false;
47
+ }
48
+ if (!value.prototype || value.prototype.constructor !== value) {
49
+ return false;
50
+ }
51
+ return true;
52
+ }
53
+ __name(isConstructor, "isConstructor");
54
+
55
+ // ../object/src/defineGetter.ts
56
+ function defineGetter(obj, key, get, des = {}) {
57
+ return Object.defineProperty(obj, key, {
58
+ configurable: true,
59
+ enumerable: false,
60
+ get,
61
+ ...des
62
+ });
63
+ }
64
+ __name(defineGetter, "defineGetter");
65
+
66
+ // ../object/src/defineValue.ts
67
+ function defineValue(obj, key, value, des = {}) {
68
+ return Object.defineProperty(obj, key, {
69
+ configurable: true,
70
+ value,
71
+ enumerable: true,
72
+ ...des
73
+ });
74
+ }
75
+ __name(defineValue, "defineValue");
76
+
77
+ // ../object/src/defineLazyProperty.ts
78
+ function defineLazyProperty(obj, key, get, des = {}) {
79
+ function getter() {
80
+ const value = get.call(this);
81
+ defineValue(this, key, value);
82
+ return value;
83
+ }
84
+ __name(getter, "getter");
85
+ return defineGetter(obj, key, getter, des);
86
+ }
87
+ __name(defineLazyProperty, "defineLazyProperty");
88
+
89
+ // ../object/src/defineMethod.ts
90
+ function defineMethod(obj, key, value, des = {}) {
91
+ return Object.defineProperty(obj, key, {
92
+ value,
93
+ configurable: true,
94
+ writable: true,
95
+ enumerable: false,
96
+ ...des
97
+ });
98
+ }
99
+ __name(defineMethod, "defineMethod");
100
+
101
+ // ../object/src/getClassChain.ts
102
+ function getClassChain(target, options) {
103
+ const ctor = isConstructor(target) ? target : target.constructor;
104
+ const result = [];
105
+ if (options?.includeSelf) {
106
+ result.push(ctor);
107
+ }
108
+ let current = ctor;
109
+ while (current = Reflect.getPrototypeOf(current)) {
110
+ if (current === Function.prototype || current === Object.prototype) {
111
+ result.push(Object);
112
+ break;
113
+ }
114
+ result.push(current);
115
+ }
116
+ return result;
117
+ }
118
+ __name(getClassChain, "getClassChain");
119
+
120
+ // ../object/src/hasOwnProperty.ts
121
+ function hasOwnProperty(object, key) {
122
+ return Object.prototype.hasOwnProperty.call(object, key);
123
+ }
124
+ __name(hasOwnProperty, "hasOwnProperty");
125
+
126
+ // ../object/src/hasPrototypeChainProperty.ts
127
+ function hasPrototypeChainProperty(object, key) {
128
+ return getClassChain(object).some((ctor) => {
129
+ return hasOwnProperty(ctor.prototype, key);
130
+ });
131
+ }
132
+ __name(hasPrototypeChainProperty, "hasPrototypeChainProperty");
133
+
134
+ // ../object/src/hasProperty.ts
135
+ function hasProperty(object, key) {
136
+ return hasOwnProperty(object, key) || hasPrototypeChainProperty(object, key);
137
+ }
138
+ __name(hasProperty, "hasProperty");
139
+
140
+ // ../map/src/mapGetOrDefault.ts
141
+ function mapGetOrDefault(map, key, factory) {
142
+ let value = map.get(key);
143
+ if (value !== void 0 || map.has(key)) {
144
+ return value;
145
+ }
146
+ value = factory(key, map);
147
+ map.set(key, value);
148
+ return value;
149
+ }
150
+ __name(mapGetOrDefault, "mapGetOrDefault");
151
+
152
+ // ../map/src/TimeoutWeakMap.ts
153
+ var TimeoutWeakMap = class {
154
+ static {
155
+ __name(this, "TimeoutWeakMap");
156
+ }
157
+ timeoutMs;
158
+ wmap = /* @__PURE__ */ new WeakMap();
159
+ /**
160
+ * @param timeoutMs Default timeout in milliseconds for entries
161
+ */
162
+ constructor(timeoutMs) {
163
+ this.timeoutMs = timeoutMs;
164
+ }
165
+ /**
166
+ * Retrieves the value for the given key and refreshes its timeout.
167
+ *
168
+ * @param key The key to retrieve
169
+ * @returns The value if found, undefined otherwise
170
+ */
171
+ get(key) {
172
+ const vt = this.wmap.get(key);
173
+ if (!vt) {
174
+ return void 0;
175
+ }
176
+ const [value, timeout] = vt;
177
+ timeout.refresh();
178
+ return value;
179
+ }
180
+ /**
181
+ * Sets a key-value pair with an optional custom timeout.
182
+ *
183
+ * @param key The key to set
184
+ * @param value The value to associate with the key
185
+ * @param timeoutMs Optional timeout override for this entry
186
+ * @returns This instance for chaining
187
+ */
188
+ set(key, value, timeoutMs) {
189
+ this.wmap.set(key, [
190
+ value,
191
+ setTimeout(() => {
192
+ this.delete(key);
193
+ }, timeoutMs ?? this.timeoutMs).unref()
194
+ ]);
195
+ return this;
196
+ }
197
+ /**
198
+ * Removes a key-value pair and clears its timeout.
199
+ *
200
+ * @param key The key to delete
201
+ * @returns True if the key existed and was deleted, false otherwise
202
+ */
203
+ delete(key) {
204
+ const vt = this.wmap.get(key);
205
+ if (!vt) {
206
+ return false;
207
+ }
208
+ const timeout = vt[1];
209
+ clearTimeout(timeout);
210
+ return this.wmap.delete(key);
211
+ }
212
+ /**
213
+ * Checks if a key exists in the map.
214
+ * Does not refresh the timeout.
215
+ *
216
+ * @param key The key to check
217
+ * @returns True if the key exists, false otherwise
218
+ */
219
+ has(key) {
220
+ return this.wmap.has(key);
221
+ }
222
+ /**
223
+ * Loads multiple key-value pairs into the map.
224
+ *
225
+ * @param entries Iterable of key-value pairs to load
226
+ * @param timeoutMs Optional timeout override for all entries
227
+ * @returns This instance for chaining
228
+ */
229
+ load(entries, timeoutMs) {
230
+ for (const [key, value] of entries) {
231
+ this.set(key, value, timeoutMs);
232
+ }
233
+ return this;
234
+ }
235
+ /**
236
+ * Updates an existing value or creates a new one using an update function.
237
+ *
238
+ * @param key The key to update
239
+ * @param update Function that receives the current value and returns the new value
240
+ * @returns This instance for chaining
241
+ */
242
+ update(key, update) {
243
+ return this.set(key, update(this.get(key), key, this));
244
+ }
245
+ /**
246
+ * Gets a value or creates it using a factory function if it doesn't exist.
247
+ * Refreshes timeout if the value exists.
248
+ *
249
+ * @param key The key to get or create
250
+ * @param factory Function to create the value if it doesn't exist
251
+ * @param timeoutMs Optional timeout override for new entries
252
+ * @returns The existing or newly created value
253
+ */
254
+ getOrDefault(key, factory, timeoutMs) {
255
+ const vt = this.wmap.get(key);
256
+ if (vt) {
257
+ const [value, timeout] = vt;
258
+ timeout.refresh();
259
+ return value;
260
+ } else {
261
+ const value = factory(key, this);
262
+ this.set(key, value, timeoutMs);
263
+ return value;
264
+ }
265
+ }
266
+ };
267
+
268
+ // ../composition/src/inspector/defaults/ignoreValuesFilterDefaults.ts
269
+ var ignoreValuesFilterDefaults = {
270
+ noFalse: /* @__PURE__ */ __name((value) => {
271
+ return value !== false;
272
+ }, "noFalse"),
273
+ noNull: /* @__PURE__ */ __name((value) => {
274
+ return value !== null;
275
+ }, "noNull"),
276
+ noUndefined: /* @__PURE__ */ __name((value) => {
277
+ return value !== void 0;
278
+ }, "noUndefined"),
279
+ noEmptyArray: /* @__PURE__ */ __name((value) => {
280
+ return !Array.isArray(value) || !!value.length;
281
+ }, "noEmptyArray"),
282
+ noEmptyObject: /* @__PURE__ */ __name((value) => {
283
+ return !value || typeof value !== "object" || Array.isArray(value) || !!Object.keys(value).length;
284
+ }, "noEmptyObject")
285
+ };
286
+
287
+ // ../composition/src/inspector/defaults/ignoreValuesDefaults.ts
288
+ var ignoreValuesDefaults = {
289
+ noEmptyArray: true,
290
+ noEmptyObject: true,
291
+ noNull: true,
292
+ noUndefined: true,
293
+ noFalse: false
294
+ };
295
+ var inspectDefaults = {
296
+ ...inspect.defaultOptions,
297
+ customInspect: true,
298
+ maxStringLength: 500,
299
+ maxArrayLength: 200,
300
+ breakLength: 100,
301
+ colors: true,
302
+ depth: 100,
303
+ compact: false,
304
+ numericSeparator: true
305
+ };
306
+
307
+ // ../composition/src/inspector/defaults/inspectorDefaults.ts
308
+ var inspectorDefaults = {
309
+ inspect: inspectDefaults,
310
+ ignoreValues: ignoreValuesDefaults,
311
+ keys: [],
312
+ autoAddBooleanKeys: false,
313
+ ignoreKeys: [],
314
+ filters: []
315
+ };
316
+ var Inspector = class _Inspector extends View {
317
+ static {
318
+ __name(this, "Inspector");
319
+ }
320
+ /**
321
+ * Composes a class with Inspector capabilities by adding inspection methods to its prototype.
322
+ * This follows the Composition pattern to extend classes without inheritance.
323
+ */
324
+ static compose(cls, options = {}) {
325
+ if (!hasProperty(cls.prototype, inspect.custom)) {
326
+ defineMethod(cls.prototype, inspect.custom, function(depth, options2) {
327
+ return this.inspector.inspect(depth, options2);
328
+ });
329
+ }
330
+ if (!hasProperty(cls.prototype, "inspector")) {
331
+ defineLazyProperty(cls.prototype, "inspector", /* @__PURE__ */ __name(function get() {
332
+ return new _Inspector(this);
333
+ }, "get"));
334
+ }
335
+ if (!hasProperty(cls.prototype, "toJSON")) {
336
+ defineMethod(cls.prototype, "toJSON", function() {
337
+ return this.inspector.toObject();
338
+ });
339
+ }
340
+ return options;
341
+ }
342
+ /**
343
+ * Compile the target object and return the output as an object.
344
+ */
345
+ toObject(depth = 0) {
346
+ const result = mapValues(this.compile(depth).output, (value) => {
347
+ if (!value) {
348
+ return value;
349
+ }
350
+ if (typeof value !== "object") {
351
+ return value;
352
+ }
353
+ if (Array.isArray(value)) {
354
+ return value.map((v) => {
355
+ if (v.inspector && v.inspector instanceof _Inspector) {
356
+ return v.inspector.toObject(depth + 1);
357
+ }
358
+ return v;
359
+ });
360
+ }
361
+ if (value.inspector && value.inspector instanceof _Inspector) {
362
+ return value.inspector.toObject(depth + 1);
363
+ }
364
+ return value;
365
+ });
366
+ return {
367
+ T: this.target.constructor.name,
368
+ ...result
369
+ };
370
+ }
371
+ /**
372
+ * Inspect the target object.
373
+ */
374
+ inspect(depth = 0, options = {}) {
375
+ const { output, inspectOptions } = this.compile(depth);
376
+ Object.assign(inspectOptions, options);
377
+ const result = inspect(output, options);
378
+ return result.replace(/Object \[\w+\] \{/gm, (match) => {
379
+ match = match.substring(8, match.length - 3);
380
+ return `[${inspectOptions.colors ? colors2.magenta(match) : match}] {`;
381
+ });
382
+ }
383
+ /**
384
+ * Compiles the output object and inspect options.
385
+ * Merges prototype chain options and applies filters to determine which properties to include.
386
+ */
387
+ compile(depth = 0) {
388
+ const output = Object.defineProperty({}, Symbol.toStringTag, {
389
+ value: this.target.constructor.name,
390
+ configurable: true
391
+ });
392
+ const options = this.mergePrototypeOptions();
393
+ const keys = new Set(options.keys);
394
+ if (options.autoAddBooleanKeys) {
395
+ const insBooleanValueKeys = Object.entries(this.target).filter(([_key, value]) => {
396
+ return typeof value === "boolean";
397
+ }).map(([key]) => {
398
+ return key;
399
+ });
400
+ const protoGetterKeys = getClassChain(this.target, {
401
+ includeSelf: false
402
+ }).map((cls) => {
403
+ return Object.getOwnPropertyNames(cls.prototype).filter((key) => {
404
+ return hasOwnProperty(Reflect.getOwnPropertyDescriptor(cls.prototype, key), "get");
405
+ });
406
+ }).flat(2);
407
+ const booleanKeys = insBooleanValueKeys.concat(protoGetterKeys).filter((key) => {
408
+ return /^(is|was|has|should)[A-Z]/.test(key);
409
+ });
410
+ booleanKeys.forEach((key) => {
411
+ return keys.add(key);
412
+ });
413
+ }
414
+ const ignoreFilters = Object.entries(options.ignoreValues).filter(([_name, enabled]) => {
415
+ return enabled;
416
+ }).map(([name]) => {
417
+ return ignoreValuesFilterDefaults[name];
418
+ });
419
+ const objectValues = [];
420
+ const arrayValues = [];
421
+ for (const key of keys) {
422
+ const value = this.target[key];
423
+ if (!ignoreFilters.every((filter) => {
424
+ return filter(value);
425
+ })) {
426
+ continue;
427
+ }
428
+ if (!options.filters.every((filter) => {
429
+ return filter.call(this.target, value, key, depth, output);
430
+ })) {
431
+ continue;
432
+ }
433
+ if (Array.isArray(value)) {
434
+ arrayValues.push(() => {
435
+ return defineValue(output, key, value);
436
+ });
437
+ } else if (isObjectLike(value)) {
438
+ objectValues.push(() => {
439
+ return defineValue(output, key, value);
440
+ });
441
+ } else {
442
+ defineValue(output, key, value);
443
+ }
444
+ }
445
+ objectValues.forEach((fn) => {
446
+ return fn();
447
+ });
448
+ arrayValues.forEach((fn) => {
449
+ return fn();
450
+ });
451
+ return {
452
+ output,
453
+ inspectOptions: options.inspect
454
+ };
455
+ }
456
+ /**
457
+ * Walks the prototype chain and merges Inspector options from all classes.
458
+ * Subclass options override superclass options following inheritance semantics.
459
+ */
460
+ mergePrototypeOptions() {
461
+ const defaults = this.getDefaults();
462
+ let inspectOptions = defaults.inspect;
463
+ const keys = new Set(defaults.keys);
464
+ let autoAddBooleanKeys = defaults.autoAddBooleanKeys;
465
+ const ignoreKeys = new Set(defaults.ignoreKeys);
466
+ const ignoreValues = defaults.ignoreValues;
467
+ const customFilters = defaults.filters;
468
+ const prototypeChainOptions = getClassChain(this.target.constructor, {
469
+ includeSelf: true
470
+ }).reverse().map((cls) => {
471
+ return cls.inspector ?? {};
472
+ });
473
+ for (const options of prototypeChainOptions) {
474
+ if (options.inspect) {
475
+ inspectOptions = {
476
+ ...inspectOptions,
477
+ ...options.inspect
478
+ };
479
+ }
480
+ options.keys?.forEach((elem) => {
481
+ return keys.add(elem);
482
+ });
483
+ if (options.autoAddBooleanKeys != null) {
484
+ autoAddBooleanKeys = options.autoAddBooleanKeys;
485
+ }
486
+ keys.forEach((elem) => {
487
+ return ignoreKeys.delete(elem);
488
+ });
489
+ options.ignoreKeys?.forEach((elem) => {
490
+ return ignoreKeys.add(elem);
491
+ });
492
+ ignoreKeys.forEach((elem) => {
493
+ return keys.delete(elem);
494
+ });
495
+ if (options.ignoreValues) {
496
+ Object.assign(ignoreValues, options.ignoreValues);
497
+ }
498
+ options.filters?.forEach((filter) => {
499
+ return customFilters.push(filter);
500
+ });
501
+ }
502
+ return {
503
+ inspect: inspectOptions,
504
+ ignoreValues,
505
+ autoAddBooleanKeys,
506
+ keys: Array.from(keys),
507
+ ignoreKeys: Array.from(ignoreKeys),
508
+ filters: customFilters
509
+ };
510
+ }
511
+ /**
512
+ * Returns a deep clone of the default Inspector options.
513
+ */
514
+ getDefaults() {
515
+ const filters = inspectorDefaults.filters.slice();
516
+ const rest = cloneDeep(omit(inspectorDefaults, "filters"));
517
+ return {
518
+ ...rest,
519
+ filters
520
+ };
521
+ }
522
+ };
523
+ var ParentRelationTypes = class _ParentRelationTypes extends View {
524
+ static {
525
+ __name(this, "ParentRelationTypes");
526
+ }
527
+ registerParent(parentType) {
528
+ _ParentRelationTypes.parentTypesStats.get(this.target).add(parentType);
529
+ _ParentRelationTypes.childTypesStats.get(parentType).add(this.target);
530
+ }
531
+ get hasParent() {
532
+ return _ParentRelationTypes.parentTypesStats.has(this.target);
533
+ }
534
+ get getParentTypes() {
535
+ return _ParentRelationTypes.parentTypesStats.get(this.target);
536
+ }
537
+ get hasChildren() {
538
+ return _ParentRelationTypes.childTypesStats.has(this.target);
539
+ }
540
+ get getChildTypes() {
541
+ return _ParentRelationTypes.childTypesStats.get(this.target);
542
+ }
543
+ get isRoot() {
544
+ return !this.hasParent && this.hasChildren;
545
+ }
546
+ get isLeaf() {
547
+ return this.hasParent && !this.hasChildren;
548
+ }
549
+ get isIsolated() {
550
+ return !this.hasParent && !this.hasChildren;
551
+ }
552
+ static getAllChildTypesStats() {
553
+ const res = {};
554
+ Array.from(this.childTypesStats.entries()).map(([cls, multimap]) => {
555
+ multimap.forEachMultiplicity((count, key) => {
556
+ if (!res[cls.name]) {
557
+ res[cls.name] = {};
558
+ }
559
+ if (!res[cls.name][key.name]) {
560
+ res[cls.name][key.name] = count;
561
+ }
562
+ });
563
+ });
564
+ return res;
565
+ }
566
+ static getAllParentTypesStats() {
567
+ const res = {};
568
+ Array.from(this.parentTypesStats.entries()).map(([cls, multimap]) => {
569
+ multimap.forEachMultiplicity((count, key) => {
570
+ if (!res[cls.name]) {
571
+ res[cls.name] = {};
572
+ }
573
+ if (!res[cls.name][key.name]) {
574
+ res[cls.name][key.name] = count;
575
+ }
576
+ });
577
+ });
578
+ return res;
579
+ }
580
+ static getAllStats() {
581
+ const classes = /* @__PURE__ */ new Set([
582
+ ...Array.from(this.childTypesStats.keys()),
583
+ ...Array.from(this.parentTypesStats.keys())
584
+ ]);
585
+ return Array.from(classes).map((cls) => {
586
+ const parents = Array.from(this.parentTypesStats.get(cls).multiplicities()).map(([cls2, count]) => {
587
+ return [
588
+ cls2.name,
589
+ count
590
+ ];
591
+ });
592
+ const children = Array.from(this.childTypesStats.get(cls).multiplicities()).map(([cls2, count]) => {
593
+ return [
594
+ cls2.name,
595
+ count
596
+ ];
597
+ });
598
+ const result = {
599
+ class: cls.name
600
+ };
601
+ if (parents.length) {
602
+ result.parents = Object.fromEntries(parents);
603
+ }
604
+ if (children.length) {
605
+ result.children = Object.fromEntries(children);
606
+ }
607
+ return result;
608
+ });
609
+ }
610
+ static printAllStats() {
611
+ console.log();
612
+ console.log(colors2.bold.yellow("Parent-Child Relation Stats"));
613
+ for (const stats of this.getAllStats()) {
614
+ console.log(stats.class);
615
+ if (stats.parents) {
616
+ let prefix = ` ${colors2.dim("parents : ")}`;
617
+ for (const [parent, count] of Object.entries(stats.parents)) {
618
+ console.log(`${prefix}${colors2.blue(parent)}: ${colors2.yellow(String(count))}`);
619
+ prefix = " ".repeat(12);
620
+ }
621
+ }
622
+ if (stats.children) {
623
+ let prefix = ` ${colors2.dim("children : ")}`;
624
+ for (const [child, count] of Object.entries(stats.children)) {
625
+ console.log(`${prefix}${colors2.green(child)}: ${colors2.yellow(String(count))}`);
626
+ prefix = " ".repeat(12);
627
+ }
628
+ }
629
+ console.log();
630
+ }
631
+ }
632
+ static childTypesStats = new DefaultMap(() => {
633
+ return new MultiSet();
634
+ });
635
+ static parentTypesStats = new DefaultMap(() => {
636
+ return new MultiSet();
637
+ });
638
+ };
639
+ var Parenting = class _Parenting extends View {
640
+ static {
641
+ __name(this, "Parenting");
642
+ }
643
+ /**
644
+ * Class decorator to register and correctly initialize a class as a 'parentingTarget'.
645
+ */
646
+ static compose(cls) {
647
+ if (!hasProperty(cls, "parenting")) {
648
+ defineLazyProperty(cls, "parenting", function() {
649
+ return new ParentRelationTypes(this);
650
+ });
651
+ }
652
+ if (!hasProperty(cls.prototype, "parenting")) {
653
+ defineLazyProperty(cls.prototype, "parenting", function() {
654
+ return new _Parenting(this);
655
+ });
656
+ }
657
+ }
658
+ /**
659
+ * Store a weak refences to the target object's parent.
660
+ */
661
+ onInstance(parent) {
662
+ if (!parent) {
663
+ return;
664
+ }
665
+ const targetClass = this.parentingTargetConstructor;
666
+ _Parenting.parentWeakRefMap.get(targetClass).set(this.target, parent);
667
+ targetClass.parenting?.registerParent(parent.constructor);
668
+ }
669
+ /**
670
+ * Retrieve the parent object of 'target' object.
671
+ */
672
+ getParent() {
673
+ const map = _Parenting.parentWeakRefMap.get(this.parentingTargetConstructor);
674
+ const parent = map.get(this.target);
675
+ return parent;
676
+ }
677
+ /**
678
+ * Recursively get parent until no parent is found or a circular reference is detected.
679
+ */
680
+ *iterateAncestors() {
681
+ let node = this.target.parenting.getParent();
682
+ if (!node) {
683
+ return;
684
+ }
685
+ const seen = /* @__PURE__ */ new Set();
686
+ while (node) {
687
+ if (seen.has(node)) {
688
+ return;
689
+ }
690
+ seen.add(node);
691
+ yield node;
692
+ node = node?.parenting?.getParent();
693
+ }
694
+ }
695
+ /**
696
+ * The depth of the object in the parent-child hierarchy.
697
+ */
698
+ get depth() {
699
+ return [
700
+ ...this.iterateAncestors()
701
+ ].length;
702
+ }
703
+ /**
704
+ * The class constructor of the target object.
705
+ */
706
+ get parentingTargetConstructor() {
707
+ return this.target.constructor;
708
+ }
709
+ /**
710
+ * A WeakMap for parent references.
711
+ */
712
+ static parentWeakRefMap = new DefaultMap(() => {
713
+ return /* @__PURE__ */ new WeakMap();
714
+ });
715
+ };
716
+
717
+ // src/common/AbstractBase.ts
718
+ function _ts_decorate(decorators, target, key, desc) {
719
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
720
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
721
+ 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;
722
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
723
+ }
724
+ __name(_ts_decorate, "_ts_decorate");
725
+ function _ts_metadata(k, v) {
726
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
727
+ }
728
+ __name(_ts_metadata, "_ts_metadata");
729
+ var AbstractBase = class _AbstractBase {
730
+ static {
731
+ __name(this, "AbstractBase");
732
+ }
733
+ static inspector = Inspector.compose(_AbstractBase, {
734
+ keys: [],
735
+ autoAddBooleanKeys: true,
736
+ ignoreKeys: [],
737
+ ignoreValues: {
738
+ noEmptyArray: true,
739
+ noEmptyObject: true,
740
+ noNull: true,
741
+ noUndefined: true,
742
+ noFalse: true
743
+ },
744
+ inspect: {
745
+ customInspect: true,
746
+ maxStringLength: 500,
747
+ maxArrayLength: 5,
748
+ breakLength: 80,
749
+ colors: true,
750
+ depth: null,
751
+ compact: false,
752
+ numericSeparator: true
753
+ },
754
+ filters: []
755
+ });
756
+ constructor(parent) {
757
+ this.parenting.onInstance(parent);
758
+ }
759
+ findParentDeep(predicate) {
760
+ for (const parent of this.parenting.iterateAncestors()) {
761
+ if (predicate(parent)) {
762
+ return parent;
763
+ }
764
+ }
765
+ return void 0;
766
+ }
767
+ get parent() {
768
+ return this.parenting.getParent();
769
+ }
770
+ getParentDeep(instanceOf) {
771
+ const parent = this.findParentDeep((p) => {
772
+ return p instanceof instanceOf;
773
+ });
774
+ if (!parent) {
775
+ throw new Error(`Parent of type ${instanceOf.name} not found.`);
776
+ }
777
+ return parent;
778
+ }
779
+ };
780
+ AbstractBase = _ts_decorate([
781
+ Parenting.compose,
782
+ _ts_metadata("design:type", Function),
783
+ _ts_metadata("design:paramtypes", [
784
+ typeof P === "undefined" ? Object : P
785
+ ])
786
+ ], AbstractBase);
787
+
788
+ // src/util/SemanticExtnamePrefix.ts
789
+ var SemanticExtnamePrefix = {
790
+ d: "d",
791
+ test: "test",
792
+ examples: "examples",
793
+ benchmark: "benchmark",
794
+ temp: "temp",
795
+ wip: "wip"
796
+ };
797
+
798
+ // ../fn/src/preserveNameAndLength.ts
799
+ function preserveNameAndLength(source, target, adjustLengthBy = 0) {
800
+ return Object.defineProperties(target, {
801
+ name: {
802
+ configurable: true,
803
+ value: source.name
804
+ },
805
+ length: {
806
+ configurable: true,
807
+ value: source.length + adjustLengthBy
808
+ }
809
+ });
810
+ }
811
+ __name(preserveNameAndLength, "preserveNameAndLength");
812
+
813
+ // ../fn/src/bindArg.ts
814
+ function bindArg(fn, boundArgIndex, boundArgValue) {
815
+ return preserveNameAndLength(fn, (...args) => {
816
+ return fn(...args.slice(0, boundArgIndex), boundArgValue, ...args.slice(boundArgIndex));
817
+ }, -1);
818
+ }
819
+ __name(bindArg, "bindArg");
820
+
821
+ // ../path/src/lib/hasExtname.ts
822
+ function hasExtname(tsFilepath, extnames) {
823
+ return new RegExp(`[.](${[
824
+ extnames
825
+ ].flat(2).join("|")})$`).test(tsFilepath);
826
+ }
827
+ __name(hasExtname, "hasExtname");
828
+ hasExtname.js = bindArg(hasExtname, 1, [
829
+ "js",
830
+ "mjs",
831
+ "jsx",
832
+ "cjs"
833
+ ]);
834
+ hasExtname.json = bindArg(hasExtname, 1, [
835
+ "json",
836
+ "jsonc"
837
+ ]);
838
+ hasExtname.yaml = bindArg(hasExtname, 1, [
839
+ "yaml",
840
+ "yml"
841
+ ]);
842
+ hasExtname.markdown = bindArg(hasExtname, 1, [
843
+ "md",
844
+ "markdown"
845
+ ]);
846
+ hasExtname.ts = bindArg(hasExtname, 1, [
847
+ "ts",
848
+ "mts",
849
+ "tsx"
850
+ ]);
851
+
852
+ // ../path/src/lib/hasParentDirname.ts
853
+ function hasParentDirname(fspath, name) {
854
+ return new RegExp(`(^|[/\\\\])${name}[/\\\\]`).test(fspath);
855
+ }
856
+ __name(hasParentDirname, "hasParentDirname");
857
+
858
+ // src/util/SemanticExtnamePrefixes.ts
859
+ var SemanticExtnamePrefixes_default = Object.values(SemanticExtnamePrefix);
860
+
861
+ // src/util/hasExtnamePrefix.ts
862
+ function hasExtnamePrefix(tsFilepath, prefixes = SemanticExtnamePrefixes_default) {
863
+ return new RegExp(`[.](${[
864
+ prefixes
865
+ ].flat(2).join("|")})[.][^/\\\\]+$`).test(tsFilepath);
866
+ }
867
+ __name(hasExtnamePrefix, "hasExtnamePrefix");
868
+
869
+ // ../decorators/src/assertDescriptorValueIsFunction.ts
870
+ function assertDescriptorValueIsFunction(key, descriptor) {
871
+ if (!(typeof descriptor.value === "function" && descriptor.value !== Function.prototype)) {
872
+ throw new TypeError(`"value" not a function for ${key} with descriptor: ${JSON.stringify(descriptor)}.`);
873
+ }
874
+ }
875
+ __name(assertDescriptorValueIsFunction, "assertDescriptorValueIsFunction");
876
+ function memoizeSync(arg = {}) {
877
+ const opts = typeof arg === "object" ? arg : {
878
+ maxAge: typeof arg === "number" ? arg : ms(arg)
879
+ };
880
+ return /* @__PURE__ */ __name(function decorator(target, key, descriptor) {
881
+ if (!descriptor) {
882
+ throw new TypeError("descriptor is undefined");
883
+ }
884
+ const orig = descriptor.value;
885
+ assertDescriptorValueIsFunction(key, descriptor);
886
+ const options = {
887
+ length: false,
888
+ ...opts
889
+ };
890
+ if (opts.instancesShareCache) {
891
+ Reflect.deleteProperty(options, "instancesShareCache");
892
+ descriptor.value = memoizee(orig, options);
893
+ } else {
894
+ const wmap = /* @__PURE__ */ new WeakMap();
895
+ descriptor.value = function(...args) {
896
+ const memoized = mapGetOrDefault(wmap, this, () => {
897
+ return memoizee(orig, options);
898
+ });
899
+ return memoized.apply(this, args);
900
+ };
901
+ }
902
+ return descriptor;
903
+ }, "decorator");
904
+ }
905
+ __name(memoizeSync, "memoizeSync");
906
+ function lazyProp(targetOrTimeout, key, descriptor) {
907
+ if (typeof targetOrTimeout === "number" || typeof targetOrTimeout === "string") {
908
+ const maxAge = typeof targetOrTimeout === "number" ? targetOrTimeout : ms(targetOrTimeout);
909
+ return createLazyPropDecorator(new TimeoutWeakMap(maxAge));
910
+ } else {
911
+ const decorator = createLazyPropDecorator(/* @__PURE__ */ new WeakMap());
912
+ return decorator(targetOrTimeout, key, descriptor);
913
+ }
914
+ }
915
+ __name(lazyProp, "lazyProp");
916
+ function createLazyPropDecorator(map) {
917
+ return function(target, key, descriptor) {
918
+ const { get, value } = descriptor;
919
+ if (isFunction(get)) {
920
+ descriptor.get = function() {
921
+ return mapGetOrDefault(map, this, () => {
922
+ return get.call(this);
923
+ });
924
+ };
925
+ return descriptor;
926
+ }
927
+ if (isFunction(value)) {
928
+ return memoizeSync()(target, key, descriptor);
929
+ }
930
+ throw new TypeError('neither "get" nor "value" are functions');
931
+ };
932
+ }
933
+ __name(createLazyPropDecorator, "createLazyPropDecorator");
934
+ function _ts_decorate2(decorators, target, key, desc) {
935
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
936
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
937
+ 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;
938
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
939
+ }
940
+ __name(_ts_decorate2, "_ts_decorate");
941
+ function _ts_metadata2(k, v) {
942
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
943
+ }
944
+ __name(_ts_metadata2, "_ts_metadata");
945
+ var File = class _File extends AbstractBase {
946
+ static {
947
+ __name(this, "File");
948
+ }
949
+ static inspector = Inspector.compose(_File, {
950
+ keys: [
951
+ "relative"
952
+ ]
953
+ });
954
+ path;
955
+ constructor(parent, filepath) {
956
+ super(parent);
957
+ this.path = path2.normalize(filepath);
958
+ }
959
+ get stats() {
960
+ return fs.statSync(this.path);
961
+ }
962
+ get isTs() {
963
+ return hasExtname(this.path, [
964
+ "ts",
965
+ "mts",
966
+ "tsx"
967
+ ]);
968
+ }
969
+ get isDotTs() {
970
+ return hasExtname(this.path, "ts");
971
+ }
972
+ get isDotTsx() {
973
+ return hasExtname(this.path, "tsx");
974
+ }
975
+ get isExample() {
976
+ return hasExtnamePrefix(this.path, SemanticExtnamePrefix.examples);
977
+ }
978
+ get isDeclaration() {
979
+ return hasExtnamePrefix(this.path, SemanticExtnamePrefix.d);
980
+ }
981
+ get isTest() {
982
+ return hasExtnamePrefix(this.path, SemanticExtnamePrefix.test);
983
+ }
984
+ get isIndexFile() {
985
+ return path2.parse(this.path).name === "index";
986
+ }
987
+ get isSourceFile() {
988
+ return hasParentDirname(this.path, "src") && !hasExtnamePrefix(this.path);
989
+ }
990
+ /**
991
+ * Read the file contents.
992
+ */
993
+ readFile() {
994
+ if (!fs.existsSync(this.path)) {
995
+ throw new Error(`File not found: ${this.path}`);
996
+ }
997
+ return fs.readFileSync(this.path, "utf8");
998
+ }
999
+ };
1000
+ _ts_decorate2([
1001
+ lazyProp(1e3),
1002
+ _ts_metadata2("design:type", typeof Stats === "undefined" ? Object : Stats),
1003
+ _ts_metadata2("design:paramtypes", [])
1004
+ ], File.prototype, "stats", null);
1005
+ File = _ts_decorate2([
1006
+ Parenting.compose,
1007
+ _ts_metadata2("design:type", Function),
1008
+ _ts_metadata2("design:paramtypes", [
1009
+ typeof P === "undefined" ? Object : P,
1010
+ String
1011
+ ])
1012
+ ], File);
1013
+
1014
+ // src/code/AbstractCode.ts
1015
+ function _ts_decorate3(decorators, target, key, desc) {
1016
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1017
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1018
+ 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;
1019
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1020
+ }
1021
+ __name(_ts_decorate3, "_ts_decorate");
1022
+ function _ts_metadata3(k, v) {
1023
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1024
+ }
1025
+ __name(_ts_metadata3, "_ts_metadata");
1026
+ var AbstractCode = class _AbstractCode extends AbstractBase {
1027
+ static {
1028
+ __name(this, "AbstractCode");
1029
+ }
1030
+ static inspector = Inspector.compose(_AbstractCode, {
1031
+ keys: []
1032
+ });
1033
+ static codePreviewOptions = {
1034
+ maxLines: 10,
1035
+ maxLineLength: 90
1036
+ };
1037
+ constructor(parent) {
1038
+ super(parent);
1039
+ }
1040
+ get path() {
1041
+ return this.getParentDeep(File).path;
1042
+ }
1043
+ get code() {
1044
+ return this.toString();
1045
+ }
1046
+ get isMultiLine() {
1047
+ return this.code.includes("\n");
1048
+ }
1049
+ get lines() {
1050
+ return this.code.split(/\r*\n/);
1051
+ }
1052
+ get codePreview() {
1053
+ const maxLines = _AbstractCode.codePreviewOptions.maxLines;
1054
+ const maxLineLength = _AbstractCode.codePreviewOptions.maxLineLength;
1055
+ const applyMaxLineLength = /* @__PURE__ */ __name((line) => {
1056
+ return line.length > maxLineLength ? `${line.substring(0, maxLineLength - 3)}...` : line;
1057
+ }, "applyMaxLineLength");
1058
+ return this.isMultiLine ? this.lines.slice(0, maxLines).map(applyMaxLineLength) : applyMaxLineLength(this.code);
1059
+ }
1060
+ codeIndexRangeOf(code) {
1061
+ const index = this.code.indexOf(code);
1062
+ if (index === -1) {
1063
+ throw new Error(`Code not found: ${code}`);
1064
+ }
1065
+ const lastIndex = index + code.length;
1066
+ return {
1067
+ index,
1068
+ lastIndex
1069
+ };
1070
+ }
1071
+ getCodeRange(range) {
1072
+ return this.code.substring(range.index, range.lastIndex);
1073
+ }
1074
+ };
1075
+ AbstractCode = _ts_decorate3([
1076
+ Parenting.compose,
1077
+ _ts_metadata3("design:type", Function),
1078
+ _ts_metadata3("design:paramtypes", [
1079
+ typeof P === "undefined" ? Object : P
1080
+ ])
1081
+ ], AbstractCode);
1082
+
1083
+ // src/code/CodeBlock.ts
1084
+ function _ts_decorate4(decorators, target, key, desc) {
1085
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1086
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1087
+ 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;
1088
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1089
+ }
1090
+ __name(_ts_decorate4, "_ts_decorate");
1091
+ function _ts_metadata4(k, v) {
1092
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1093
+ }
1094
+ __name(_ts_metadata4, "_ts_metadata");
1095
+ var CodeBlock = class _CodeBlock extends AbstractCode {
1096
+ static {
1097
+ __name(this, "CodeBlock");
1098
+ }
1099
+ static inspector = Inspector.compose(_CodeBlock, {
1100
+ keys: []
1101
+ });
1102
+ indexRange;
1103
+ constructor(parent, indexRange) {
1104
+ super(parent);
1105
+ this.indexRange = indexRange;
1106
+ }
1107
+ toString() {
1108
+ return this.parenting.getParent().getCodeRange(this.indexRange);
1109
+ }
1110
+ };
1111
+ _ts_decorate4([
1112
+ lazyProp(2500),
1113
+ _ts_metadata4("design:type", Function),
1114
+ _ts_metadata4("design:paramtypes", []),
1115
+ _ts_metadata4("design:returntype", String)
1116
+ ], CodeBlock.prototype, "toString", null);
1117
+ CodeBlock = _ts_decorate4([
1118
+ Parenting.compose,
1119
+ _ts_metadata4("design:type", Function),
1120
+ _ts_metadata4("design:paramtypes", [
1121
+ typeof P === "undefined" ? Object : P,
1122
+ Object
1123
+ ])
1124
+ ], CodeBlock);
1125
+
1126
+ // src/code/imports/ImportKeywords.ts
1127
+ function _ts_decorate5(decorators, target, key, desc) {
1128
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1129
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1130
+ 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;
1131
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1132
+ }
1133
+ __name(_ts_decorate5, "_ts_decorate");
1134
+ var ImportKeywords = class _ImportKeywords extends CodeBlock {
1135
+ static {
1136
+ __name(this, "ImportKeywords");
1137
+ }
1138
+ static inspector = Inspector.compose(_ImportKeywords, {
1139
+ keys: [
1140
+ "code"
1141
+ ]
1142
+ });
1143
+ get keywords() {
1144
+ return this.code.split(/\s+/).map((s) => {
1145
+ return s.trim();
1146
+ }).filter((s) => {
1147
+ return !!s;
1148
+ });
1149
+ }
1150
+ has(kw) {
1151
+ return this.keywords.includes(kw);
1152
+ }
1153
+ get isType() {
1154
+ return this.has("type");
1155
+ }
1156
+ };
1157
+ ImportKeywords = _ts_decorate5([
1158
+ Parenting.compose
1159
+ ], ImportKeywords);
1160
+
1161
+ // src/code/imports/ImportSpecifiers.ts
1162
+ function _ts_decorate6(decorators, target, key, desc) {
1163
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1164
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1165
+ 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;
1166
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1167
+ }
1168
+ __name(_ts_decorate6, "_ts_decorate");
1169
+ var ImportSpecifiers = class _ImportSpecifiers extends CodeBlock {
1170
+ static {
1171
+ __name(this, "ImportSpecifiers");
1172
+ }
1173
+ static inspector = Inspector.compose(_ImportSpecifiers, {
1174
+ keys: [
1175
+ "import",
1176
+ "type"
1177
+ ],
1178
+ autoAddBooleanKeys: false
1179
+ });
1180
+ get codeWithoutTypeKeyword() {
1181
+ return this.code.replace(/[\s]*\btype\b[\s]*/g, " ");
1182
+ }
1183
+ get type() {
1184
+ if (this.isMixedImport) {
1185
+ return "mixed";
1186
+ }
1187
+ if (this.isNamedImport) {
1188
+ return "named";
1189
+ }
1190
+ if (this.isNamespaceImport) {
1191
+ return "namespace";
1192
+ }
1193
+ return "default";
1194
+ }
1195
+ get isDefaultImport() {
1196
+ return /[a-zA-Z_$][\w$]*/.test(this.codeWithoutTypeKeyword) && !this.isNamespaceImport;
1197
+ }
1198
+ get isNamedImport() {
1199
+ return /\{[^}]+\}/.test(this.codeWithoutTypeKeyword);
1200
+ }
1201
+ get isMixedImport() {
1202
+ return /([a-zA-Z_$][\w$]*),\s*\{[^}]+\}/.test(this.codeWithoutTypeKeyword);
1203
+ }
1204
+ get isNamespaceImport() {
1205
+ return /\*\s+as\s+([a-zA-Z_$][\w$]*)/.test(this.codeWithoutTypeKeyword);
1206
+ }
1207
+ get namedImportsArray() {
1208
+ return this.code.replace("\n", " ").match(/\{([^}]+)\}/)?.[1].split(",").map((specifier) => {
1209
+ return specifier.trim();
1210
+ }).filter((s) => {
1211
+ return !!s;
1212
+ }) || [];
1213
+ }
1214
+ /**
1215
+ * Splits the import specifier into an array of specifiers as if to split into individual import statements.
1216
+ * @example `{A,B} => {A},{B}`
1217
+ */
1218
+ splitSpecifiers() {
1219
+ return this.isNamedImport ? this.namedImportsArray.map((n) => {
1220
+ return this.code.startsWith("type ") ? `type { ${n} }` : `{ ${n} }`;
1221
+ }) : [
1222
+ this.code
1223
+ ];
1224
+ }
1225
+ /**
1226
+ * Returns the keys added to the global namespace by this import specifier.
1227
+ */
1228
+ get importedNamesArray() {
1229
+ return this.codeWithoutTypeKeyword.replace(/[\w*]+ as \w+/, (m) => {
1230
+ return m.split(" as ")[1];
1231
+ }).replace(/[{}]/g, " ").split(",").map((s) => {
1232
+ return s.trim();
1233
+ }).filter(Boolean);
1234
+ }
1235
+ get defaultImport() {
1236
+ return this.codeWithoutTypeKeyword.match(/^([a-zA-Z_$][\w$]*)\s*(,|)/)?.[1] || void 0;
1237
+ }
1238
+ get namespaceImport() {
1239
+ return this.codeWithoutTypeKeyword.match(/^\*\s+as\s+([a-zA-Z_$][\w$]*)/)?.[1] || void 0;
1240
+ }
1241
+ get hasNamedImport() {
1242
+ return !!this.namedImportsArray.length;
1243
+ }
1244
+ get hasDefaultImport() {
1245
+ return !!this.defaultImport;
1246
+ }
1247
+ };
1248
+ ImportSpecifiers = _ts_decorate6([
1249
+ Parenting.compose
1250
+ ], ImportSpecifiers);
1251
+ function _ts_decorate7(decorators, target, key, desc) {
1252
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1253
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1254
+ 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;
1255
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1256
+ }
1257
+ __name(_ts_decorate7, "_ts_decorate");
1258
+ var ModuleSpecifier = class _ModuleSpecifier extends CodeBlock {
1259
+ static {
1260
+ __name(this, "ModuleSpecifier");
1261
+ }
1262
+ static inspector = Inspector.compose(_ModuleSpecifier, {
1263
+ keys: [
1264
+ "from"
1265
+ ]
1266
+ });
1267
+ /**
1268
+ * Alias for the `code` property.
1269
+ */
1270
+ get from() {
1271
+ return this.code;
1272
+ }
1273
+ get dependency() {
1274
+ if (!this.isDependency) {
1275
+ return void 0;
1276
+ }
1277
+ return this.code.split("/").slice(0, this.isScoped ? 2 : 1).join("/");
1278
+ }
1279
+ get isBuiltin() {
1280
+ return builtinModules.includes(this.code.replace(/^node:/i, ""));
1281
+ }
1282
+ get isScoped() {
1283
+ return this.code.startsWith("@");
1284
+ }
1285
+ get isRepoScoped() {
1286
+ return this.code.startsWith(`@${this.getParentDeep(MonoRepo).name}/`);
1287
+ }
1288
+ /**
1289
+ * Returns whether import is an other, but local workspace in the monorepo.
1290
+ */
1291
+ get isOtherRepoWorkspace() {
1292
+ return this.getParentDeep(MonoRepo).workspaces.map((ws) => {
1293
+ return ws.name;
1294
+ }).filter((name) => {
1295
+ return name !== this.getParentDeep(Workspace).name;
1296
+ }).some((name) => {
1297
+ return this.code.includes(name);
1298
+ });
1299
+ }
1300
+ get isRelative() {
1301
+ return this.code.startsWith(".");
1302
+ }
1303
+ get isFromRepoRoot() {
1304
+ return this.code.startsWith("/");
1305
+ }
1306
+ get isExternal() {
1307
+ return !this.isBuiltin && !this.isRepoScoped && !this.isRelative;
1308
+ }
1309
+ get isDependency() {
1310
+ return this.isExternal || this.isRepoScoped;
1311
+ }
1312
+ };
1313
+ ModuleSpecifier = _ts_decorate7([
1314
+ Parenting.compose
1315
+ ], ModuleSpecifier);
1316
+
1317
+ // src/file/TsFile.ts
1318
+ function _ts_decorate8(decorators, target, key, desc) {
1319
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1320
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1321
+ 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;
1322
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1323
+ }
1324
+ __name(_ts_decorate8, "_ts_decorate");
1325
+ function _ts_metadata5(k, v) {
1326
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1327
+ }
1328
+ __name(_ts_metadata5, "_ts_metadata");
1329
+ var TsFile = class _TsFile extends File {
1330
+ static {
1331
+ __name(this, "TsFile");
1332
+ }
1333
+ static inspector = Inspector.compose(_TsFile, {
1334
+ keys: [
1335
+ "tsCode"
1336
+ ]
1337
+ });
1338
+ get tsCode() {
1339
+ return new TsCode(this, this.readFile());
1340
+ }
1341
+ get dependencies() {
1342
+ return this.tsCode.dependencies;
1343
+ }
1344
+ };
1345
+ _ts_decorate8([
1346
+ lazyProp(5e3),
1347
+ _ts_metadata5("design:type", typeof TsCode === "undefined" ? Object : TsCode),
1348
+ _ts_metadata5("design:paramtypes", [])
1349
+ ], TsFile.prototype, "tsCode", null);
1350
+ TsFile = _ts_decorate8([
1351
+ Parenting.compose
1352
+ ], TsFile);
1353
+
1354
+ // src/code/imports/ImportStatement.ts
1355
+ function _ts_decorate9(decorators, target, key, desc) {
1356
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1357
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1358
+ 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;
1359
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1360
+ }
1361
+ __name(_ts_decorate9, "_ts_decorate");
1362
+ function _ts_metadata6(k, v) {
1363
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1364
+ }
1365
+ __name(_ts_metadata6, "_ts_metadata");
1366
+ var ImportStatement = class _ImportStatement extends CodeBlock {
1367
+ static {
1368
+ __name(this, "ImportStatement");
1369
+ }
1370
+ static inspector = Inspector.compose(_ImportStatement, {
1371
+ keys: [
1372
+ "keywords",
1373
+ "specifiers",
1374
+ "module"
1375
+ ],
1376
+ inspect: {
1377
+ compact: true
1378
+ }
1379
+ });
1380
+ toOneLine() {
1381
+ return this.code.replace(/\r?\n/g, " ").replace(/\s{2,}/g, " ").replace(/,\s+\}/, " }");
1382
+ }
1383
+ get keywords() {
1384
+ const match = this.code.match(/^import\s+(?:type\s+)?/);
1385
+ const code = match[0].trim();
1386
+ return new ImportKeywords(this, this.codeIndexRangeOf(code));
1387
+ }
1388
+ get specifiers() {
1389
+ const match = this.code.match(/import\s+([^'"]+)\s+from\s+/);
1390
+ const code = match ? match[1].trim() : "";
1391
+ if (!code) {
1392
+ return void 0;
1393
+ }
1394
+ return new ImportSpecifiers(this, this.codeIndexRangeOf(code));
1395
+ }
1396
+ get module() {
1397
+ const match = this.code.match(/(?:from|import)\s+['"]([^'"]+)['"]/);
1398
+ const code = match[1].trim();
1399
+ return new ModuleSpecifier(this, this.codeIndexRangeOf(code));
1400
+ }
1401
+ split() {
1402
+ return this.specifiers?.splitSpecifiers().map((specifier) => {
1403
+ return `import ${specifier} from '${this.module.from}'`;
1404
+ }) ?? [
1405
+ this.code
1406
+ ];
1407
+ }
1408
+ get filepath() {
1409
+ return this.getParentDeep(TsFile).path;
1410
+ }
1411
+ };
1412
+ _ts_decorate9([
1413
+ lazyProp,
1414
+ _ts_metadata6("design:type", void 0),
1415
+ _ts_metadata6("design:paramtypes", [])
1416
+ ], ImportStatement.prototype, "keywords", null);
1417
+ _ts_decorate9([
1418
+ lazyProp,
1419
+ _ts_metadata6("design:type", void 0),
1420
+ _ts_metadata6("design:paramtypes", [])
1421
+ ], ImportStatement.prototype, "specifiers", null);
1422
+ _ts_decorate9([
1423
+ lazyProp,
1424
+ _ts_metadata6("design:type", void 0),
1425
+ _ts_metadata6("design:paramtypes", [])
1426
+ ], ImportStatement.prototype, "module", null);
1427
+ ImportStatement = _ts_decorate9([
1428
+ Parenting.compose
1429
+ ], ImportStatement);
1430
+
1431
+ // ../array/src/lib/arrRemoveDuplicates.ts
1432
+ function arrRemoveDuplicates(array) {
1433
+ return Array.from(new Set(array));
1434
+ }
1435
+ __name(arrRemoveDuplicates, "arrRemoveDuplicates");
1436
+
1437
+ // ../regex/src/rexec.ts
1438
+ function rexec(regex, string) {
1439
+ regex = new RegExp(regex.source, regex.flags);
1440
+ const result = [];
1441
+ let match;
1442
+ while ((match = regex.exec(string)) !== null) {
1443
+ result.push({
1444
+ index: match.index,
1445
+ lastIndex: regex.lastIndex,
1446
+ location: findLineColumn(string, match.index),
1447
+ groups: Object.assign({}, match.groups),
1448
+ match: match[0]
1449
+ });
1450
+ }
1451
+ return result;
1452
+ }
1453
+ __name(rexec, "rexec");
1454
+ function findLineColumn(content, index) {
1455
+ const lines = content.split("\n");
1456
+ const line = content.substring(0, index).split("\n").length;
1457
+ lines.splice(line - 1);
1458
+ const startOfLineIndex = lines.join("\n").length + (lines.length ? 1 : 0);
1459
+ const col = index - startOfLineIndex;
1460
+ return [
1461
+ line,
1462
+ col
1463
+ ];
1464
+ }
1465
+ __name(findLineColumn, "findLineColumn");
1466
+ function importStatementToOneLiner(code) {
1467
+ return strip(code).replace(/\r*\n/g, " ").replace(/\s+/g, " ").replace(/,\s*\}/, " }").replace(/\s*,\s*/g, ", ").replace(/\s+/g, " ").trim();
1468
+ }
1469
+ __name(importStatementToOneLiner, "importStatementToOneLiner");
1470
+
1471
+ // ../tscode/src/tsCrlfToLf.ts
1472
+ function tsCrlfToLf(code) {
1473
+ return code.replace(/\r+\n/g, "\n");
1474
+ }
1475
+ __name(tsCrlfToLf, "tsCrlfToLf");
1476
+
1477
+ // ../tscode/src/tsExtractImports.ts
1478
+ function tsExtractImports(code) {
1479
+ code = tsCrlfToLf(code);
1480
+ code = replaceImportStatementsInsideLiteralStrings(code);
1481
+ code = replaceImportStatementsInsideBlockComments(code);
1482
+ const isFirstLine = /^import /;
1483
+ const isFirstLineInMulti = /\{\s*$/;
1484
+ const isLastLineInMulti = /^\} from ['"]/;
1485
+ const result = [];
1486
+ let isMulti = false;
1487
+ let impLines = [];
1488
+ const lines = code.split(/\r?\n/);
1489
+ for (let l = 0; l < lines.length; l++) {
1490
+ const line = lines[l];
1491
+ if (isFirstLine.test(line)) {
1492
+ if (isFirstLineInMulti.test(line)) {
1493
+ impLines.push(line);
1494
+ isMulti = true;
1495
+ } else {
1496
+ const match = line;
1497
+ const matchOneLine = importStatementToOneLiner(match);
1498
+ result.push({
1499
+ start: l,
1500
+ end: l + 1,
1501
+ match,
1502
+ matchOneLine
1503
+ });
1504
+ }
1505
+ } else if (isMulti) {
1506
+ impLines.push(line);
1507
+ if (isLastLineInMulti.test(line)) {
1508
+ const match = impLines.join("\n");
1509
+ const matchOneLine = importStatementToOneLiner(match);
1510
+ result.push({
1511
+ start: l - impLines.length + 1,
1512
+ end: l + 1,
1513
+ match,
1514
+ matchOneLine
1515
+ });
1516
+ impLines = [];
1517
+ isMulti = false;
1518
+ }
1519
+ }
1520
+ }
1521
+ return result;
1522
+ }
1523
+ __name(tsExtractImports, "tsExtractImports");
1524
+ function replaceImportStatementsInsideLiteralStrings(code) {
1525
+ return code.replace(/(['"`])(.*?)\1/gs, (match) => {
1526
+ return match.replace(/\nimport /gs, "\nIMPORT ");
1527
+ });
1528
+ }
1529
+ __name(replaceImportStatementsInsideLiteralStrings, "replaceImportStatementsInsideLiteralStrings");
1530
+ function replaceImportStatementsInsideBlockComments(code) {
1531
+ return code.replace(/\/\*(.*?)\*\//gs, (match) => {
1532
+ return match.replace(/\nimport /gs, "\nIMPORT ");
1533
+ });
1534
+ }
1535
+ __name(replaceImportStatementsInsideBlockComments, "replaceImportStatementsInsideBlockComments");
1536
+
1537
+ // src/code/TsCode.ts
1538
+ function _ts_decorate10(decorators, target, key, desc) {
1539
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1540
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1541
+ 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;
1542
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1543
+ }
1544
+ __name(_ts_decorate10, "_ts_decorate");
1545
+ function _ts_metadata7(k, v) {
1546
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1547
+ }
1548
+ __name(_ts_metadata7, "_ts_metadata");
1549
+ var TsCode = class _TsCode extends AbstractCode {
1550
+ static {
1551
+ __name(this, "TsCode");
1552
+ }
1553
+ static inspector = Inspector.compose(_TsCode, {
1554
+ keys: [
1555
+ "imports"
1556
+ ]
1557
+ });
1558
+ #code;
1559
+ get code() {
1560
+ return this.#code;
1561
+ }
1562
+ constructor(parent, code) {
1563
+ super(parent);
1564
+ this.#code = code;
1565
+ }
1566
+ toString() {
1567
+ return this.code;
1568
+ }
1569
+ requires(format = "modules") {
1570
+ if (format === "lines") {
1571
+ return this.code.split(/\r*\n/).filter((line) => {
1572
+ return this.requireRegex.test(line);
1573
+ });
1574
+ }
1575
+ return arrRemoveDuplicates(Array.from(this.code.matchAll(this.requireRegex)).map((o) => {
1576
+ return o[1];
1577
+ }));
1578
+ }
1579
+ get imports() {
1580
+ const statements = tsExtractImports(this.code).map((o) => {
1581
+ return o.match;
1582
+ });
1583
+ return statements.map((line) => {
1584
+ return new ImportStatement(this, this.codeIndexRangeOf(line));
1585
+ });
1586
+ }
1587
+ get exportedClassNames() {
1588
+ return rexec(/^export (abstract )?class (?<name>\w+)/gm, this.code).map((o) => {
1589
+ return o.groups?.name;
1590
+ }).filter(Boolean);
1591
+ }
1592
+ get dependencies() {
1593
+ return this.imports.map((imp) => {
1594
+ return imp.module.dependency;
1595
+ }).filter(Boolean).sort();
1596
+ }
1597
+ get requireRegex() {
1598
+ return /require\(['"](.+)['"]\)/g;
1599
+ }
1600
+ };
1601
+ _ts_decorate10([
1602
+ lazyProp,
1603
+ _ts_metadata7("design:type", Array),
1604
+ _ts_metadata7("design:paramtypes", [])
1605
+ ], TsCode.prototype, "imports", null);
1606
+ TsCode = _ts_decorate10([
1607
+ Parenting.compose,
1608
+ _ts_metadata7("design:type", Function),
1609
+ _ts_metadata7("design:paramtypes", [
1610
+ typeof P === "undefined" ? Object : P,
1611
+ String
1612
+ ])
1613
+ ], TsCode);
1614
+
1615
+ // src/file/TestFile.ts
1616
+ function _ts_decorate11(decorators, target, key, desc) {
1617
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1618
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1619
+ 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;
1620
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1621
+ }
1622
+ __name(_ts_decorate11, "_ts_decorate");
1623
+ function _ts_metadata8(k, v) {
1624
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1625
+ }
1626
+ __name(_ts_metadata8, "_ts_metadata");
1627
+ var TestFile = class extends TsFile {
1628
+ static {
1629
+ __name(this, "TestFile");
1630
+ }
1631
+ static inspector = Inspector.compose(TsFile, {});
1632
+ get tsCode() {
1633
+ return new TsCode(this, this.readFile());
1634
+ }
1635
+ get dependencies() {
1636
+ return this.tsCode.dependencies;
1637
+ }
1638
+ };
1639
+ _ts_decorate11([
1640
+ lazyProp(5e3),
1641
+ _ts_metadata8("design:type", typeof TsCode === "undefined" ? Object : TsCode),
1642
+ _ts_metadata8("design:paramtypes", [])
1643
+ ], TestFile.prototype, "tsCode", null);
1644
+ TestFile = _ts_decorate11([
1645
+ Parenting.compose
1646
+ ], TestFile);
1647
+ var getRepoRootDirpath = onetime(/* @__PURE__ */ __name(function getRepoRootDirpath2() {
1648
+ return (/* @__PURE__ */ __name(function recurse(dirpath = process.cwd()) {
1649
+ dirpath = path2.normalizeSafe(dirpath);
1650
+ const pkgpath = path2.joinSafe(dirpath, "package.json");
1651
+ if (fs2.existsSync(pkgpath) && fs2.readJsonSync(pkgpath)?.workspaces) {
1652
+ return dirpath;
1653
+ }
1654
+ const parent = path2.dirname(dirpath);
1655
+ if (parent !== dirpath) {
1656
+ return recurse(parent);
1657
+ }
1658
+ throw new Error(`Could not find repo root from process.cwd(): ${process.cwd()}`);
1659
+ }, "recurse"))();
1660
+ }, "getRepoRootDirpath"));
1661
+ function resolveModuleImportPath(filepath, importFrom) {
1662
+ const rootdir = getRepoRootDirpath();
1663
+ const result = resolveModuleName(importFrom, filepath, {
1664
+ paths: fs3.readJsonSync(path2.joinSafe(rootdir, "tsconfig.paths.json")).compilerOptions.paths,
1665
+ allowJs: true,
1666
+ allowArbitraryExtensions: true,
1667
+ allowImportingTsExtensions: true,
1668
+ allowSyntheticDefaultImports: true,
1669
+ esModuleInterop: true,
1670
+ strict: false
1671
+ }, createCompilerHost({}, true));
1672
+ const f = result.resolvedModule?.resolvedFileName;
1673
+ if (f) {
1674
+ result.resolvedModule.resolvedFileName = path2.relative(rootdir, f);
1675
+ }
1676
+ return result.resolvedModule;
1677
+ }
1678
+ __name(resolveModuleImportPath, "resolveModuleImportPath");
1679
+ function walkDirectory(dirpath, options) {
1680
+ dirpath = path2.normalizeSafe(dirpath);
1681
+ if (!options.stats && !options.only) {
1682
+ return walkdir.sync(dirpath, {
1683
+ ...convertToWalkdirOptions(options),
1684
+ return_object: false
1685
+ }).map((fspath) => {
1686
+ return path2.normalizeSafe(fspath);
1687
+ });
1688
+ }
1689
+ let entries = Object.entries(walkdir.sync(dirpath, convertToWalkdirOptions(options)));
1690
+ if (options.only === "files") {
1691
+ entries = entries.filter(([_, stats]) => {
1692
+ return stats.isFile();
1693
+ });
1694
+ } else if (options.only === "directories") {
1695
+ entries = entries.filter(([_, stats]) => {
1696
+ return stats.isDirectory();
1697
+ });
1698
+ }
1699
+ entries = entries.map(([fspath, stats]) => {
1700
+ return [
1701
+ path2.normalizeSafe(fspath),
1702
+ stats
1703
+ ];
1704
+ });
1705
+ if (options.stats) {
1706
+ return entries;
1707
+ } else {
1708
+ return entries.map(([fspath]) => {
1709
+ return fspath;
1710
+ });
1711
+ }
1712
+ }
1713
+ __name(walkDirectory, "walkDirectory");
1714
+ function convertToWalkdirOptions(options) {
1715
+ const result = {
1716
+ fs: fs2,
1717
+ sync: true,
1718
+ return_object: true
1719
+ };
1720
+ if (options.maxDepth !== void 0) {
1721
+ result.max_depth = options.maxDepth;
1722
+ }
1723
+ if (options.followSymlinks !== void 0) {
1724
+ result.follow_symlinks = options.followSymlinks;
1725
+ }
1726
+ if (options.ignoreInodes !== void 0) {
1727
+ result.track_inodes = !options.ignoreInodes;
1728
+ }
1729
+ if (options.filter) {
1730
+ const filter = options.filter;
1731
+ result.filter = (dirpath, files) => {
1732
+ return filter(path2.normalizeSafe(dirpath), path2.basename(dirpath)) ? files : [];
1733
+ };
1734
+ }
1735
+ return result;
1736
+ }
1737
+ __name(convertToWalkdirOptions, "convertToWalkdirOptions");
1738
+
1739
+ // src/repo/Workspace.ts
1740
+ function _ts_decorate12(decorators, target, key, desc) {
1741
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1742
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1743
+ 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;
1744
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1745
+ }
1746
+ __name(_ts_decorate12, "_ts_decorate");
1747
+ function _ts_metadata9(k, v) {
1748
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1749
+ }
1750
+ __name(_ts_metadata9, "_ts_metadata");
1751
+ var Workspace = class _Workspace extends AbstractBase {
1752
+ static {
1753
+ __name(this, "Workspace");
1754
+ }
1755
+ static inspector = Inspector.compose(_Workspace, {
1756
+ keys: [
1757
+ "name",
1758
+ "tsFiles",
1759
+ "testFiles"
1760
+ ]
1761
+ });
1762
+ /**
1763
+ * The workspace's origin directory name, eg. 'libs', 'apps', etc.
1764
+ */
1765
+ origin;
1766
+ /**
1767
+ * The workspace's root directory path.
1768
+ */
1769
+ path;
1770
+ constructor(parent, dirpath) {
1771
+ super(parent);
1772
+ this.path = path2.normalize(dirpath);
1773
+ this.origin = path2.basename(path2.dirname(this.path));
1774
+ }
1775
+ /**
1776
+ * The workspace's package.json filepath.
1777
+ */
1778
+ get packageJsonPath() {
1779
+ return path2.join(this.path, "package.json");
1780
+ }
1781
+ /**
1782
+ * The workspace's package.json file as an object.
1783
+ */
1784
+ get packageJson() {
1785
+ return readJsonSync(this.packageJsonPath);
1786
+ }
1787
+ /**
1788
+ * The workspace's name from the package.json file.
1789
+ */
1790
+ get name() {
1791
+ if (!this.packageJson.name) {
1792
+ throw new Error(`Workspace package.json missing 'name' field: ${this.packageJsonPath}`);
1793
+ }
1794
+ return this.packageJson.name;
1795
+ }
1796
+ /**
1797
+ * Reads the workspace's package.json file and returns the 'dependencies' field as a sorted array of strings.
1798
+ */
1799
+ get installedDependencies() {
1800
+ const deps = this.packageJson.dependencies ?? {};
1801
+ return Object.keys(deps).sort();
1802
+ }
1803
+ /**
1804
+ * Reads the workspace's package.json file and returns the 'devDependencies' field as a sorted array of strings.
1805
+ */
1806
+ get installedDevDependencies() {
1807
+ const deps = this.packageJson.devDependencies ?? {};
1808
+ return Object.keys(deps).sort();
1809
+ }
1810
+ /**
1811
+ * Get all unique file-level dependencies of the workspace, including transitive dependencies through other local workspaces.
1812
+ *
1813
+ * This method recursively traverses the dependency graph of the workspace, collecting all unique dependencies. It distinguishes between internal dependencies (other local workspaces) and external dependencies (npm packages).
1814
+ *
1815
+ * @returns An object containing two arrays: `internal` for internal workspace dependencies and `external` for npm package dependencies.
1816
+ */
1817
+ get importedDependenciesRecursive() {
1818
+ const repo = this.parent;
1819
+ const wsNames = repo.workspaces.map((w) => {
1820
+ return w.name;
1821
+ });
1822
+ const allDeps = recurse(this.tsFiles.filter((f) => {
1823
+ return f.isSourceFile;
1824
+ }));
1825
+ const internal = [
1826
+ ...allDeps
1827
+ ].filter((d) => {
1828
+ return wsNames.some((name) => {
1829
+ return name === d;
1830
+ });
1831
+ }).sort();
1832
+ const external = [
1833
+ ...allDeps
1834
+ ].filter((d) => {
1835
+ return !wsNames.some((name) => {
1836
+ return name === d;
1837
+ });
1838
+ }).sort();
1839
+ function recurse(files, allDeps2 = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), depth = 0) {
1840
+ for (const file of files) {
1841
+ if (visited.has(file.path)) {
1842
+ continue;
1843
+ }
1844
+ visited.add(file.path);
1845
+ for (const dep of file.dependencies) {
1846
+ allDeps2.add(dep);
1847
+ const depWs = repo.workspaces.find((w) => {
1848
+ return w.name === dep;
1849
+ });
1850
+ if (depWs) {
1851
+ recurse(depWs.tsFiles.filter((f) => {
1852
+ return f.isSourceFile;
1853
+ }), allDeps2, visited, depth + 1).forEach((d) => {
1854
+ return allDeps2.add(d);
1855
+ });
1856
+ }
1857
+ }
1858
+ }
1859
+ return allDeps2;
1860
+ }
1861
+ __name(recurse, "recurse");
1862
+ return {
1863
+ internal,
1864
+ external
1865
+ };
1866
+ }
1867
+ /**
1868
+ * Get the source files in the workspace's 'src' directory.
1869
+ * Test files are not included.
1870
+ */
1871
+ get tsFiles() {
1872
+ return walkDirectory(this.path, {
1873
+ stats: true,
1874
+ only: "files",
1875
+ filter: /* @__PURE__ */ __name((_dirpath, basename) => {
1876
+ if (basename === "node_modules") {
1877
+ return false;
1878
+ }
1879
+ if (basename === "coverage") {
1880
+ return false;
1881
+ }
1882
+ if (basename.startsWith(".")) {
1883
+ return false;
1884
+ }
1885
+ return true;
1886
+ }, "filter")
1887
+ }).filter(([fspath]) => {
1888
+ return hasParentDirname(fspath, "src") && !hasExtnamePrefix(fspath);
1889
+ }).map(([fspath]) => {
1890
+ return new TsFile(this, fspath);
1891
+ });
1892
+ }
1893
+ /**
1894
+ * Get the test files in the workspace's 'src' directory.
1895
+ */
1896
+ get testFiles() {
1897
+ return walkDirectory(this.path, {
1898
+ stats: true,
1899
+ only: "files",
1900
+ filter: /* @__PURE__ */ __name((_dirpath, basename) => {
1901
+ if (basename === "node_modules") {
1902
+ return false;
1903
+ }
1904
+ if (basename === "coverage") {
1905
+ return false;
1906
+ }
1907
+ if (basename.startsWith(".")) {
1908
+ return false;
1909
+ }
1910
+ return true;
1911
+ }, "filter")
1912
+ }).filter(([fspath]) => {
1913
+ return hasParentDirname(fspath, "src") && !hasExtnamePrefix(fspath, SemanticExtnamePrefix.test);
1914
+ }).map(([fspath]) => {
1915
+ return new TestFile(this, fspath);
1916
+ });
1917
+ }
1918
+ get files() {
1919
+ return [
1920
+ ...this.tsFiles,
1921
+ ...this.testFiles
1922
+ ];
1923
+ }
1924
+ /**
1925
+ * Get imported non-relative dependencies for each source file in the workspace, grouped by file.
1926
+ */
1927
+ get importedDependenciesByFile() {
1928
+ return new Map(this.tsFiles.map((file) => {
1929
+ return [
1930
+ path2.relative(process.cwd(), file.path),
1931
+ file.dependencies
1932
+ ];
1933
+ }));
1934
+ }
1935
+ /**
1936
+ * Get imported non-relative dependencies for each test file in the workspace, grouped by file.
1937
+ */
1938
+ get importedTestDependenciesByFile() {
1939
+ return new Map(this.testFiles.map((file) => {
1940
+ return [
1941
+ path2.relative(process.cwd(), file.path),
1942
+ file.dependencies
1943
+ ];
1944
+ }));
1945
+ }
1946
+ /**
1947
+ * Get imported non-relative dependencies for each source file in the workspace in a flat array.
1948
+ */
1949
+ get importedDependencies() {
1950
+ return arrRemoveDuplicates(Array.from(this.importedDependenciesByFile.values()).flat());
1951
+ }
1952
+ /**
1953
+ * Get imported non-relative dependencies for each test file in the workspace in a flat array.
1954
+ */
1955
+ get importedTestDependencies() {
1956
+ return arrRemoveDuplicates(Array.from(this.importedTestDependenciesByFile.values()).flat());
1957
+ }
1958
+ /**
1959
+ * Get dependencies that are imported but not listed in the workspace's package.json under 'dependencies'.
1960
+ */
1961
+ get missingDependencies() {
1962
+ return difference(this.importedDependencies, this.installedDependencies).filter((dep) => {
1963
+ return !this.parent.packageJson.dependencies?.[dep];
1964
+ }).filter((dep) => {
1965
+ return !this.parent.tsconfigBasePaths?.[dep];
1966
+ });
1967
+ }
1968
+ /**
1969
+ * Get dependencies that are imported but not listed in the workspace's package.json under 'devDependencies'.
1970
+ */
1971
+ get missingDevDependencies() {
1972
+ return difference(this.importedTestDependencies, union(this.installedDependencies, this.installedDevDependencies)).filter((dep) => {
1973
+ return !this.parent.packageJson.devDependencies?.[dep];
1974
+ }).filter((dep) => {
1975
+ return !this.parent.packageJson.dependencies?.[dep];
1976
+ }).filter((dep) => {
1977
+ return !this.parent.tsconfigBasePaths?.[dep];
1978
+ });
1979
+ }
1980
+ /**
1981
+ * Get dependencies that are listed in the workspace's package.json but not imported in any source file (excl. test files).
1982
+ */
1983
+ get unusedDependencies() {
1984
+ return difference(this.installedDependencies, this.importedDependencies);
1985
+ }
1986
+ /**
1987
+ *
1988
+ */
1989
+ get incorrectlyImportedRepoWorkspaces() {
1990
+ const results = [];
1991
+ for (const file of this.files) {
1992
+ for (const imp of file.tsCode.imports) {
1993
+ if (imp.module.from === this.name) {
1994
+ const resolvedFileName = resolveModuleImportPath(file.path, imp.module.from)?.resolvedFileName;
1995
+ if (resolvedFileName) {
1996
+ results.push({
1997
+ filepath: file.path,
1998
+ replaceValue: imp.module.from,
1999
+ withValue: resolvedFileName.endsWith("index.ts") ? `./${imp.specifiers?.importedNamesArray[0]}` : `./${path2.relative(path2.dirname(file.path), resolvedFileName)}`
2000
+ });
2001
+ }
2002
+ }
2003
+ }
2004
+ }
2005
+ return results;
2006
+ }
2007
+ /**
2008
+ * Returns an object with found dependency problems for the workspace or undefined if no problems were found.
2009
+ * @see WorkspaceDependencyProblems
2010
+ */
2011
+ get dependencyProblems() {
2012
+ const result = {
2013
+ origin: this.origin,
2014
+ workspace: this.name,
2015
+ unused: this.unusedDependencies,
2016
+ missing: this.missingDependencies,
2017
+ missingDev: this.missingDevDependencies,
2018
+ imports: this.incorrectlyImportedRepoWorkspaces
2019
+ };
2020
+ if (!result.unused.length && !result.missing.length && !result.missingDev.length) {
2021
+ return void 0;
2022
+ }
2023
+ for (const [key, value] of Object.entries(result)) {
2024
+ if (!value.length) {
2025
+ delete result[key];
2026
+ }
2027
+ }
2028
+ return result;
2029
+ }
2030
+ async depcheck() {
2031
+ try {
2032
+ const rootPkg = this.parent.packageJson;
2033
+ const dependencies = rootPkg.dependencies || {};
2034
+ const devDependencies = rootPkg.devDependencies || {};
2035
+ const ignores = Object.keys({
2036
+ ...devDependencies,
2037
+ ...dependencies
2038
+ }).concat("@mono/*");
2039
+ const ignoresFlag = `--ignores "${ignores.join(",")}"`;
2040
+ const cmd = `yarn depcheck ${this.path} ${ignoresFlag} --json`;
2041
+ const execPromise = promisify(exec);
2042
+ const res = await execPromise(cmd);
2043
+ return JSON.parse(res.stdout.toString());
2044
+ } catch (error) {
2045
+ const res = error;
2046
+ if (res.stdout) {
2047
+ return JSON.parse(res.stdout.toString());
2048
+ }
2049
+ console.error(error);
2050
+ return {
2051
+ dependencies: [],
2052
+ devDependencies: [],
2053
+ using: {},
2054
+ missing: {},
2055
+ invalidFiles: {},
2056
+ invalidDirs: {}
2057
+ };
2058
+ }
2059
+ }
2060
+ /**
2061
+ * Returns the workspace's cwd-relative path.
2062
+ */
2063
+ toString() {
2064
+ return path2.relative(process.cwd(), this.path);
2065
+ }
2066
+ };
2067
+ _ts_decorate12([
2068
+ lazyProp(1e3),
2069
+ _ts_metadata9("design:type", typeof PackageJson === "undefined" ? Object : PackageJson),
2070
+ _ts_metadata9("design:paramtypes", [])
2071
+ ], Workspace.prototype, "packageJson", null);
2072
+ _ts_decorate12([
2073
+ lazyProp(5e3),
2074
+ _ts_metadata9("design:type", Array),
2075
+ _ts_metadata9("design:paramtypes", [])
2076
+ ], Workspace.prototype, "tsFiles", null);
2077
+ _ts_decorate12([
2078
+ lazyProp(5e3),
2079
+ _ts_metadata9("design:type", Array),
2080
+ _ts_metadata9("design:paramtypes", [])
2081
+ ], Workspace.prototype, "testFiles", null);
2082
+ _ts_decorate12([
2083
+ lazyProp(1e3),
2084
+ _ts_metadata9("design:type", typeof Map === "undefined" ? Object : Map),
2085
+ _ts_metadata9("design:paramtypes", [])
2086
+ ], Workspace.prototype, "importedDependenciesByFile", null);
2087
+ _ts_decorate12([
2088
+ lazyProp(1e3),
2089
+ _ts_metadata9("design:type", typeof Map === "undefined" ? Object : Map),
2090
+ _ts_metadata9("design:paramtypes", [])
2091
+ ], Workspace.prototype, "importedTestDependenciesByFile", null);
2092
+ Workspace = _ts_decorate12([
2093
+ Parenting.compose,
2094
+ _ts_metadata9("design:type", Function),
2095
+ _ts_metadata9("design:paramtypes", [
2096
+ typeof P === "undefined" ? Object : P,
2097
+ String
2098
+ ])
2099
+ ], Workspace);
2100
+ function _ts_decorate13(decorators, target, key, desc) {
2101
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2102
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2103
+ 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;
2104
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2105
+ }
2106
+ __name(_ts_decorate13, "_ts_decorate");
2107
+ function _ts_metadata10(k, v) {
2108
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2109
+ }
2110
+ __name(_ts_metadata10, "_ts_metadata");
2111
+ var MonoRepo = class _MonoRepo extends AbstractBase {
2112
+ static {
2113
+ __name(this, "MonoRepo");
2114
+ }
2115
+ static inspector = Inspector.compose(_MonoRepo, {
2116
+ keys: [
2117
+ "name",
2118
+ "workspaces"
2119
+ ]
2120
+ });
2121
+ static instances = /* @__PURE__ */ new Map();
2122
+ path;
2123
+ constructor() {
2124
+ const oPath = getRepoRootDirpath();
2125
+ if (_MonoRepo.instances.has(oPath)) {
2126
+ return _MonoRepo.instances.get(oPath);
2127
+ }
2128
+ super(null);
2129
+ this.path = oPath;
2130
+ _MonoRepo.instances.set(this.path, this);
2131
+ }
2132
+ get monoRepo() {
2133
+ return this;
2134
+ }
2135
+ get packageJsonPath() {
2136
+ return path2.join(this.path, "package.json");
2137
+ }
2138
+ get tsconfigBaseJsonPath() {
2139
+ return path2.join(this.path, "tsconfig.json");
2140
+ }
2141
+ get tsconfigBase() {
2142
+ const o = readJsonSync(this.tsconfigBaseJsonPath);
2143
+ if (!o.compilerOptions) {
2144
+ o.compilerOptions = {};
2145
+ }
2146
+ o.compilerOptions.paths = o.compilerOptions.paths || this.tsconfigBasePaths;
2147
+ return o;
2148
+ }
2149
+ get tsconfigBasePathsJsonPath() {
2150
+ return path2.join(this.path, "tsconfig.paths.json");
2151
+ }
2152
+ get tsconfigBasePaths() {
2153
+ if (!fs.existsSync(this.tsconfigBasePathsJsonPath)) {
2154
+ return {};
2155
+ }
2156
+ return readJsonSync(this.tsconfigBasePathsJsonPath).compilerOptions?.paths ?? {};
2157
+ }
2158
+ get packageJson() {
2159
+ return readJsonSync(this.packageJsonPath);
2160
+ }
2161
+ get name() {
2162
+ if (!this.packageJson.name) {
2163
+ throw new Error(`MonoRepo package.json missing 'name' field: ${this.packageJsonPath}`);
2164
+ }
2165
+ return this.packageJson.name;
2166
+ }
2167
+ get workspacesRootPaths() {
2168
+ if (!this.packageJson.workspaces) {
2169
+ throw new Error(`MonoRepo package.json missing 'workspaces' field: ${this.packageJsonPath}`);
2170
+ }
2171
+ return this.packageJson.workspaces.map((workspacePath) => {
2172
+ return path2.join(this.path, workspacePath.replace(/\*$/, ""));
2173
+ });
2174
+ }
2175
+ get workspacePaths() {
2176
+ return this.workspacesRootPaths.map((workspacePath) => {
2177
+ return fs.readdirSync(workspacePath, {
2178
+ withFileTypes: true
2179
+ }).filter((dirent) => {
2180
+ return dirent.isDirectory();
2181
+ }).map((dirent) => {
2182
+ return path2.join(workspacePath, dirent.name);
2183
+ });
2184
+ }).flat();
2185
+ }
2186
+ get workspaces() {
2187
+ return this.workspacePaths.map((dirpath) => {
2188
+ return new Workspace(this, dirpath);
2189
+ });
2190
+ }
2191
+ };
2192
+ _ts_decorate13([
2193
+ lazyProp(5e3),
2194
+ _ts_metadata10("design:type", void 0),
2195
+ _ts_metadata10("design:paramtypes", [])
2196
+ ], MonoRepo.prototype, "tsconfigBase", null);
2197
+ _ts_decorate13([
2198
+ lazyProp(5e3),
2199
+ _ts_metadata10("design:type", typeof Record === "undefined" ? Object : Record),
2200
+ _ts_metadata10("design:paramtypes", [])
2201
+ ], MonoRepo.prototype, "tsconfigBasePaths", null);
2202
+ _ts_decorate13([
2203
+ lazyProp(5e3),
2204
+ _ts_metadata10("design:type", typeof PackageJson === "undefined" ? Object : PackageJson),
2205
+ _ts_metadata10("design:paramtypes", [])
2206
+ ], MonoRepo.prototype, "packageJson", null);
2207
+ _ts_decorate13([
2208
+ lazyProp(5e3),
2209
+ _ts_metadata10("design:type", void 0),
2210
+ _ts_metadata10("design:paramtypes", [])
2211
+ ], MonoRepo.prototype, "workspacePaths", null);
2212
+ _ts_decorate13([
2213
+ lazyProp,
2214
+ _ts_metadata10("design:type", Array),
2215
+ _ts_metadata10("design:paramtypes", [])
2216
+ ], MonoRepo.prototype, "workspaces", null);
2217
+ MonoRepo = _ts_decorate13([
2218
+ Parenting.compose,
2219
+ _ts_metadata10("design:type", Function),
2220
+ _ts_metadata10("design:paramtypes", [])
2221
+ ], MonoRepo);
2222
+ function getRepoPackageJsonPath() {
2223
+ return path2.joinSafe(getRepoRootDirpath(), "package.json");
2224
+ }
2225
+ __name(getRepoPackageJsonPath, "getRepoPackageJsonPath");
2226
+
2227
+ // src/methods/getRepoPackageJson.ts
2228
+ async function getRepoPackageJson() {
2229
+ return await fs2.readJson(getRepoPackageJsonPath());
2230
+ }
2231
+ __name(getRepoPackageJson, "getRepoPackageJson");
2232
+ async function getAllWorkspacePaths() {
2233
+ const pkg = await getRepoPackageJson();
2234
+ return (await Promise.all(pkg.workspaces.map((pattern) => {
2235
+ return glob(pattern);
2236
+ }))).flat().map((fp) => {
2237
+ return path2.normalizeSafe(fp);
2238
+ });
2239
+ }
2240
+ __name(getAllWorkspacePaths, "getAllWorkspacePaths");
2241
+ async function getAllWorkspacePackageJsonPaths() {
2242
+ const paths = await getAllWorkspacePaths();
2243
+ return paths.map((p) => {
2244
+ return path2.join(p, "package.json");
2245
+ });
2246
+ }
2247
+ __name(getAllWorkspacePackageJsonPaths, "getAllWorkspacePackageJsonPaths");
2248
+
2249
+ // src/methods/getAllWorkspacePackageJsons.ts
2250
+ async function getAllWorkspacePackageJsons() {
2251
+ const paths = await getAllWorkspacePackageJsonPaths();
2252
+ return paths.map((p) => {
2253
+ return fs2.readJsonSync(p);
2254
+ });
2255
+ }
2256
+ __name(getAllWorkspacePackageJsons, "getAllWorkspacePackageJsons");
2257
+
2258
+ // src/methods/getAllWorkspacePackageNames.ts
2259
+ async function getAllWorkspacePackageNames() {
2260
+ const pkgs = await getAllWorkspacePackageJsons();
2261
+ return pkgs.map((p) => {
2262
+ return p.name;
2263
+ });
2264
+ }
2265
+ __name(getAllWorkspacePackageNames, "getAllWorkspacePackageNames");
2266
+
2267
+ // src/methods/findWorkspacePackageName.ts
2268
+ async function findWorkspacePackageName(name) {
2269
+ const wsPkgNames = await getAllWorkspacePackageNames();
2270
+ return wsPkgNames.find((n) => {
2271
+ return n === name;
2272
+ }) || wsPkgNames.find((n) => {
2273
+ return n === `@mono/${name}`;
2274
+ });
2275
+ }
2276
+ __name(findWorkspacePackageName, "findWorkspacePackageName");
2277
+
2278
+ // src/methods/getAllImports.ts
2279
+ function getAllImports(repo) {
2280
+ return repo.workspaces.flatMap((ws) => {
2281
+ return ws.tsFiles.filter((ts) => {
2282
+ return ts.isSourceFile;
2283
+ }).flatMap((ts) => {
2284
+ return ts.tsCode.imports.flatMap((imp) => {
2285
+ return imp;
2286
+ });
2287
+ });
2288
+ });
2289
+ }
2290
+ __name(getAllImports, "getAllImports");
2291
+
2292
+ // src/util/SemanticExtnamePrefixDescriptions.ts
2293
+ var SemanticExtnamePrefixDescriptions = {
2294
+ d: "declarations",
2295
+ test: "vitest test suite",
2296
+ examples: "contains working and tested example usage code. Included in git, but ignored by most repo tools",
2297
+ benchmark: "benchmark files, included in git, but ignored by most repo tools.",
2298
+ temp: "temporary files, ignored by git, build, tests, etc.",
2299
+ wip: "work in progress, ignored by git, build, tests, etc."
2300
+ };
2301
+ function getWorkspaceDirpaths() {
2302
+ const rootDirpath = getRepoRootDirpath();
2303
+ const pkg = fs2.readJsonSync(path2.joinSafe(rootDirpath, "package.json"));
2304
+ if (!pkg.workspaces) {
2305
+ throw new Error(`No workspaces found in package.json at ${rootDirpath}`);
2306
+ }
2307
+ return pkg.workspaces.flatMap((workspace) => {
2308
+ return globSync(workspace);
2309
+ }).map(path2.normalizeSafe);
2310
+ }
2311
+ __name(getWorkspaceDirpaths, "getWorkspaceDirpaths");
2312
+
2313
+ // src/util/semverVersionBump.ts
2314
+ function semverVersionBump(version, level) {
2315
+ const arr = (typeof version === "string" ? version.split(".") : version).map(Number);
2316
+ if (level === "major") {
2317
+ arr[0] += 1;
2318
+ arr[1] = 0;
2319
+ arr[2] = 0;
2320
+ } else if (level === "minor") {
2321
+ arr[1] += 1;
2322
+ arr[2] = 0;
2323
+ } else if (level === "patch") {
2324
+ arr[2] += 1;
2325
+ }
2326
+ return arr.join(".");
2327
+ }
2328
+ __name(semverVersionBump, "semverVersionBump");
2329
+
2330
+ export { AbstractBase, AbstractCode, CodeBlock, File, ImportKeywords, ImportSpecifiers, ImportStatement, ModuleSpecifier, MonoRepo, SemanticExtnamePrefix, SemanticExtnamePrefixDescriptions, TestFile, TsCode, TsFile, Workspace, findWorkspacePackageName, getAllImports, getAllWorkspacePackageJsonPaths, getAllWorkspacePackageJsons, getAllWorkspacePackageNames, getAllWorkspacePaths, getRepoPackageJson, getRepoPackageJsonPath, getRepoRootDirpath, getWorkspaceDirpaths, hasExtnamePrefix, resolveModuleImportPath, semverVersionBump };