@teambit/aspect-loader 1.0.107 → 1.0.108

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/constants.ts ADDED
@@ -0,0 +1,16 @@
1
+ import chalk from 'chalk';
2
+
3
+ export const UNABLE_TO_LOAD_EXTENSION = (id: string, errMsg?: string) =>
4
+ `error: Bit received an error loading "${id}", due to the error "${
5
+ errMsg || '<unknown-error>'
6
+ }", please use the '--log=error' flag for the full error.`;
7
+ export const UNABLE_TO_LOAD_EXTENSION_FROM_LIST = (ids: string[], errMsg?: string, neededFor?: string) => {
8
+ // const installOutput = err?.code === 'MODULE_NOT_FOUND' ? `try running "bit install" to install the missing dependencies` : '';
9
+ const installOutput = `try running ${chalk.cyan('"bit install"')} to fix this issue`;
10
+ return `Bit received an error loading ${chalk.cyan(ids.join(', '))}, due to the error:
11
+ "${errMsg || '<unknown-error>'}".
12
+ This is required for the component: ${chalk.cyan(neededFor || 'unknown')}
13
+ Please use the ${chalk.cyan("'--log=error'")} flag for the full error.
14
+ ${installOutput}
15
+ `;
16
+ };
@@ -0,0 +1,10 @@
1
+ import { getCoreAspectName } from './core-aspects';
2
+
3
+ describe('core-aspects', () => {
4
+ describe('getCoreAspectName', () => {
5
+ it('should include the namespace in the aspect name', () => {
6
+ const aspectName = getCoreAspectName('teambit.workspace/e2e/workspace');
7
+ expect(aspectName).toEqual('e2e.workspace');
8
+ });
9
+ });
10
+ });
@@ -0,0 +1,153 @@
1
+ import { BitError } from '@teambit/bit-error';
2
+ import { existsSync, readdir } from 'fs-extra';
3
+ import { join, resolve } from 'path';
4
+ import { Config } from '@teambit/bvm.config';
5
+ import { findCurrentBvmDir } from '@teambit/bvm.path';
6
+
7
+ let _bvmConfig;
8
+
9
+ export function getBvmDir(): string {
10
+ if (!_bvmConfig) {
11
+ _bvmConfig = Config.load(false, ['env', 'file']);
12
+ }
13
+
14
+ const bvmConfig = _bvmConfig;
15
+ return bvmConfig.getBvmDirectory();
16
+ }
17
+
18
+ function isRunFromBvm() {
19
+ return __dirname.includes('.bvm') || __dirname.includes(getBvmDir());
20
+ }
21
+
22
+ function resolveFromPaths(packageName: string, aspectName: string, pathsToResolveAspects: string[]): string {
23
+ const moduleDirectory = require.resolve(packageName, { paths: pathsToResolveAspects });
24
+ const dirPath = join(moduleDirectory, '../..'); // to remove the "index.js" at the end
25
+ if (!existsSync(dirPath)) {
26
+ throw new Error(`unable to find ${aspectName} in ${dirPath}`);
27
+ }
28
+ return dirPath;
29
+ }
30
+
31
+ function resolveFromCurrDir(packageName: string, aspectName: string): string | undefined {
32
+ try {
33
+ const moduleDirectory = require.resolve(packageName);
34
+ const dirPath = join(moduleDirectory, '../..'); // to remove the "index.js" at the end
35
+ if (!existsSync(dirPath)) {
36
+ throw new Error(`unable to find ${aspectName} in ${dirPath}`);
37
+ }
38
+ return dirPath;
39
+ } catch (err) {
40
+ return undefined;
41
+ }
42
+ }
43
+ function resolveFromBvmDir(packageName: string): string | undefined {
44
+ const currentBitDir = findCurrentBvmDir();
45
+ if (currentBitDir) {
46
+ return resolve(currentBitDir, 'node_modules', packageName);
47
+ }
48
+ return undefined;
49
+ }
50
+
51
+ function getAspectDirFromPath(id: string, pathsToResolveAspects?: string[]): string {
52
+ const aspectName = getCoreAspectName(id);
53
+ const packageName = getCoreAspectPackageName(id);
54
+
55
+ if (pathsToResolveAspects && pathsToResolveAspects.length) {
56
+ const fromPaths = resolveFromPaths(packageName, aspectName, pathsToResolveAspects);
57
+ return fromPaths;
58
+ }
59
+ const isRunFromBvmDir = isRunFromBvm();
60
+ const resolvers = isRunFromBvmDir ? [resolveFromBvmDir, resolveFromCurrDir] : [resolveFromCurrDir, resolveFromBvmDir];
61
+ for (const resolver of resolvers) {
62
+ const currResolved = resolver(packageName, aspectName);
63
+ if (currResolved) return currResolved;
64
+ }
65
+ throw new Error(`unable to find ${aspectName}`);
66
+ }
67
+
68
+ export function getAspectDir(id: string): string {
69
+ const aspectName = getCoreAspectName(id);
70
+ let dirPath;
71
+
72
+ try {
73
+ dirPath = getAspectDirFromPath(id);
74
+ } catch (err: any) {
75
+ dirPath = resolve(__dirname, '../..', aspectName, 'dist');
76
+ }
77
+ if (!existsSync(dirPath)) {
78
+ throw new Error(`unable to find ${aspectName} in ${dirPath}`);
79
+ }
80
+ return dirPath;
81
+ }
82
+
83
+ type BvmDirOptions = {
84
+ version?: string;
85
+ linkName?: string;
86
+ };
87
+
88
+ export function getAspectDirFromBvm(id: string, bvmDirOptions?: BvmDirOptions): string {
89
+ // Resolve from default link
90
+ if (!bvmDirOptions) {
91
+ const packageName = getCoreAspectPackageName(id);
92
+ const resolved = resolveFromBvmDir(packageName);
93
+ if (resolved) return resolved;
94
+ }
95
+
96
+ if (!_bvmConfig) {
97
+ _bvmConfig = Config.load(false, ['env', 'file']);
98
+ }
99
+
100
+ const bvmConfig = _bvmConfig;
101
+ let version;
102
+ if (bvmDirOptions?.version) {
103
+ version = bvmDirOptions?.version;
104
+ } else {
105
+ const link = bvmDirOptions?.linkName || bvmConfig.getDefaultLinkName();
106
+ if (!link) {
107
+ throw new BitError(`can't find link in bvm config. most likely bvm is not installed`);
108
+ }
109
+ const links = bvmConfig.getLinks();
110
+ version = links[link];
111
+ if (!version) {
112
+ throw new BitError(`can't find link named ${bvmDirOptions?.linkName} in bvm config`);
113
+ }
114
+ }
115
+ const { versionDir, exists } = bvmConfig.getSpecificVersionDir(version, true);
116
+ if (!exists) {
117
+ throw new BitError(`can't find version ${version} in bvm folder`);
118
+ }
119
+ return getAspectDirFromPath(id, [versionDir]);
120
+ }
121
+
122
+ export function getAspectDistDir(id: string) {
123
+ return resolve(`${getAspectDir(id)}/dist`);
124
+ }
125
+
126
+ export function getCoreAspectName(id: string): string {
127
+ const [, ...name] = id.split('/');
128
+ const aspectName = name.join('.');
129
+ return aspectName;
130
+ }
131
+
132
+ export function getCoreAspectPackageName(id: string): string {
133
+ const aspectName = getCoreAspectName(id);
134
+ return `@teambit/${aspectName}`;
135
+ }
136
+
137
+ export async function getAspectDef(aspectName: string, runtime?: string) {
138
+ const dirPath = getAspectDistDir(aspectName);
139
+
140
+ const files = await readdir(dirPath);
141
+ let runtimeFile;
142
+ if (runtime) {
143
+ runtimeFile = files.find((file) => file.includes(`.${runtime}.runtime.js`)) || null;
144
+ }
145
+ const aspectFile = files.find((file) => file.includes(`.aspect.js`)) || null;
146
+
147
+ return {
148
+ id: aspectName,
149
+ aspectPath: join(dirPath, '..'),
150
+ aspectFilePath: aspectFile ? resolve(`${dirPath}/${aspectFile}`) : null,
151
+ runtimePath: runtimeFile ? resolve(`${dirPath}/${runtimeFile}`) : null,
152
+ };
153
+ }
@@ -1,5 +1,5 @@
1
1
  import { Component } from '@teambit/component';
