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