@bemoje/monorepo 2.0.0 → 3.0.2

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