2
- export declare type AspectDefinitionProps = {
2
+ export type AspectDefinitionProps = {
3
3
  id?: string;
4
4
  component?: Component;
5
5
  aspectPath: string;
@@ -23,15 +23,15 @@ export declare class AspectDefinition {
23
23
  /**
24
24
  * aspect component
25
25
  */
26
- readonly component?: Component | undefined;
26
+ readonly component?: Component;
27
27
  /**
28
28
  * id of the component (used instead of component in the case of core aspect)
29
29
  */
30
- readonly id?: string | undefined;
30
+ readonly id?: string;
31
31
  /**
32
32
  * aspect defined using 'file://' protocol
33
33
  */
34
- readonly local?: boolean | undefined;
34
+ readonly local?: boolean;
35
35
  constructor(
36
36
  /**
37
37
  * path to the root directory of the aspect module.
@@ -48,15 +48,15 @@ export declare class AspectDefinition {
48
48
  /**
49
49
  * aspect component
50
50
  */
51
- component?: Component | undefined,
51
+ component?: Component,
52
52
  /**
53
53
  * id of the component (used instead of component in the case of core aspect)
54
54
  */
55
- id?: string | undefined,
55
+ id?: string,
56
56
  /**
57
57
  * aspect defined using 'file://' protocol
58
58
  */
59
- local?: boolean | undefined);
60
- get getId(): string | null;
59
+ local?: boolean);
60
+ get getId(): string;
61
61
  static from({ component, aspectPath, aspectFilePath, runtimePath, id, local }: AspectDefinitionProps): AspectDefinition;
62
62
  }
@@ -1,2 +1,2 @@
1
- import React from 'react';
2
- export declare const Logo: () => React.JSX.Element;
1
+ /// <reference types="react" />
2
+ export declare const Logo: () => JSX.Element;
@@ -8,8 +8,8 @@ import { EnvsMain } from '@teambit/envs';
8
8
  import { AspectDefinition, AspectDefinitionProps } from './aspect-definition';
9
9
  import { PluginDefinition } from './plugin-definition';
10
10
  import { Plugins } from './plugins';
11
- export declare type PluginDefinitionSlot = SlotRegistry<PluginDefinition[]>;
12
- export declare type AspectDescriptor = {
11
+ export type PluginDefinitionSlot = SlotRegistry<PluginDefinition[]>;
12
+ export type AspectDescriptor = {
13
13
  /**
14
14
  * name of the extension.
15
15
  */
@@ -19,17 +19,17 @@ export declare type AspectDescriptor = {
19
19
  */
20
20
  icon?: string;
21
21
  };
22
- export declare type AspectResolver = (component: Component) => Promise<ResolvedAspect | undefined>;
23
- export declare type ResolvedAspect = {
22
+ export type AspectResolver = (component: Component) => Promise<ResolvedAspect | undefined>;
23
+ export type ResolvedAspect = {
24
24
  aspectPath: string;
25
25
  runtimePath: string | null;
26
26
  aspectFilePath: string | null;
27
27
  };
28
- export declare type LoadExtByManifestContext = {
28
+ export type LoadExtByManifestContext = {
29
29
  seeders?: string[];
30
30
  neededFor?: string;
31
31
  };
32
- export declare type LoadExtByManifestOptions = {
32
+ export type LoadExtByManifestOptions = {
33
33
  throwOnError?: boolean;
34
34
  hideMissingModuleError?: boolean;
35
35
  ignoreErrors?: boolean;
@@ -39,15 +39,15 @@ export declare type LoadExtByManifestOptions = {
39
39
  */
40
40
  unifyErrorsByExtId?: boolean;
41
41
  };
42
- declare type OnAspectLoadError = (err: Error, id: ComponentID) => Promise<boolean>;
43
- export declare type OnAspectLoadErrorSlot = SlotRegistry<OnAspectLoadError>;
44
- export declare type OnAspectLoadErrorHandler = (err: Error, component: Component) => Promise<boolean>;
45
- export declare type OnLoadRequireableExtension = (requireableExtension: RequireableComponent, manifest: ExtensionManifest | Aspect) => Promise<ExtensionManifest | Aspect>;
42
+ type OnAspectLoadError = (err: Error, id: ComponentID) => Promise<boolean>;
43
+ export type OnAspectLoadErrorSlot = SlotRegistry<OnAspectLoadError>;
44
+ export type OnAspectLoadErrorHandler = (err: Error, component: Component) => Promise<boolean>;
45
+ export type OnLoadRequireableExtension = (requireableExtension: RequireableComponent, manifest: ExtensionManifest | Aspect) => Promise<ExtensionManifest | Aspect>;
46
46
  /**
47
47
  * A slot which run during loading the requirable extension (after first manifest calculation)
48
48
  */
49
- export declare type OnLoadRequireableExtensionSlot = SlotRegistry<OnLoadRequireableExtension>;
50
- export declare type MainAspect = {
49
+ export type OnLoadRequireableExtensionSlot = SlotRegistry<OnLoadRequireableExtension>;
50
+ export type MainAspect = {
51
51
  /**
52
52
  * path to the main aspect.
53
53
  */
@@ -206,9 +206,8 @@ class AspectLoaderMain {
206
206
  _defineProperty(this, "failedLoadAspect", []);
207
207
  }
208
208
  getCompiler(component) {
209
- var _this$envs$getEnv;
210
- const env = (_this$envs$getEnv = this.envs.getEnv(component)) === null || _this$envs$getEnv === void 0 ? void 0 : _this$envs$getEnv.env;
211
- return env === null || env === void 0 ? void 0 : env.getCompiler();
209
+ const env = this.envs.getEnv(component)?.env;
210
+ return env?.getCompiler();
212
211
  }
213
212
  registerOnAspectLoadErrorSlot(onAspectLoadError) {
214
213
  this.onAspectLoadErrorSlot.register(onAspectLoadError);
@@ -323,8 +322,7 @@ class AspectLoaderMain {
323
322
  const configuredAspects = this.getConfiguredAspects();
324
323
  const harmonyExtensions = this.harmony.extensionsIds;
325
324
  const loadedExtensions = harmonyExtensions.filter(extId => {
326
- var _this$harmony$extensi;
327
- return (_this$harmony$extensi = this.harmony.extensions.get(extId)) === null || _this$harmony$extensi === void 0 ? void 0 : _this$harmony$extensi.loaded;
325
+ return this.harmony.extensions.get(extId)?.loaded;
328
326
  });
329
327
  const extensionsToLoad = (0, _lodash().difference)(configuredAspects, loadedExtensions);
330
328
  return extensionsToLoad;
@@ -583,8 +581,7 @@ class AspectLoaderMain {
583
581
  try {
584
582
  await aspectLoader.loadRequireableExtensions(resolvedAspects, true);
585
583
  } catch (err) {
586
- var _err$error;
587
- if ((err === null || err === void 0 || (_err$error = err.error) === null || _err$error === void 0 ? void 0 : _err$error.code) === 'MODULE_NOT_FOUND') {
584
+ if (err?.error?.code === 'MODULE_NOT_FOUND') {
588
585
  const resolvedAspectsAgain = await scope.getResolvedAspects(components, {
589
586
  skipIfExists: false,
590
587
  workspaceName: 'global-scope'
@@ -617,8 +614,7 @@ class AspectLoaderMain {
617
614
  if (componentIds && componentIds.length && filterOpts.requestedOnly) {
618
615
  const componentIdsString = componentIds.map(id => id.toString());
619
616
  defs = defs.filter(def => {
620
- var _def$component;
621
- return def.id && componentIdsString.includes(def.id) || def.component && componentIdsString.includes((_def$component = def.component) === null || _def$component === void 0 ? void 0 : _def$component.id.toString());
617
+ return def.id && componentIdsString.includes(def.id) || def.component && componentIdsString.includes(def.component?.id.toString());
622
618
  });
623
619
  }
624
620
  return defs;
@@ -748,9 +744,8 @@ class AspectLoaderMain {
748
744
  const graph = new (_graph().Graph)();
749
745
  manifests.forEach(manifest => graph.setNode(new (_graph().Node)(manifest.id, manifest)));
750
746
  manifests.forEach(manifest => {
751
- var _manifest$getRuntime;
752
- const deps = (_manifest$getRuntime = manifest.getRuntime(_cli().MainRuntime)) === null || _manifest$getRuntime === void 0 || (_manifest$getRuntime = _manifest$getRuntime.dependencies) === null || _manifest$getRuntime === void 0 ? void 0 : _manifest$getRuntime.map(dep => dep.id);
753
- deps === null || deps === void 0 || deps.forEach(dep => {
747
+ const deps = manifest.getRuntime(_cli().MainRuntime)?.dependencies?.map(dep => dep.id);
748
+ deps?.forEach(dep => {
754
749
  if (graph.node(dep)) {
755
750
  graph.setEdge(new (_graph().Edge)(manifest.id, dep, 'dep'));
756
751
  }