@teambit/aspect-loader 1.0.106 → 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.
@@ -0,0 +1,860 @@
1
+ import { join, resolve } from 'path';
2
+ import { NativeCompileCache } from '@teambit/toolbox.performance.v8-cache';
3
+ import esmLoader from '@teambit/node.utils.esm-loader';
4
+ // import findRoot from 'find-root';
5
+ import { readdirSync, existsSync } from 'fs-extra';
6
+ import { Graph, Node, Edge } from '@teambit/graph.cleargraph';
7
+ import { ComponentID } from '@teambit/component-id';
8
+ import LegacyScope from '@teambit/legacy/dist/scope/scope';
9
+ import { GLOBAL_SCOPE, DEFAULT_DIST_DIRNAME } from '@teambit/legacy/dist/constants';
10
+ import { MainRuntime } from '@teambit/cli';
11
+ import { ExtensionManifest, Harmony, Aspect, SlotRegistry, Slot } from '@teambit/harmony';
12
+ import { BitError } from '@teambit/bit-error';
13
+ import type { LoggerMain } from '@teambit/logger';
14
+ import { Component, FilterAspectsOptions } from '@teambit/component';
15
+ import { Logger, LoggerAspect } from '@teambit/logger';
16
+ import { RequireableComponent } from '@teambit/harmony.modules.requireable-component';
17
+ import { replaceFileExtToJs } from '@teambit/compilation.modules.babel-compiler';
18
+ import { EnvsAspect, EnvsMain } from '@teambit/envs';
19
+ import { loadBit } from '@teambit/bit';
20
+ import { ScopeAspect, ScopeMain } from '@teambit/scope';
21
+ import mapSeries from 'p-map-series';
22
+ import { difference, compact, flatten, intersection, uniqBy, some, isEmpty, isObject } from 'lodash';
23
+ import { AspectDefinition, AspectDefinitionProps } from './aspect-definition';
24
+ import { PluginDefinition } from './plugin-definition';
25
+ import { AspectLoaderAspect } from './aspect-loader.aspect';
26
+ import { UNABLE_TO_LOAD_EXTENSION, UNABLE_TO_LOAD_EXTENSION_FROM_LIST } from './constants';
27
+ import { isEsmModule } from './is-esm-module';
28
+ import { CannotLoadExtension } from './exceptions';
29
+ import { getAspectDef } from './core-aspects';
30
+ import { Plugins } from './plugins';
31
+
32
+ export type PluginDefinitionSlot = SlotRegistry<PluginDefinition[]>;
33
+
34
+ export type AspectDescriptor = {
35
+ /**
36
+ * name of the extension.
37
+ */
38
+ id: string;
39
+
40
+ /**
41
+ * icon of the extension.
42
+ */
43
+ icon?: string;
44
+ };
45
+
46
+ export type AspectResolver = (component: Component) => Promise<ResolvedAspect | undefined>;
47
+
48
+ export type ResolvedAspect = {
49
+ aspectPath: string;
50
+ runtimePath: string | null;
51
+ aspectFilePath: string | null;
52
+ };
53
+
54
+ export type LoadExtByManifestContext = {
55
+ seeders?: string[];
56
+ neededFor?: string;
57
+ };
58
+
59
+ export type LoadExtByManifestOptions = {
60
+ throwOnError?: boolean;
61
+ hideMissingModuleError?: boolean;
62
+ ignoreErrors?: boolean;
63
+ /**
64
+ * If this is enabled then we will show loading error only once for a given extension
65
+ * (even if it was actually try to load it few times by different components for example)
66
+ */
67
+ unifyErrorsByExtId?: boolean;
68
+ };
69
+
70
+ type OnAspectLoadError = (err: Error, id: ComponentID) => Promise<boolean>;
71
+ export type OnAspectLoadErrorSlot = SlotRegistry<OnAspectLoadError>;
72
+
73
+ export type OnAspectLoadErrorHandler = (err: Error, component: Component) => Promise<boolean>;
74
+
75
+ export type OnLoadRequireableExtension = (
76
+ requireableExtension: RequireableComponent,
77
+ manifest: ExtensionManifest | Aspect
78
+ ) => Promise<ExtensionManifest | Aspect>;
79
+ /**
80
+ * A slot which run during loading the requirable extension (after first manifest calculation)
81
+ */
82
+ export type OnLoadRequireableExtensionSlot = SlotRegistry<OnLoadRequireableExtension>;
83
+
84
+ export type MainAspect = {
85
+ /**
86
+ * path to the main aspect.
87
+ */
88
+ path: string;
89
+
90
+ /**
91
+ * version of the aspect.
92
+ */
93
+ version: string | undefined;
94
+
95
+ /**
96
+ * package name of the aspect
97
+ */
98
+ packageName: string | undefined;
99
+
100
+ /**
101
+ * reference to aspect manifest.
102
+ */
103
+ aspect: Aspect;
104
+
105
+ /**
106
+ * The name of the aspect (without the scope prefix)
107
+ */
108
+ name: string;
109
+
110
+ /**
111
+ * The name of the aspect
112
+ */
113
+ id: string;
114
+ };
115
+
116
+ export class AspectLoaderMain {
117
+ private inMemoryConfiguredAspects: string[] = [];
118
+ private failedToLoadExt = new Set<string>();
119
+ private alreadyShownWarning = new Set<string>();
120
+
121
+ constructor(
122
+ private logger: Logger,
123
+ private envs: EnvsMain,
124
+ private harmony: Harmony,
125
+ private onAspectLoadErrorSlot: OnAspectLoadErrorSlot,
126
+ private onLoadRequireableExtensionSlot: OnLoadRequireableExtensionSlot,
127
+ private pluginSlot: PluginDefinitionSlot
128
+ ) {}
129
+
130
+ private getCompiler(component: Component) {
131
+ const env = this.envs.getEnv(component)?.env;
132
+ return env?.getCompiler();
133
+ }
134
+
135
+ registerOnAspectLoadErrorSlot(onAspectLoadError: OnAspectLoadError) {
136
+ this.onAspectLoadErrorSlot.register(onAspectLoadError);
137
+ }
138
+
139
+ registerOnLoadRequireableExtensionSlot(onLoadRequireableExtension: OnLoadRequireableExtension) {
140
+ this.onLoadRequireableExtensionSlot.register(onLoadRequireableExtension);
141
+ }
142
+
143
+ /**
144
+ * returns whether the aspect-load issue has been fixed.
145
+ */
146
+ async triggerOnAspectLoadError(err: Error, component: Component): Promise<boolean> {
147
+ const entries = this.onAspectLoadErrorSlot.toArray(); // e.g. [ [ 'teambit.bit/compiler', [Function: bound onAspectLoadError] ] ]
148
+ let isFixed = false;
149
+ await mapSeries(entries, async ([, onAspectFailFunc]) => {
150
+ const result = await onAspectFailFunc(err, component.id);
151
+ if (result) isFixed = true;
152
+ });
153
+
154
+ return isFixed;
155
+ }
156
+
157
+ async getRuntimePath(component: Component, modulePath: string, runtime: string): Promise<string | null> {
158
+ const runtimeFile = component.filesystem.files.find((file: any) => {
159
+ return file.relative.includes(`.${runtime}.runtime`);
160
+ });
161
+
162
+ // @david we should add a compiler api for this.
163
+ if (!runtimeFile) return null;
164
+ try {
165
+ const compiler = this.getCompiler(component);
166
+
167
+ if (!compiler) {
168
+ return join(modulePath, runtimeFile.relative);
169
+ }
170
+
171
+ const dist = compiler.getDistPathBySrcPath(runtimeFile.relative);
172
+ return join(modulePath, dist);
173
+ } catch (e) {
174
+ this.logger.info(`got an error during get runtime path, probably the env is not loaded yet ${e}`);
175
+ // TODO: we are manually adding the dist here and replace the file name to handle case when
176
+ // we load aspects from scope, and their env in the same iteration, but we get into the aspect before its
177
+ // env, so it's env doesn't exist yet
178
+ // we should make sure to first load the env correctly before loading the aspect
179
+ const distPath = join(modulePath, DEFAULT_DIST_DIRNAME, replaceFileExtToJs(runtimeFile.relative));
180
+ return distPath;
181
+ }
182
+ }
183
+
184
+ async getAspectFilePath(component: Component, modulePath: string): Promise<string | null> {
185
+ const aspectFile = component.filesystem.files.find((file: any) => {
186
+ return file.relative.includes(`.aspect.ts`) || file.relative.includes(`.aspect.js`);
187
+ });
188
+
189
+ // @david we should add a compiler api for this.
190
+ if (!aspectFile) return null;
191
+ try {
192
+ const compiler = this.getCompiler(component);
193
+
194
+ if (!compiler) {
195
+ return join(modulePath, aspectFile.relative);
196
+ }
197
+
198
+ const dist = compiler.getDistPathBySrcPath(aspectFile.relative);
199
+ return join(modulePath, dist);
200
+ } catch (e) {
201
+ this.logger.info(`got an error during get runtime path, probably the env is not loaded yet ${e}`);
202
+ // TODO: we are manually adding the dist here and replace the file name to handle case when
203
+ // we load aspects from scope, and their env in the same iteration, but we get into the aspect before its
204
+ // env, so it's env doesn't exist yet
205
+ // we should make sure to first load the env correctly before loading the aspect
206
+ const distPath = join(modulePath, DEFAULT_DIST_DIRNAME, replaceFileExtToJs(aspectFile.relative));
207
+ return distPath;
208
+ }
209
+ }
210
+
211
+ isAspectLoaded(id: string) {
212
+ if (this.failedAspects.includes(id)) return true;
213
+ try {
214
+ return this.harmony.get(id);
215
+ } catch (err: any) {
216
+ return false;
217
+ }
218
+ }
219
+
220
+ getDescriptor(id: string): AspectDescriptor | undefined {
221
+ try {
222
+ const instance = this.harmony.get<any>(id);
223
+ const iconFn = instance.icon;
224
+
225
+ const icon = iconFn ? iconFn.apply(instance) : undefined;
226
+
227
+ return {
228
+ id,
229
+ icon,
230
+ };
231
+ } catch (err) {
232
+ return undefined;
233
+ }
234
+ }
235
+
236
+ /**
237
+ * This is used when adding aspects to workspace.jsonc during the process (like in bit use command)
238
+ * and we want to make sure that follow operation (like bit install) will recognize those aspects
239
+ * but the harmony config is already in memory.
240
+ * Probably a better to do it is to make sure we can re-load the config somehow
241
+ * ideally by adding the config class in harmony a reload API
242
+ * @param aspectId
243
+ */
244
+ addInMemoryConfiguredAspect(aspectId: string): void {
245
+ this.inMemoryConfiguredAspects.push(aspectId);
246
+ }
247
+
248
+ /**
249
+ * get all the configured aspects in the config file (workspace.jsonc / bit.jsonc)
250
+ */
251
+ getConfiguredAspects(): string[] {
252
+ const configuredAspects = Array.from(this.harmony.config.raw.keys());
253
+ const iMemoryConfiguredAspects = this.inMemoryConfiguredAspects;
254
+ return configuredAspects.concat(iMemoryConfiguredAspects);
255
+ }
256
+ getNotLoadedConfiguredExtensions() {
257
+ const configuredAspects = this.getConfiguredAspects();
258
+ const harmonyExtensions = this.harmony.extensionsIds;
259
+ const loadedExtensions = harmonyExtensions.filter((extId) => {
260
+ return this.harmony.extensions.get(extId)?.loaded;
261
+ });
262
+ const extensionsToLoad = difference(configuredAspects, loadedExtensions);
263
+ return extensionsToLoad;
264
+ }
265
+
266
+ loadDefinition(props: AspectDefinitionProps): AspectDefinition {
267
+ return AspectDefinition.from(props);
268
+ }
269
+
270
+ private _coreAspects: Aspect[] = [];
271
+
272
+ get coreAspects() {
273
+ return this._coreAspects;
274
+ }
275
+
276
+ isCoreAspect(id: string) {
277
+ const ids = this.getCoreAspectIds();
278
+ return ids.includes(id);
279
+ }
280
+
281
+ setCoreAspects(aspects: Aspect[]) {
282
+ this._coreAspects = aspects;
283
+ return this;
284
+ }
285
+
286
+ getCoreAspectIds() {
287
+ const ids = this.coreAspects.map((aspect) => aspect.id);
288
+ return ids.concat(this._reserved);
289
+ }
290
+
291
+ /**
292
+ * Get all the core envs ids which is still register in the bit manifest as core aspect
293
+ */
294
+ getCoreEnvsIds(): string[] {
295
+ const envsIds = this.envs.getCoreEnvsIds();
296
+ const allIds = this.getCoreAspectIds();
297
+ return intersection(allIds, envsIds);
298
+ }
299
+
300
+ isCoreEnv(id: string): boolean {
301
+ const ids = this.getCoreEnvsIds();
302
+ return ids.includes(id);
303
+ }
304
+
305
+ private _reserved = ['teambit.harmony/bit', 'teambit.harmony/config'];
306
+
307
+ getUserAspects(): string[] {
308
+ const coreAspectIds = this.getCoreAspectIds();
309
+ return difference(this.harmony.extensionsIds, coreAspectIds);
310
+ }
311
+
312
+ async getCoreAspectDefs(runtimeName?: string) {
313
+ const defs = await Promise.all(
314
+ this.coreAspects.map(async (aspect) => {
315
+ const id = aspect.id;
316
+ const rawDef = await getAspectDef(id, runtimeName);
317
+ return this.loadDefinition(rawDef);
318
+ })
319
+ );
320
+
321
+ return defs.filter((def) => def.runtimePath);
322
+ }
323
+
324
+ async resolveAspects(components: Component[], resolver: AspectResolver): Promise<AspectDefinition[]> {
325
+ const promises = components.map(async (component) => {
326
+ const resolvedAspect = await resolver(component);
327
+ if (!resolvedAspect) return undefined;
328
+ return new AspectDefinition(
329
+ resolvedAspect.aspectPath,
330
+ resolvedAspect.aspectFilePath,
331
+ resolvedAspect.runtimePath,
332
+ component
333
+ );
334
+ });
335
+
336
+ const aspectDefs = await Promise.all(promises);
337
+ // return aspectDefs.filter((def) => def.runtimePath);
338
+ return compact(aspectDefs);
339
+ }
340
+
341
+ private _mainAspect: MainAspect;
342
+
343
+ get mainAspect() {
344
+ return this._mainAspect;
345
+ }
346
+
347
+ setMainAspect(mainAspect: MainAspect) {
348
+ this._mainAspect = mainAspect;
349
+ return this;
350
+ }
351
+
352
+ private failedLoadAspect: string[] = [];
353
+
354
+ get failedAspects() {
355
+ return this.failedLoadAspect;
356
+ }
357
+
358
+ public resetFailedLoadAspects() {
359
+ this.failedLoadAspect = [];
360
+ }
361
+
362
+ private addFailure(id: string): void {
363
+ if (this.failedAspects.includes(id)) return;
364
+ this.failedLoadAspect.push(id);
365
+ }
366
+
367
+ cloneManifest(manifest: any) {
368
+ const cloned = Object.assign(Object.create(Object.getPrototypeOf(manifest)), manifest);
369
+ cloned.provider = manifest.provider;
370
+ cloned.addRuntime = manifest.addRuntime;
371
+ cloned.getRuntime = manifest.getRuntime;
372
+ return cloned;
373
+ }
374
+
375
+ /**
376
+ * run "require" of the component code to get the manifest
377
+ */
378
+ async doRequire(
379
+ requireableExtension: RequireableComponent,
380
+ runSubscribers = true
381
+ ): Promise<ExtensionManifest | Aspect> {
382
+ const idStr = requireableExtension.component.id.toString();
383
+ const aspect = await requireableExtension.require();
384
+ const manifest = aspect.default || aspect;
385
+ manifest.id = idStr;
386
+ // It's important to clone deep the manifest here to prevent mutate dependencies of other manifests as they point to the same location in memory
387
+ const cloned = this.cloneManifest(manifest);
388
+ if (runSubscribers) return this.runOnLoadRequireableExtensionSubscribers(requireableExtension, cloned);
389
+ return cloned;
390
+ }
391
+
392
+ /**
393
+ * in case the extension failed to load, prefer to throw an error, unless `throwOnError` param
394
+ * passed as `false`.
395
+ * there are cases when throwing an error blocks the user from doing anything else. for example,
396
+ * when a user develops an extension and deletes the node-modules, the extension on the workspace
397
+ * cannot be loaded anymore until "bit compile" is running. however, if this function throws an
398
+ * error, it'll throw for "bit compile" as well, which blocks the user.
399
+ * for the CI, it is important to throw an error because errors on console can be ignored.
400
+ * for now, when loading the extension from the workspace the throwOnError is passed as false.
401
+ * when loading from the scope (CI) it should be true.
402
+ *
403
+ * the console printing here is done directly by "console.error" and not by the logger. the reason
404
+ * is that the logger.console only prints when the loader started (which, btw, happens after
405
+ * entering this function, so it can't work) and here we want it to be printed regardless of the
406
+ * rules of starting the loader. e.g. if by mistake the CI got it as throwOnError=false, it's ok
407
+ * to break the output by the console.error.
408
+ *
409
+ * @todo: this is not the final word however about throwing/non throwing errors here.
410
+ * in some cases, such as "bit tag", it's better not to tag if an extension changes the model.
411
+ */
412
+ async loadRequireableExtensions(requireableExtensions: RequireableComponent[], throwOnError = false): Promise<void> {
413
+ const manifests = await this.getManifestsFromRequireableExtensions(requireableExtensions, throwOnError);
414
+ return this.loadExtensionsByManifests(manifests, undefined, { throwOnError });
415
+ }
416
+
417
+ async getManifestsFromRequireableExtensions(
418
+ requireableExtensions: RequireableComponent[],
419
+ throwOnError = false,
420
+ runSubscribers = true
421
+ ): Promise<Array<ExtensionManifest | Aspect>> {
422
+ const manifestsP = mapSeries(requireableExtensions, async (requireableExtension) => {
423
+ if (!requireableExtensions) return undefined;
424
+ const idStr = requireableExtension.component.id.toString();
425
+ try {
426
+ return await this.doRequire(requireableExtension, runSubscribers);
427
+ } catch (firstErr: any) {
428
+ this.addFailure(idStr);
429
+ this.logger.warn(`failed loading an aspect "${idStr}", will try to fix and reload`, firstErr);
430
+ const isFixed = await this.triggerOnAspectLoadError(firstErr, requireableExtension.component);
431
+ let errAfterReLoad;
432
+ if (isFixed) {
433
+ this.logger.info(`the loading issue might be fixed now, re-loading ${idStr}`);
434
+ try {
435
+ return await this.doRequire(requireableExtension);
436
+ } catch (err: any) {
437
+ this.logger.warn(`re-load of the aspect "${idStr}" failed as well`, err);
438
+ errAfterReLoad = err;
439
+ }
440
+ }
441
+ const error = errAfterReLoad || firstErr;
442
+ this.handleExtensionLoadingError(error, idStr, throwOnError);
443
+ }
444
+ return undefined;
445
+ });
446
+ const manifests = await manifestsP;
447
+
448
+ // Remove empty manifests as a result of loading issue
449
+ return compact(manifests);
450
+ }
451
+
452
+ handleExtensionLoadingError(error: Error, idStr: string, throwOnError: boolean) {
453
+ this.envs.addFailedToLoadExt(idStr);
454
+ const errorMsg = error.message.split('\n')[0]; // show only the first line if the error is long (e.g. happens with MODULE_NOT_FOUND errors)
455
+ const msg = UNABLE_TO_LOAD_EXTENSION(idStr, errorMsg);
456
+ if (throwOnError) {
457
+ // @ts-ignore
458
+ this.logger.console(error);
459
+ throw new CannotLoadExtension(idStr, error);
460
+ }
461
+ this.logger.error(msg, error);
462
+ this.printWarningIfFirstTime(idStr, msg, this.logger.isLoaderStarted);
463
+ }
464
+
465
+ private printWarningIfFirstTime(envId: string, msg: string, showAsFailure: boolean) {
466
+ if (!this.alreadyShownWarning.has(envId)) {
467
+ this.alreadyShownWarning.add(envId);
468
+ if (showAsFailure) {
469
+ this.logger.consoleFailure(msg);
470
+ } else {
471
+ this.logger.consoleWarning(msg);
472
+ }
473
+ }
474
+ }
475
+
476
+ async runOnLoadRequireableExtensionSubscribers(
477
+ requireableExtension: RequireableComponent,
478
+ manifest: ExtensionManifest | Aspect
479
+ ): Promise<ExtensionManifest | Aspect> {
480
+ let updatedManifest = manifest;
481
+ const entries = this.onLoadRequireableExtensionSlot.toArray();
482
+ await mapSeries(entries, async ([, onLoadRequireableExtensionFunc]) => {
483
+ updatedManifest = await onLoadRequireableExtensionFunc(requireableExtension, updatedManifest);
484
+ });
485
+ return updatedManifest;
486
+ }
487
+
488
+ getPluginDefs() {
489
+ return flatten(this.pluginSlot.values());
490
+ }
491
+
492
+ getPlugins(component: Component, componentPath: string): Plugins {
493
+ const defs = this.getPluginDefs();
494
+ return this.getPluginsFromDefs(component, componentPath, defs);
495
+ }
496
+
497
+ async isEsmModule(path: string) {
498
+ return isEsmModule(path);
499
+ }
500
+
501
+ async loadEsm(path: string) {
502
+ NativeCompileCache.uninstall();
503
+ return esmLoader(path);
504
+ }
505
+
506
+ getPluginsFromDefs(component: Component, componentPath: string, defs: PluginDefinition[]): Plugins {
507
+ return Plugins.from(
508
+ component,
509
+ defs,
510
+ this.triggerOnAspectLoadError.bind(this),
511
+ this.logger,
512
+ this.pluginFileResolver.call(this, component, componentPath)
513
+ );
514
+ }
515
+
516
+ getPluginFiles(component: Component, componentPath: string): string[] {
517
+ const defs = this.getPluginDefs();
518
+ return Plugins.files(component, defs, this.pluginFileResolver.call(this, component, componentPath));
519
+ }
520
+
521
+ hasPluginFiles(component: Component): boolean {
522
+ const defs = this.getPluginDefs();
523
+ const files = Plugins.files(component, defs);
524
+ return !isEmpty(files);
525
+ }
526
+
527
+ pluginFileResolver(component: Component, rootDir: string) {
528
+ return (relativePath: string) => {
529
+ const compiler = this.getCompiler(component);
530
+ if (!compiler) {
531
+ return join(rootDir, relativePath);
532
+ }
533
+
534
+ const dist = compiler.getDistPathBySrcPath(relativePath);
535
+ return join(rootDir, dist);
536
+ };
537
+ }
538
+
539
+ isAspect(manifest: any) {
540
+ return !!(manifest.addRuntime && manifest.getRuntime);
541
+ }
542
+
543
+ isValidAspect(manifest: any): boolean {
544
+ return this.isAspect(manifest) || manifest.provider;
545
+ }
546
+
547
+ isAspectComponent(component: Component): boolean {
548
+ return this.envs.isUsingAspectEnv(component);
549
+ }
550
+
551
+ /**
552
+ * get or create a global scope, import the non-core aspects, load bit from that scope, create
553
+ * capsules for the aspects and load them from the capsules.
554
+ */
555
+ async loadAspectsFromGlobalScope(
556
+ aspectIds: string[]
557
+ ): Promise<{ components: Component[]; globalScopeHarmony: Harmony }> {
558
+ const globalScope = await LegacyScope.ensure(GLOBAL_SCOPE, 'global-scope');
559
+ await globalScope.ensureDir();
560
+ const globalScopeHarmony = await loadBit(globalScope.path);
561
+ const scope = globalScopeHarmony.get<ScopeMain>(ScopeAspect.id);
562
+ const aspectLoader = globalScopeHarmony.get<AspectLoaderMain>(AspectLoaderAspect.id);
563
+ // @todo: Gilad make this work
564
+ // const ids = await scope.resolveMultipleComponentIds(aspectIds);
565
+ const ids = aspectIds.map((id) => ComponentID.fromString(id));
566
+ const hasVersions = ids.every((id) => id.hasVersion());
567
+ const useCache = hasVersions; // if all components has versions, try to use the cached aspects
568
+ await scope.import(ids, { useCache, reason: 'to load aspects from global scope' });
569
+ const components = await scope.getMany(ids, true);
570
+
571
+ // don't use `await scope.loadAspectsFromCapsules(components, true);`
572
+ // it won't work for globalScope because `this !== scope.aspectLoader` (this instance
573
+ // is not the same as the aspectLoader instance Scope has)
574
+ const resolvedAspects = await scope.getResolvedAspects(components, { workspaceName: 'global-scope' });
575
+ try {
576
+ await aspectLoader.loadRequireableExtensions(resolvedAspects, true);
577
+ } catch (err: any) {
578
+ if (err?.error?.code === 'MODULE_NOT_FOUND') {
579
+ const resolvedAspectsAgain = await scope.getResolvedAspects(components, {
580
+ skipIfExists: false,
581
+ workspaceName: 'global-scope',
582
+ });
583
+ await aspectLoader.loadRequireableExtensions(resolvedAspectsAgain, true);
584
+ } else {
585
+ throw err;
586
+ }
587
+ }
588
+
589
+ return { components, globalScopeHarmony };
590
+ }
591
+
592
+ filterAspectDefs(
593
+ allDefs: AspectDefinition[],
594
+ componentIds: ComponentID[],
595
+ runtimeName: string | undefined,
596
+ filterOpts: FilterAspectsOptions = {}
597
+ ) {
598
+ const coreIds = this.getCoreAspectIds();
599
+ const stringIds = componentIds.map((id) => id.toStringWithoutVersion());
600
+ const afterExclusion = filterOpts.excludeCore
601
+ ? allDefs.filter((def) => {
602
+ const isCore = coreIds.includes(def.getId || '');
603
+ const id = ComponentID.fromString(def.getId || '');
604
+ const isTarget = stringIds.includes(id.toStringWithoutVersion());
605
+ if (isTarget) return true;
606
+ return !isCore;
607
+ })
608
+ : allDefs;
609
+
610
+ const uniqDefs = uniqBy(afterExclusion, (def) => `${def.aspectPath}-${def.runtimePath}`);
611
+ let defs = uniqDefs;
612
+ if (runtimeName && filterOpts.filterByRuntime) {
613
+ defs = defs.filter((def) => def.runtimePath);
614
+ }
615
+
616
+ if (componentIds && componentIds.length && filterOpts.requestedOnly) {
617
+ const componentIdsString = componentIds.map((id) => id.toString());
618
+ defs = defs.filter((def) => {
619
+ return (
620
+ (def.id && componentIdsString.includes(def.id)) ||
621
+ (def.component && componentIdsString.includes(def.component?.id.toString()))
622
+ );
623
+ });
624
+ }
625
+
626
+ return defs;
627
+ }
628
+
629
+ getAspectIdFromAspectFile(aspectFilePath: string): string | undefined {
630
+ try {
631
+ // eslint-disable-next-line global-require, import/no-dynamic-require
632
+ const module = aspectFilePath ? require(aspectFilePath) : undefined;
633
+ let manifest = module.default || module;
634
+ if (this.isAspect(manifest)) {
635
+ return manifest.id;
636
+ }
637
+ if (isObject(manifest)) {
638
+ if (isEmpty(manifest)) {
639
+ this.logger.warn(
640
+ `getAspectIdFromAspectFile - aspect at ${aspectFilePath} missing exports. couldn't calculate the manifest`
641
+ );
642
+ return undefined;
643
+ }
644
+ if (Object.keys(manifest).length > 1) {
645
+ this.logger.warn(
646
+ `getAspectIdFromAspectFile - aspect at ${aspectFilePath} exports too many keys. couldn't calculate the manifest`
647
+ );
648
+ return undefined;
649
+ }
650
+ manifest = Object.values(manifest)[0];
651
+ if (this.isAspect(manifest)) {
652
+ return manifest.id;
653
+ }
654
+ }
655
+ this.logger.warn(`getAspectIdFromAspectFile - aspect at ${aspectFilePath} is not a valid aspect`);
656
+ return undefined;
657
+ } catch (err) {
658
+ this.logger.warn(`getAspectIdFromAspectFile - couldn't require the aspect file ${aspectFilePath}. err: ${err}`);
659
+ return undefined;
660
+ }
661
+ }
662
+
663
+ private prepareManifests(manifests: Array<ExtensionManifest | Aspect>): Aspect[] {
664
+ return manifests.map((manifest: any) => {
665
+ if (this.isAspect(manifest)) return manifest as Aspect;
666
+ manifest.runtime = MainRuntime;
667
+ if (!manifest.id) throw new Error('manifest must have static id');
668
+ const aspect = Aspect.create({
669
+ id: manifest.id,
670
+ });
671
+ aspect.addRuntime(manifest);
672
+ return aspect;
673
+ });
674
+ }
675
+
676
+ /**
677
+ * register a plugin.
678
+ */
679
+ registerPlugins(pluginDefs: PluginDefinition[]) {
680
+ this.pluginSlot.register(pluginDefs);
681
+ }
682
+
683
+ async loadExtensionsByManifests(
684
+ extensionsManifests: Array<ExtensionManifest | Aspect>,
685
+ context: LoadExtByManifestContext = {
686
+ seeders: [],
687
+ },
688
+ options: LoadExtByManifestOptions = {
689
+ throwOnError: true,
690
+ hideMissingModuleError: false,
691
+ ignoreErrors: false,
692
+ unifyErrorsByExtId: true,
693
+ }
694
+ ) {
695
+ const neededFor = context.neededFor;
696
+ const seeders = context.seeders || [];
697
+ const defaultLoadExtByManifestOptions = {
698
+ throwOnError: true,
699
+ hideMissingModuleError: false,
700
+ ignoreErrors: false,
701
+ unifyErrorsByExtId: true,
702
+ };
703
+ const mergedOptions = { ...defaultLoadExtByManifestOptions, ...options };
704
+ try {
705
+ const manifests = extensionsManifests.filter((manifest) => {
706
+ const isValid = this.isValidAspect(manifest);
707
+ if (!isValid) this.logger.warn(`${manifest.id} is invalid. please make sure the extension is valid.`);
708
+ return isValid;
709
+ });
710
+ const preparedManifests = this.prepareManifests(manifests);
711
+ // don't let harmony load all aspects. if seeders were sent, find their manifests, check for their static
712
+ // dependencies, and load only them.
713
+ const getOnlyDeclaredDependenciesManifests = () => {
714
+ if (!seeders.length || seeders.length === preparedManifests.length) {
715
+ return preparedManifests;
716
+ }
717
+ const manifestGraph = this.generateManifestGraph(preparedManifests);
718
+ const nodes = seeders.map((seeder) => manifestGraph.successors(seeder)).flat();
719
+ const seederNodes = compact(seeders.map((seeder) => manifestGraph.node(seeder)));
720
+ const allNodes = [...nodes, ...seederNodes];
721
+ const nodesUniq = uniqBy(allNodes, 'id');
722
+ return nodesUniq.map((n) => n.attr);
723
+ };
724
+ const relevantManifests = getOnlyDeclaredDependenciesManifests();
725
+ // @ts-ignore TODO: fix this
726
+ await this.harmony.load(relevantManifests);
727
+ } catch (e: any) {
728
+ const ids = extensionsManifests.map((manifest) => manifest.id || 'unknown');
729
+ // TODO: improve texts
730
+ const errorMsg = e.message.split('\n')[0];
731
+ const warning = UNABLE_TO_LOAD_EXTENSION_FROM_LIST(ids, errorMsg, neededFor);
732
+ this.logger.error(warning, e);
733
+ if (mergedOptions.ignoreErrors) return;
734
+ if (e.code === 'MODULE_NOT_FOUND' && mergedOptions.hideMissingModuleError) return;
735
+ if (mergedOptions.unifyErrorsByExtId) {
736
+ const needToPrint = some(ids, (id) => !this.failedToLoadExt.has(id));
737
+ if (!needToPrint) return;
738
+ ids.forEach((id) => {
739
+ this.failedToLoadExt.add(id);
740
+ this.envs.addFailedToLoadExt(id);
741
+ const parsedId = ComponentID.tryFromString(id);
742
+ if (parsedId) {
743
+ this.failedToLoadExt.add(parsedId.fullName);
744
+ this.envs.addFailedToLoadExt(parsedId.fullName);
745
+ }
746
+ });
747
+ }
748
+ if (this.logger.isLoaderStarted) {
749
+ if (mergedOptions.throwOnError) throw new BitError(warning);
750
+ this.logger.consoleFailure(warning);
751
+ } else {
752
+ this.logger.consoleWarning(warning);
753
+ this.logger.consoleWarning(e);
754
+ }
755
+ if (mergedOptions.throwOnError) {
756
+ throw e;
757
+ }
758
+ }
759
+ }
760
+
761
+ private generateManifestGraph(manifests: Aspect[]) {
762
+ const graph = new Graph<Aspect, string>();
763
+ manifests.forEach((manifest) => graph.setNode(new Node(manifest.id, manifest)));
764
+ manifests.forEach((manifest) => {
765
+ const deps = manifest.getRuntime(MainRuntime)?.dependencies?.map((dep) => dep.id);
766
+ deps?.forEach((dep) => {
767
+ if (graph.node(dep)) {
768
+ graph.setEdge(new Edge(manifest.id, dep, 'dep'));
769
+ }
770
+ });
771
+ });
772
+ return graph;
773
+ }
774
+
775
+ public async loadAspectFromPath(localAspects: string[]) {
776
+ const dirPaths = this.parseLocalAspect(localAspects);
777
+ const manifests = dirPaths.map((dirPath) => {
778
+ const scopeRuntime = this.findRuntime(dirPath, 'scope');
779
+ if (scopeRuntime) {
780
+ // eslint-disable-next-line global-require, import/no-dynamic-require
781
+ const module = require(join(dirPath, 'dist', scopeRuntime));
782
+ return module.default || module;
783
+ }
784
+ // eslint-disable-next-line global-require, import/no-dynamic-require
785
+ const module = require(dirPath);
786
+ return module.default || module;
787
+ });
788
+
789
+ await this.loadExtensionsByManifests(manifests, undefined, { throwOnError: true });
790
+ }
791
+
792
+ private parseLocalAspect(localAspects: string[]) {
793
+ const dirPaths = localAspects.map((localAspect) => resolve(localAspect.replace('file://', '')));
794
+ const nonExistsDirPaths = dirPaths.filter((path) => !existsSync(path));
795
+ nonExistsDirPaths.forEach((path) => this.logger.warn(`no such file or directory: ${path}`));
796
+ const existsDirPaths = dirPaths.filter((path) => existsSync(path));
797
+ return existsDirPaths;
798
+ }
799
+
800
+ private findRuntime(dirPath: string, runtime: string) {
801
+ const files = readdirSync(join(dirPath, 'dist'));
802
+ return files.find((path) => path.includes(`${runtime}.runtime.js`));
803
+ }
804
+
805
+ public async resolveLocalAspects(ids: string[], runtime?: string): Promise<AspectDefinition[]> {
806
+ const dirs = this.parseLocalAspect(ids);
807
+
808
+ return dirs.map((dir) => {
809
+ const srcRuntimeManifest = runtime ? this.findRuntime(dir, runtime) : undefined;
810
+ const srcAspectFilePath = runtime ? this.findAspectFile(dir) : undefined;
811
+ const aspectFilePath = srcAspectFilePath ? join(dir, 'dist', srcAspectFilePath) : null;
812
+ const runtimeManifest = srcRuntimeManifest ? join(dir, 'dist', srcRuntimeManifest) : null;
813
+ const aspectId = aspectFilePath ? this.getAspectIdFromAspectFile(aspectFilePath) : undefined;
814
+
815
+ return new AspectDefinition(dir, aspectFilePath, runtimeManifest, undefined, aspectId, true);
816
+ });
817
+ }
818
+
819
+ private findAspectFile(dirPath: string) {
820
+ const files = readdirSync(join(dirPath, 'dist'));
821
+ return files.find((path) => path.includes(`.aspect.js`));
822
+ }
823
+
824
+ static runtime = MainRuntime;
825
+ static dependencies = [LoggerAspect, EnvsAspect];
826
+ static slots = [
827
+ Slot.withType<OnAspectLoadError>(),
828
+ Slot.withType<OnLoadRequireableExtension>(),
829
+ Slot.withType<PluginDefinition[]>(),
830
+ ];
831
+
832
+ static async provider(
833
+ [loggerExt, envs]: [LoggerMain, EnvsMain],
834
+ config,
835
+ [onAspectLoadErrorSlot, onLoadRequireableExtensionSlot, pluginSlot]: [
836
+ OnAspectLoadErrorSlot,
837
+ OnLoadRequireableExtensionSlot,
838
+ PluginDefinitionSlot
839
+ ],
840
+ harmony: Harmony
841
+ ) {
842
+ const logger = loggerExt.createLogger(AspectLoaderAspect.id);
843
+ const aspectLoader = new AspectLoaderMain(
844
+ logger,
845
+ envs,
846
+ harmony,
847
+ onAspectLoadErrorSlot,
848
+ onLoadRequireableExtensionSlot,
849
+ pluginSlot
850
+ );
851
+
852
+ aspectLoader.registerPlugins([envs.getEnvPlugin()]);
853
+
854
+ return aspectLoader;
855
+ }
856
+ }
857
+
858
+ AspectLoaderAspect.addRuntime(AspectLoaderMain);
859
+
860
+ export default AspectLoaderMain;