@teambit/dependencies 1.0.82 → 1.0.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dependencies-loader/README.md +34 -0
  2. package/dependencies-loader/apply-overrides.ts +552 -0
  3. package/dependencies-loader/auto-detect-deps.ts +761 -0
  4. package/dependencies-loader/dependencies-data.ts +47 -0
  5. package/dependencies-loader/dependencies-loader.ts +174 -0
  6. package/dependencies-loader/dependencies-versions-resolver.ts +160 -0
  7. package/dependencies-loader/index.ts +2 -0
  8. package/dependencies-loader/overrides-dependencies.ts +115 -0
  9. package/dependencies-loader/package-to-definetly-typed.spec.ts +53 -0
  10. package/dependencies-loader/package-to-definetly-typed.ts +10 -0
  11. package/dist/dependencies-loader/README.md +34 -0
  12. package/dist/dependencies-loader/apply-overrides.d.ts +100 -0
  13. package/dist/dependencies-loader/apply-overrides.js +541 -0
  14. package/dist/dependencies-loader/apply-overrides.js.map +1 -0
  15. package/dist/dependencies-loader/auto-detect-deps.d.ts +165 -0
  16. package/dist/dependencies-loader/auto-detect-deps.js +768 -0
  17. package/dist/dependencies-loader/auto-detect-deps.js.map +1 -0
  18. package/dist/dependencies-loader/dependencies-data.d.ts +17 -0
  19. package/dist/dependencies-loader/dependencies-data.js +72 -0
  20. package/dist/dependencies-loader/dependencies-data.js.map +1 -0
  21. package/dist/dependencies-loader/dependencies-loader.d.ts +30 -0
  22. package/dist/dependencies-loader/dependencies-loader.js +229 -0
  23. package/dist/dependencies-loader/dependencies-loader.js.map +1 -0
  24. package/dist/dependencies-loader/dependencies-versions-resolver.d.ts +6 -0
  25. package/dist/dependencies-loader/dependencies-versions-resolver.js +153 -0
  26. package/dist/dependencies-loader/dependencies-versions-resolver.js.map +1 -0
  27. package/dist/dependencies-loader/index.d.ts +2 -0
  28. package/dist/dependencies-loader/index.js +33 -0
  29. package/dist/dependencies-loader/index.js.map +1 -0
  30. package/dist/dependencies-loader/overrides-dependencies.d.ts +17 -0
  31. package/dist/dependencies-loader/overrides-dependencies.js +118 -0
  32. package/dist/dependencies-loader/overrides-dependencies.js.map +1 -0
  33. package/dist/dependencies-loader/package-to-definetly-typed.d.ts +1 -0
  34. package/dist/dependencies-loader/package-to-definetly-typed.js +18 -0
  35. package/dist/dependencies-loader/package-to-definetly-typed.js.map +1 -0
  36. package/dist/dependencies-loader/package-to-definetly-typed.spec.d.ts +1 -0
  37. package/dist/dependencies-loader/package-to-definetly-typed.spec.js +27 -0
  38. package/dist/dependencies-loader/package-to-definetly-typed.spec.js.map +1 -0
  39. package/dist/dependencies.main.runtime.d.ts +21 -4
  40. package/dist/dependencies.main.runtime.js +49 -14
  41. package/dist/dependencies.main.runtime.js.map +1 -1
  42. package/package.json +17 -6
  43. /package/dist/{preview-1701813377689.js → preview-1701874572488.js} +0 -0
@@ -0,0 +1,768 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.AutoDetectDeps = void 0;
7
+ exports.getValidVersion = getValidVersion;
8
+ function path() {
9
+ const data = _interopRequireWildcard(require("path"));
10
+ path = function () {
11
+ return data;
12
+ };
13
+ return data;
14
+ }
15
+ function _fsExtra() {
16
+ const data = _interopRequireDefault(require("fs-extra"));
17
+ _fsExtra = function () {
18
+ return data;
19
+ };
20
+ return data;
21
+ }
22
+ function _ramda() {
23
+ const data = _interopRequireDefault(require("ramda"));
24
+ _ramda = function () {
25
+ return data;
26
+ };
27
+ return data;
28
+ }
29
+ function _semver() {
30
+ const data = _interopRequireDefault(require("semver"));
31
+ _semver = function () {
32
+ return data;
33
+ };
34
+ return data;
35
+ }
36
+ function _componentVersion() {
37
+ const data = require("@teambit/component-version");
38
+ _componentVersion = function () {
39
+ return data;
40
+ };
41
+ return data;
42
+ }
43
+ function _lodash() {
44
+ const data = require("lodash");
45
+ _lodash = function () {
46
+ return data;
47
+ };
48
+ return data;
49
+ }
50
+ function _componentIssues() {
51
+ const data = require("@teambit/component-issues");
52
+ _componentIssues = function () {
53
+ return data;
54
+ };
55
+ return data;
56
+ }
57
+ function _dependencies() {
58
+ const data = require("@teambit/legacy/dist/consumer/component/dependencies");
59
+ _dependencies = function () {
60
+ return data;
61
+ };
62
+ return data;
63
+ }
64
+ function _constants() {
65
+ const data = require("@teambit/legacy/dist/constants");
66
+ _constants = function () {
67
+ return data;
68
+ };
69
+ return data;
70
+ }
71
+ function _logger() {
72
+ const data = _interopRequireDefault(require("@teambit/legacy/dist/logger/logger"));
73
+ _logger = function () {
74
+ return data;
75
+ };
76
+ return data;
77
+ }
78
+ function _utils() {
79
+ const data = require("@teambit/legacy/dist/utils");
80
+ _utils = function () {
81
+ return data;
82
+ };
83
+ return data;
84
+ }
85
+ function _path2() {
86
+ const data = require("@teambit/legacy/dist/utils/path");
87
+ _path2 = function () {
88
+ return data;
89
+ };
90
+ return data;
91
+ }
92
+ function _filesDependencyBuilder() {
93
+ const data = require("@teambit/legacy/dist/consumer/component/dependencies/files-dependency-builder");
94
+ _filesDependencyBuilder = function () {
95
+ return data;
96
+ };
97
+ return data;
98
+ }
99
+ function _aspectLoader() {
100
+ const data = require("@teambit/aspect-loader");
101
+ _aspectLoader = function () {
102
+ return data;
103
+ };
104
+ return data;
105
+ }
106
+ function _packageToDefinetlyTyped() {
107
+ const data = require("./package-to-definetly-typed");
108
+ _packageToDefinetlyTyped = function () {
109
+ return data;
110
+ };
111
+ return data;
112
+ }
113
+ function _dependenciesData() {
114
+ const data = require("./dependencies-data");
115
+ _dependenciesData = function () {
116
+ return data;
117
+ };
118
+ return data;
119
+ }
120
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
121
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
122
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
123
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
124
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
125
+ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
126
+ class AutoDetectDeps {
127
+ constructor(component, workspace, devFiles, depsResolver, aspectLoader) {
128
+ this.component = component;
129
+ this.workspace = workspace;
130
+ this.devFiles = devFiles;
131
+ this.depsResolver = depsResolver;
132
+ this.aspectLoader = aspectLoader;
133
+ _defineProperty(this, "componentId", void 0);
134
+ _defineProperty(this, "componentMap", void 0);
135
+ _defineProperty(this, "componentFromModel", void 0);
136
+ _defineProperty(this, "consumerPath", void 0);
137
+ _defineProperty(this, "tree", void 0);
138
+ _defineProperty(this, "allDependencies", void 0);
139
+ _defineProperty(this, "allPackagesDependencies", void 0);
140
+ _defineProperty(this, "issues", void 0);
141
+ _defineProperty(this, "coreAspects", []);
142
+ _defineProperty(this, "processedFiles", void 0);
143
+ _defineProperty(this, "debugDependenciesData", void 0);
144
+ _defineProperty(this, "autoDetectConfigMerge", void 0);
145
+ this.componentId = component.componentId;
146
+ // the consumerComponent is coming from the workspace, so it must have the componentMap prop
147
+ this.componentMap = this.component.componentMap;
148
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
149
+ this.componentFromModel = this.component.componentFromModel;
150
+ this.consumerPath = this.consumer.getPath();
151
+ this.allDependencies = {
152
+ dependencies: [],
153
+ devDependencies: []
154
+ };
155
+ this.allPackagesDependencies = {
156
+ packageDependencies: {},
157
+ devPackageDependencies: {},
158
+ peerPackageDependencies: {}
159
+ };
160
+ this.processedFiles = [];
161
+ this.issues = component.issues;
162
+ this.debugDependenciesData = {
163
+ components: []
164
+ };
165
+ }
166
+ get consumer() {
167
+ return this.workspace.consumer;
168
+ }
169
+ setTree(tree) {
170
+ this.tree = tree;
171
+ // console.log(JSON.stringify(tree, null, 4)); // uncomment to easily watch the tree received from bit-javascript
172
+ }
173
+
174
+ /**
175
+ * Resolve components and packages dependencies for a component.
176
+ * This method should NOT have any side-effect on the component. the DependenciesLoader class is
177
+ * responsible for saving this data on the component object.
178
+ *
179
+ * The process is as follows:
180
+ * 1) Use the language driver to parse the component files and find for each file its dependencies.
181
+ * 2) The results we get from the driver per file tells us what are the files and packages that depend on our file.
182
+ * and also whether there are missing packages and files.
183
+ * 3) Using the information from the driver, we go over each one of the dependencies files and find its counterpart
184
+ * component. The way how we find it, is by using the bit.map file which has a mapping between the component name and
185
+ * the file paths.
186
+ * 4) If we find a component to the file dependency, we add it to component.dependencies. Otherwise, it's added to
187
+ * component.issues.untrackedDependencies
188
+ * 5) Similarly, when we find the packages dependencies, they are added to component.packageDependencies. Otherwise,
189
+ * they're added to component.issues.missingPackagesDependenciesOnFs
190
+ * 6) In case the driver found a file dependency that is not on the file-system, we add that file to
191
+ * component.issues.missingDependenciesOnFs
192
+ */
193
+ async getDependenciesData(cacheResolvedDependencies, cacheProjectAst) {
194
+ const componentDir = path().join(this.consumerPath, this.componentMap.rootDir);
195
+ const {
196
+ nonTestsFiles,
197
+ testsFiles
198
+ } = this.componentMap.getFilesGroupedByBeingTests();
199
+ const allFiles = [...nonTestsFiles, ...testsFiles];
200
+ const envDetectors = await this.getEnvDetectors();
201
+ // find the dependencies (internal files and packages) through automatic dependency resolution
202
+ const dependenciesTree = await (0, _filesDependencyBuilder().getDependencyTree)({
203
+ componentDir,
204
+ workspacePath: this.consumerPath,
205
+ filePaths: allFiles,
206
+ bindingPrefix: this.component.bindingPrefix,
207
+ visited: cacheResolvedDependencies,
208
+ cacheProjectAst,
209
+ envDetectors
210
+ });
211
+ // we have the files dependencies, these files should be components that are registered in bit.map. Otherwise,
212
+ // they are referred as "untracked components" and the user should add them later on in order to tag
213
+ this.setTree(dependenciesTree.tree);
214
+ const devFiles = await this.devFiles.getDevFilesForConsumerComp(this.component);
215
+ await this.populateDependencies(allFiles, devFiles);
216
+ return {
217
+ dependenciesData: new (_dependenciesData().DependenciesData)(this.allDependencies, this.allPackagesDependencies, this.issues, this.coreAspects),
218
+ debugDependenciesData: this.debugDependenciesData
219
+ };
220
+ }
221
+ async getEnvDetectors() {
222
+ return this.depsResolver.calcComponentEnvDepDetectors(this.component.extensions);
223
+ }
224
+
225
+ /**
226
+ * Given the tree of file dependencies from the driver, find the components of these files.
227
+ * Each dependency file has a path, use bit.map to search for the component name by that path.
228
+ * If the component is found, add it to "this.allDependencies.dependencies". Otherwise, add it to "this.issues.untrackedDependencies".
229
+ *
230
+ * For the found components, add their sourceRelativePath and destinationRelativePath, they are being used for
231
+ * generating links upon import:
232
+ * sourceRelativePath - location of the link file.
233
+ * destinationRelativePath - destination written inside the link file.
234
+ *
235
+ * When a dependency is found in a regular (implementation) file, it goes to `dependencies`. If
236
+ * it found on a test file, it goes to `devDependencies`.
237
+ * Similarly, when a package is found in a regular file, it goes to `packageDependencies`. When
238
+ * if found in a test file, it goes to `devPackageDependencies`.
239
+ * An exception for the above is when a package is required in a regular or test file but is also
240
+ * mentioned in the `package.json` file as a peerDependency, in that case, the package is added
241
+ * to `peerPackageDependencies` and removed from other places. Unless this package is overridden
242
+ * and marked as ignored in the consumer or component config file.
243
+ */
244
+ async populateDependencies(files, testsFiles) {
245
+ files.forEach(file => {
246
+ const fileType = {
247
+ isTestFile: testsFiles.includes(file)
248
+ };
249
+ this.throwForNonExistFile(file);
250
+ this.processCoreAspects(file);
251
+ this.processMissing(file, fileType);
252
+ this.processErrors(file);
253
+ this.processPackages(file, fileType);
254
+ this.processComponents(file, fileType);
255
+ this.processDepFiles(file, fileType);
256
+ this.processUnidentifiedPackages(file);
257
+ });
258
+ }
259
+ throwForNonExistFile(file) {
260
+ if (!this.tree[file]) {
261
+ throw new Error(`DependencyResolver: a file "${file}" was not returned from the driver, its dependencies are unknown`);
262
+ }
263
+ }
264
+ getComponentIdByResolvedPackageData(bit) {
265
+ if (!bit.componentId) {
266
+ throw new Error(`resolved Bit component must have componentId prop in the package.json file`);
267
+ }
268
+ return bit.componentId;
269
+ }
270
+
271
+ /**
272
+ * this happens when using relative paths between components, which is allowed on Legacy only.
273
+ * on Harmony, during the execution of this function, it recognizes the use of relative-paths, enter
274
+ * it to the "issues", then, later, it shows a warning on bit-status and block tagging.
275
+ */
276
+ getComponentIdByDepFile(depFile) {
277
+ let depFileRelative = depFile; // dependency file path relative to consumer root
278
+ let destination;
279
+ const rootDir = this.componentMap.rootDir;
280
+ // The depFileRelative is relative to rootDir, change it to be relative to current consumer.
281
+ // We can't use path.resolve(rootDir, fileDep) because this might not work when running
282
+ // bit commands not from root, because resolve take by default the process.cwd
283
+ const rootDirFullPath = path().join(this.consumerPath, rootDir);
284
+ const fullDepFile = path().resolve(rootDirFullPath, depFile);
285
+ depFileRelative = (0, _utils().pathNormalizeToLinux)(path().relative(this.consumerPath, fullDepFile));
286
+ const componentId = this.consumer.bitMap.getComponentIdByPath(depFileRelative);
287
+ return {
288
+ componentId,
289
+ depFileRelative,
290
+ destination
291
+ };
292
+ }
293
+ processDepFiles(originFile, fileType, nested = false) {
294
+ // We don't just return because different files of the component might import different things from the depFile
295
+ // See more info here: https://github.com/teambit/bit/issues/1796
296
+ if (!this.processedFiles.includes(originFile)) {
297
+ this.processedFiles.push(originFile);
298
+ // We don't want to calculate nested files again after they calculated as direct files
299
+ } else if (nested) {
300
+ return;
301
+ }
302
+ const allDepsFiles = this.tree[originFile].files;
303
+ if (!allDepsFiles || _ramda().default.isEmpty(allDepsFiles)) return;
304
+ allDepsFiles.forEach(depFile => {
305
+ const isDepFileUntracked = this.processOneDepFile(originFile, depFile.file, depFile.importSpecifiers, fileType, depFile, nested);
306
+ // Only continue recursively if the dep file is untracked
307
+ // for tracked deps if they have untracked deps they will be shown under their own components
308
+ if (isDepFileUntracked) {
309
+ // Recursively check for untracked files (to show them all in bit status)
310
+ // for nested files we don't really care about the file types since we won't do all the checking
311
+ const dummyFileType = {
312
+ isTestFile: false
313
+ };
314
+ this.processDepFiles(depFile.file, dummyFileType, true);
315
+ }
316
+ });
317
+ }
318
+
319
+ // return true if the dep file is untracked
320
+ processOneDepFile(originFile, depFile, importSpecifiers, fileType, depFileObject, nested = false) {
321
+ const {
322
+ componentId,
323
+ depFileRelative,
324
+ destination
325
+ } = this.getComponentIdByDepFile(depFile);
326
+ const importSource = depFileObject.importSource;
327
+ // the file dependency doesn't have any counterpart component. Add it to this.issues.untrackedDependencies
328
+ if (!componentId) {
329
+ this._pushToUntrackDependenciesIssues(originFile, depFileRelative, nested);
330
+ return true;
331
+ }
332
+ // happens when in the same component one file requires another one. In this case, there is
333
+ // noting to do regarding the dependencies
334
+ if (componentId.isEqual(this.componentId, {
335
+ ignoreVersion: true
336
+ })) {
337
+ return false;
338
+ }
339
+ const depComponentMap = this.consumer.bitMap.getComponentIfExist(componentId);
340
+ // found a dependency component. Add it to this.allDependencies.dependencies
341
+ const depRootDir = depComponentMap ? depComponentMap.rootDir : undefined;
342
+ const destinationRelativePath = destination || (depRootDir && depFileRelative.startsWith(depRootDir) ? (0, _utils().pathRelativeLinux)(depRootDir, depFileRelative) : depFileRelative);
343
+
344
+ // when there is no rootDir for the current dependency (it happens when it's AUTHORED), keep the original path
345
+ const sourceRelativePath = depRootDir ? depFileRelative : depFile;
346
+ const depsPaths = {
347
+ sourceRelativePath,
348
+ destinationRelativePath
349
+ };
350
+ if (importSpecifiers) {
351
+ importSpecifiers.forEach(importSpecifier => {
352
+ if (importSpecifier.mainFile) delete importSpecifier.mainFile.exported;
353
+ });
354
+ depsPaths.importSpecifiers = importSpecifiers;
355
+ }
356
+ const currentComponentsDeps = new (_dependencies().Dependency)(componentId, [depsPaths]);
357
+ this._pushToRelativeComponentsAuthoredIssues(originFile, componentId, importSource, depsPaths);
358
+ const allDependencies = [...this.allDependencies.dependencies, ...this.allDependencies.devDependencies];
359
+ const existingDependency = this.getExistingDependency(allDependencies, componentId);
360
+ if (existingDependency) {
361
+ const existingDepRelativePaths = this.getExistingDepRelativePaths(existingDependency, depsPaths);
362
+ if (!existingDepRelativePaths) {
363
+ // it is another file of an already existing component. Just add the new path
364
+ existingDependency.relativePaths.push(depsPaths);
365
+ return false;
366
+ }
367
+ // The dep path already exists but maybe this dep-file has more importSpecifiers
368
+ if (depsPaths.importSpecifiers) {
369
+ // add them to the existing dep
370
+ if (!existingDepRelativePaths.importSpecifiers) {
371
+ existingDepRelativePaths.importSpecifiers = [...depsPaths.importSpecifiers];
372
+ } else {
373
+ // both have importSpecifiers
374
+ const nonExistingImportSpecifiers = this.getDiffSpecifiers(existingDepRelativePaths.importSpecifiers, depsPaths.importSpecifiers);
375
+ existingDepRelativePaths.importSpecifiers.push(...nonExistingImportSpecifiers);
376
+ }
377
+ }
378
+ if (depsPaths.importSource && !existingDepRelativePaths.importSource) {
379
+ existingDepRelativePaths.importSource = depsPaths.importSource;
380
+ }
381
+ } else {
382
+ const depDebug = {
383
+ id: currentComponentsDeps.id,
384
+ importSource
385
+ };
386
+ this.pushToDependenciesArray(currentComponentsDeps, fileType, depDebug);
387
+ }
388
+ return false;
389
+ }
390
+
391
+ /**
392
+ * process require/import of Bit components where the require statement is not a relative path
393
+ * but a module path, such as `require('@bit/bit.envs/compiler/babel');`
394
+ */
395
+ processComponents(originFile, fileType) {
396
+ const components = this.tree[originFile].components;
397
+ if (!components || _ramda().default.isEmpty(components)) return;
398
+ components.forEach(compDep => {
399
+ let componentId = this.getComponentIdByResolvedPackageData(compDep);
400
+ if (componentId.isEqual(this.componentId)) {
401
+ // the component is importing itself, so ignore it. although currently it doesn't cause any issues, (probably
402
+ // because it filtered out later), it's better to remove it as soon as possible, for less-confusing debugging.
403
+ return;
404
+ }
405
+ const depDebug = {
406
+ id: componentId,
407
+ dependencyPackageJsonPath: compDep.packageJsonPath,
408
+ dependentPackageJsonPath: compDep.dependentPackageJsonPath,
409
+ componentIdResolvedFrom: 'DependencyPkgJson',
410
+ packageName: compDep.name
411
+ };
412
+ const getVersionFromPkgJson = () => {
413
+ const versionFromDependencyPkgJson = getValidVersion(compDep.concreteVersion);
414
+ if (versionFromDependencyPkgJson) {
415
+ depDebug.versionResolvedFrom = 'DependencyPkgJson';
416
+ return versionFromDependencyPkgJson;
417
+ }
418
+ const versionFromDependentPkgJson = getValidVersion(compDep.versionUsedByDependent);
419
+ if (versionFromDependentPkgJson) {
420
+ depDebug.versionResolvedFrom = 'DependentPkgJson';
421
+ return versionFromDependentPkgJson;
422
+ }
423
+ return null;
424
+ };
425
+ const version = getVersionFromPkgJson();
426
+ if (version) {
427
+ componentId = componentId.changeVersion(version);
428
+ }
429
+ const existingId = componentId;
430
+ if (existingId.isEqual(this.componentId)) {
431
+ // happens when one of the component files requires another using module path
432
+ // no need to enter anything to the dependencies
433
+ return;
434
+ }
435
+ this.addImportNonMainIssueIfNeeded(originFile, compDep);
436
+ const currentComponentsDeps = new (_dependencies().Dependency)(existingId, [], compDep.name);
437
+ this._pushToDependenciesIfNotExist(currentComponentsDeps, fileType, depDebug);
438
+ });
439
+ }
440
+ isPkgInWorkspacePolicies(pkgName) {
441
+ var _this$depsResolver$ge;
442
+ return (_this$depsResolver$ge = this.depsResolver.getWorkspacePolicyManifest().dependencies) === null || _this$depsResolver$ge === void 0 ? void 0 : _this$depsResolver$ge[pkgName];
443
+ }
444
+ addImportNonMainIssueIfNeeded(filePath, dependencyPkgData) {
445
+ var _dependencyPkgData$pa, _dependencyPkgData$pa2;
446
+ const depMain = (_dependencyPkgData$pa = dependencyPkgData.packageJsonContent) === null || _dependencyPkgData$pa === void 0 ? void 0 : _dependencyPkgData$pa.main;
447
+ if (!depMain) {
448
+ return;
449
+ }
450
+ const depFullPath = (0, _utils().pathNormalizeToLinux)(dependencyPkgData.fullPath);
451
+ if (depFullPath.endsWith(depMain)) {
452
+ // it requires the main-file. all is good.
453
+ return;
454
+ }
455
+ const extDisallowNonMain = ['.ts', '.tsx', '.js', '.jsx'];
456
+ if (!extDisallowNonMain.includes(path().extname(depFullPath))) {
457
+ // some files such as scss/json are needed to be imported as non-main
458
+ return;
459
+ }
460
+ const pkgRootDir = (_dependencyPkgData$pa2 = dependencyPkgData.packageJsonContent) === null || _dependencyPkgData$pa2 === void 0 ? void 0 : _dependencyPkgData$pa2.componentRootFolder;
461
+ if (pkgRootDir && !_fsExtra().default.existsSync(path().join(pkgRootDir, _constants().DEFAULT_DIST_DIRNAME))) {
462
+ // the dependency wasn't compiled yet. the issue is probably because depMain points to the dist
463
+ // and depFullPath is in the source.
464
+ return;
465
+ }
466
+ const nonMainFileSplit = depFullPath.split(`node_modules/`);
467
+ const nonMainFileShort = nonMainFileSplit[1] || nonMainFileSplit[0];
468
+ if (nonMainFileShort.includes('eslintrc')) {
469
+ // a temporary workaround for envs that don't expose eslintrc config in their index file.
470
+ // this is needed for a future change of detecting require.resolve syntax
471
+ return;
472
+ }
473
+ (this.issues.getOrCreate(_componentIssues().IssuesClasses.ImportNonMainFiles).data[filePath] ||= []).push(nonMainFileShort);
474
+ }
475
+ processPackages(originFile, fileType) {
476
+ var _this$tree$originFile;
477
+ const packages = this.tree[originFile].packages;
478
+ if (this.componentFromModel) {
479
+ const modelDeps = this.componentFromModel.getAllPackageDependencies();
480
+ // If a package is not in the policies, then we resolve the package from the model.
481
+ for (const pkgName of Object.keys(packages)) {
482
+ if (!this.isPkgInWorkspacePolicies(pkgName) && modelDeps[pkgName]) {
483
+ packages[pkgName] = modelDeps[pkgName];
484
+ }
485
+ }
486
+ }
487
+ const packageNames = Object.keys(packages).concat(((_this$tree$originFile = this.tree[originFile].missing) === null || _this$tree$originFile === void 0 ? void 0 : _this$tree$originFile.packages) ?? []);
488
+ this._addTypesPackagesForTypeScript(packageNames, originFile);
489
+ if (!packages || _ramda().default.isEmpty(packages)) return;
490
+ if (fileType.isTestFile) {
491
+ Object.assign(this.allPackagesDependencies.devPackageDependencies, packages);
492
+ } else {
493
+ Object.assign(this.allPackagesDependencies.packageDependencies, packages);
494
+ }
495
+ }
496
+ processMissing(originFile, fileType) {
497
+ const missing = this.tree[originFile].missing;
498
+ if (!missing) return;
499
+ const processMissingFiles = () => {
500
+ if ((0, _lodash().isEmpty)(missing.files)) return;
501
+ const missingFiles = missing.files.filter(file => {
502
+ const hasExtension = Boolean(path().extname(file));
503
+ if (!hasExtension) return true;
504
+ // the missing file has extension, e.g. "index.js". It's possible that this file doesn't exist in the source
505
+ // but will be available in the dists. so if found same filename without the extension, we assume it's fine.
506
+ const rootDirAbs = this.consumer.toAbsolutePath(this.componentMap.rootDir);
507
+ const filePathAbs = path().resolve(rootDirAbs, file);
508
+ const relativeToCompDir = path().relative(rootDirAbs, filePathAbs);
509
+ const relativeToCompDirWithoutExt = (0, _path2().removeFileExtension)(relativeToCompDir);
510
+ const compFilesWithoutExt = this.componentMap.getAllFilesPaths().map(f => (0, _path2().removeFileExtension)(f));
511
+ const existWithDifferentExt = compFilesWithoutExt.some(f => f === relativeToCompDirWithoutExt);
512
+ return !existWithDifferentExt;
513
+ });
514
+ if (_ramda().default.isEmpty(missingFiles)) return;
515
+ this._pushToMissingDependenciesOnFs(originFile, missingFiles);
516
+ };
517
+ const processMissingPackages = () => {
518
+ if ((0, _lodash().isEmpty)(missing.packages)) return;
519
+ const missingPackages = missing.packages;
520
+ if (!_ramda().default.isEmpty(missingPackages)) {
521
+ this._pushToMissingPackagesDependenciesIssues(originFile, missingPackages, fileType);
522
+ }
523
+ };
524
+ processMissingFiles();
525
+ processMissingPackages();
526
+ }
527
+ processErrors(originFile) {
528
+ const error = this.tree[originFile].error;
529
+ if (!error) return;
530
+ _logger().default.errorAndAddBreadCrumb('dependency-resolver.processErrors', 'got an error from the driver while resolving dependencies');
531
+ _logger().default.error('dependency-resolver.processErrors', error);
532
+ if (error.code === 'PARSING_ERROR') {
533
+ const location = error.lineNumber && error.column ? ` (line: ${error.lineNumber}, column: ${error.column})` : '';
534
+ this.issues.getOrCreate(_componentIssues().IssuesClasses.ParseErrors).data[originFile] = error.message + location;
535
+ } else this.issues.getOrCreate(_componentIssues().IssuesClasses.ResolveErrors).data[originFile] = error.message;
536
+ }
537
+ getCoreAspectsPackagesAndIds() {
538
+ const allCoreAspectsIds = this.aspectLoader.getCoreAspectIds();
539
+ const coreAspectsPackagesAndIds = {};
540
+ allCoreAspectsIds.forEach(id => {
541
+ const packageName = (0, _aspectLoader().getCoreAspectPackageName)(id);
542
+ coreAspectsPackagesAndIds[packageName] = id;
543
+ });
544
+ return coreAspectsPackagesAndIds;
545
+ }
546
+
547
+ /**
548
+ * when a user uses core-extensions these core-extensions should not be dependencies.
549
+ * here, we filter them out from all places they could entered as dependencies.
550
+ * an exception is when running this method on bit-core-extensions themselves (dogfooding), in
551
+ * which case we recognizes that the current originFile is a core-extension and avoid filtering.
552
+ */
553
+ processCoreAspects(originFile) {
554
+ const coreAspects = this.getCoreAspectsPackagesAndIds();
555
+
556
+ // const scopes = coreAspects.map((id) => {
557
+ // const id = id.split()
558
+ // });
559
+
560
+ const coreAspectIds = Object.values(coreAspects);
561
+ if (coreAspectIds.includes(this.component.id.toStringWithoutVersion())) {
562
+ return;
563
+ }
564
+ const coreAspectsPackages = Object.keys(coreAspects);
565
+ const components = this.tree[originFile].components;
566
+ const unidentifiedPackages = this.tree[originFile].unidentifiedPackages;
567
+ const usedCoreAspects = [];
568
+ const findMatchingCoreAspect = packageName => {
569
+ return coreAspectsPackages.find(coreAspectName => packageName === coreAspectName);
570
+ };
571
+ const unidentifiedPackagesFiltered = unidentifiedPackages === null || unidentifiedPackages === void 0 ? void 0 : unidentifiedPackages.filter(packageName => {
572
+ const matchingCoreAspectPackageName = findMatchingCoreAspect(packageName);
573
+ if (matchingCoreAspectPackageName) {
574
+ usedCoreAspects.push(coreAspects[matchingCoreAspectPackageName]);
575
+ }
576
+ return !matchingCoreAspectPackageName;
577
+ });
578
+ const bitsFiltered = components === null || components === void 0 ? void 0 : components.filter(packageInfo => {
579
+ const matchingCoreAspectPackageName = findMatchingCoreAspect(packageInfo.name);
580
+ if (matchingCoreAspectPackageName) {
581
+ usedCoreAspects.push(coreAspects[matchingCoreAspectPackageName]);
582
+ }
583
+ return !matchingCoreAspectPackageName;
584
+ });
585
+ this.tree[originFile].unidentifiedPackages = unidentifiedPackagesFiltered;
586
+ this.tree[originFile].components = bitsFiltered;
587
+ this.coreAspects.push(..._ramda().default.uniq(usedCoreAspects));
588
+ }
589
+
590
+ /**
591
+ * ** LEGACY ONLY **
592
+ * This is related to a legacy feature "custom-module-resolution". the code was removed, only the debug is still there, just in case.
593
+ *
594
+ * ** OLD COMMENT **
595
+ * currently the only unidentified packages being process are the ones coming from custom-modules-resolution.
596
+ * assuming the author used custom-resolution, which enable using non-relative import syntax,
597
+ * for example, requiring the file 'src/utils/is-string' from anywhere as require('utils/is-string');
598
+ * now, when the component is imported, the driver recognizes 'utils/is-string' as a package,
599
+ * because it's not relative.
600
+ * the goal here is to use the 'package' the driver found and match it with one of the
601
+ * dependencies from the model. In the example above, we might find in the model, a dependency
602
+ * is-string with importSource of 'utils/is-string'.
603
+ * Once a match is found, copy the relativePaths from the model.
604
+ *
605
+ * keep in mind that this custom-modules-resolution supported on legacy components only.
606
+ * as such, no need to find the packageName to pass to _pushToDependenciesIfNotExist method.
607
+ */
608
+ processUnidentifiedPackages(originFile) {
609
+ const unidentifiedPackages = this.tree[originFile].unidentifiedPackages;
610
+ if (!unidentifiedPackages || !unidentifiedPackages.length) return;
611
+ this.debugDependenciesData.unidentifiedPackages = unidentifiedPackages;
612
+ }
613
+ _pushToDependenciesIfNotExist(dependency, fileType, depDebug) {
614
+ const existingDependency = this.getExistingDependency(this.allDependencies.dependencies, dependency.id);
615
+ const existingDevDependency = this.getExistingDependency(this.allDependencies.devDependencies, dependency.id);
616
+ // no need to enter dev dependency to devDependencies if it exists already in dependencies
617
+ if (existingDependency || existingDevDependency && fileType.isTestFile) {
618
+ return;
619
+ }
620
+ // at this point, either, it doesn't exist at all and should be entered.
621
+ // or it exists in devDependencies but now it comes from non-dev file, which should be entered
622
+ // as non-dev.
623
+ this.pushToDependenciesArray(dependency, fileType, depDebug);
624
+ }
625
+ pushToDependenciesArray(currentComponentsDeps, fileType, depDebug) {
626
+ if (fileType.isTestFile) {
627
+ this.allDependencies.devDependencies.push(currentComponentsDeps);
628
+ } else {
629
+ this.allDependencies.dependencies.push(currentComponentsDeps);
630
+ }
631
+ this.debugDependenciesData.components.push(depDebug);
632
+ }
633
+ getExistingDependency(dependencies, id) {
634
+ return dependencies.find(d => d.id.isEqualWithoutVersion(id));
635
+ }
636
+ getExistingDepRelativePaths(dependency, relativePath) {
637
+ if (!dependency.relativePaths || _ramda().default.isEmpty(dependency.relativePaths)) return null;
638
+ return dependency.relativePaths.find(paths => paths.sourceRelativePath === relativePath.sourceRelativePath && paths.destinationRelativePath === relativePath.destinationRelativePath);
639
+ }
640
+ getDiffSpecifiers(originSpecifiers, targetSpecifiers) {
641
+ const cmp = (specifier1, specifier2) => specifier1.mainFile.name === specifier2.mainFile.name;
642
+ return _ramda().default.differenceWith(cmp, targetSpecifiers, originSpecifiers);
643
+ }
644
+
645
+ /**
646
+ * when requiring packages in typescript, sometimes there are the types packages with the same
647
+ * name, which the user probably wants as well. for example, requiring `foo` package, will also
648
+ * add `@types/foo` to the devDependencies if it has been found in the user `package.json` file.
649
+ *
650
+ * ideally this should be in bit-javascript. however, the decision where to put these `@types`
651
+ * packages (dependencies/devDependencies) is done here according to the user `package.json`
652
+ * and can't be done there because the `Tree` we get from bit-javascript doesn't have this
653
+ * distinction.
654
+ */
655
+ _addTypesPackagesForTypeScript(packageNames, originFile) {
656
+ if (packageNames.length === 0) return;
657
+ const isTypeScript = (0, _utils().getExt)(originFile) === 'ts' || (0, _utils().getExt)(originFile) === 'tsx';
658
+ if (!isTypeScript) return;
659
+ const depsHost = this.depsResolver.getWorkspacePolicyManifest();
660
+ const addFromConfig = packageName => {
661
+ if (!depsHost) return false;
662
+ return _constants().DEPENDENCIES_FIELDS.some(depField => {
663
+ if (!depsHost[depField]) return false;
664
+ const typesPackage = (0, _packageToDefinetlyTyped().packageToDefinetlyTyped)(packageName);
665
+ if (!depsHost[depField][typesPackage]) return false;
666
+ Object.assign(this.allPackagesDependencies.devPackageDependencies, {
667
+ [typesPackage]: depsHost[depField][typesPackage]
668
+ });
669
+ return true;
670
+ });
671
+ };
672
+ const addFromModel = packageName => {
673
+ if (!this.componentFromModel) return;
674
+ const typesPackage = (0, _packageToDefinetlyTyped().packageToDefinetlyTyped)(packageName);
675
+ const typedPackageFromModel = this.componentFromModel.devPackageDependencies[typesPackage];
676
+ if (!typedPackageFromModel) return;
677
+ Object.assign(this.allPackagesDependencies.devPackageDependencies, {
678
+ [typesPackage]: typedPackageFromModel
679
+ });
680
+ };
681
+ packageNames.forEach(packageName => {
682
+ const added = addFromConfig(packageName);
683
+ if (!added) addFromModel(packageName);
684
+ });
685
+ }
686
+ _pushToUntrackDependenciesIssues(originFile, depFileRelative, nested = false) {
687
+ const findExisting = () => {
688
+ var _this$issues$getIssue;
689
+ let result;
690
+ _ramda().default.forEachObjIndexed(currentUntracked => {
691
+ const found = currentUntracked.untrackedFiles.find(file => {
692
+ return file.relativePath === depFileRelative;
693
+ });
694
+ if (found) {
695
+ result = found;
696
+ }
697
+ }, ((_this$issues$getIssue = this.issues.getIssue(_componentIssues().IssuesClasses.UntrackedDependencies)) === null || _this$issues$getIssue === void 0 ? void 0 : _this$issues$getIssue.data) || {});
698
+ return result;
699
+ };
700
+ const existing = findExisting();
701
+ const newUntrackedFile = {
702
+ relativePath: depFileRelative,
703
+ existing: false
704
+ };
705
+ // If it's already found mark them both as existing
706
+ if (existing) {
707
+ newUntrackedFile.existing = true;
708
+ existing.existing = true;
709
+ }
710
+ const untrackIssue = this.issues.getOrCreate(_componentIssues().IssuesClasses.UntrackedDependencies);
711
+ const untrackedCurrentFile = untrackIssue === null || untrackIssue === void 0 ? void 0 : untrackIssue.data[originFile];
712
+ if (untrackedCurrentFile) {
713
+ untrackedCurrentFile.untrackedFiles.push(newUntrackedFile);
714
+ } else {
715
+ untrackIssue.data[originFile] = {
716
+ nested,
717
+ untrackedFiles: [newUntrackedFile]
718
+ };
719
+ }
720
+ }
721
+ _pushToRelativeComponentsAuthoredIssues(originFile, componentId, importSource, relativePath) {
722
+ (this.issues.getOrCreate(_componentIssues().IssuesClasses.RelativeComponentsAuthored).data[originFile] ||= []).push({
723
+ importSource,
724
+ componentId,
725
+ relativePath
726
+ });
727
+ }
728
+ _pushToMissingDependenciesOnFs(originFile, missingFiles) {
729
+ (this.issues.getOrCreate(_componentIssues().IssuesClasses.MissingDependenciesOnFs).data[originFile] ||= []).push(...missingFiles);
730
+ }
731
+ _pushToMissingPackagesDependenciesIssues(originFile, missingPackages, fileType) {
732
+ const data = this.issues.getOrCreate(_componentIssues().IssuesClasses.MissingPackagesDependenciesOnFs).data;
733
+ const foundFile = data.find(file => file.filePath === originFile);
734
+ if (foundFile) {
735
+ foundFile.missingPackages = (0, _lodash().uniq)([...missingPackages, ...foundFile.missingPackages]);
736
+ } else {
737
+ data.push({
738
+ filePath: originFile,
739
+ missingPackages,
740
+ isDevFile: fileType.isTestFile
741
+ });
742
+ }
743
+ }
744
+ }
745
+ exports.AutoDetectDeps = AutoDetectDeps;
746
+ function getValidVersion(version) {
747
+ if (!version) {
748
+ return null;
749
+ }
750
+ if (_semver().default.valid(version)) {
751
+ // this takes care of pre-releases as well, as they're considered valid semver.
752
+ return version;
753
+ }
754
+ if (_semver().default.validRange(version)) {
755
+ // if this is a range, e.g. ^1.0.0, return a valid version: 1.0.0.
756
+ const coerced = _semver().default.coerce(version);
757
+ if (coerced) {
758
+ return coerced.version;
759
+ }
760
+ }
761
+ if ((0, _componentVersion().isSnap)(version)) {
762
+ return version;
763
+ }
764
+ // it's probably a relative path to the component
765
+ return null;
766
+ }
767
+
768
+ //# sourceMappingURL=auto-detect-deps.js.map