@teambit/workspace 1.0.108 → 1.0.109

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/workspace.ts DELETED
@@ -1,2014 +0,0 @@
1
- /* eslint-disable max-lines */
2
- import memoize from 'memoizee';
3
- import mapSeries from 'p-map-series';
4
- import { Graph, Node, Edge } from '@teambit/graph.cleargraph';
5
- import type { PubsubMain } from '@teambit/pubsub';
6
- import { IssuesList } from '@teambit/component-issues';
7
- import type { AspectLoaderMain, AspectDefinition } from '@teambit/aspect-loader';
8
- import DependencyGraph from '@teambit/legacy/dist/scope/graph/scope-graph';
9
- import { generateNodeModulesPattern, PatternTarget } from '@teambit/dependencies.modules.packages-excluder';
10
- import {
11
- AspectEntry,
12
- ComponentMain,
13
- Component,
14
- ComponentFactory,
15
- AspectList,
16
- InvalidComponent,
17
- ResolveAspectsOptions,
18
- } from '@teambit/component';
19
- import { BitError } from '@teambit/bit-error';
20
- import { REMOVE_EXTENSION_SPECIAL_SIGN } from '@teambit/legacy/dist/consumer/config';
21
- import { ComponentScopeDirMap, ConfigMain } from '@teambit/config';
22
- import { DependencyResolverMain, DependencyResolverAspect, VariantPolicy } from '@teambit/dependency-resolver';
23
- import { EnvsMain, EnvsAspect } from '@teambit/envs';
24
- import { GraphqlMain } from '@teambit/graphql';
25
- import { Harmony } from '@teambit/harmony';
26
- import { Logger } from '@teambit/logger';
27
- import type { ScopeMain } from '@teambit/scope';
28
- import { isMatchNamespacePatternItem } from '@teambit/workspace.modules.match-pattern';
29
- import type { VariantsMain } from '@teambit/variants';
30
- import { ComponentID, ComponentIdList } from '@teambit/component-id';
31
- import { InvalidScopeName, InvalidScopeNameFromRemote, isValidScopeName, BitId } from '@teambit/legacy-bit-id';
32
- import { LaneId } from '@teambit/lane-id';
33
- import { Consumer, loadConsumer } from '@teambit/legacy/dist/consumer';
34
- import { GetBitMapComponentOptions } from '@teambit/legacy/dist/consumer/bit-map/bit-map';
35
- import { getMaxSizeForComponents, InMemoryCache } from '@teambit/legacy/dist/cache/in-memory-cache';
36
- import { createInMemoryCache } from '@teambit/legacy/dist/cache/cache-factory';
37
- import ComponentsList from '@teambit/legacy/dist/consumer/component/components-list';
38
- import { NoComponentDir } from '@teambit/legacy/dist/consumer/component/exceptions/no-component-dir';
39
- import { ExtensionDataList, ExtensionDataEntry } from '@teambit/legacy/dist/consumer/config/extension-data';
40
- import { pathIsInside } from '@teambit/legacy/dist/utils';
41
- import {
42
- PathOsBased,
43
- PathOsBasedRelative,
44
- PathOsBasedAbsolute,
45
- pathNormalizeToLinux,
46
- } from '@teambit/legacy/dist/utils/path';
47
- import fs from 'fs-extra';
48
- import { CompIdGraph, DepEdgeType } from '@teambit/graph';
49
- import { slice, isEmpty, merge, compact, uniqBy } from 'lodash';
50
- import { MergeConfigFilename, CFG_DEFAULT_RESOLVE_ENVS_FROM_ROOTS } from '@teambit/legacy/dist/constants';
51
- import path from 'path';
52
- import ConsumerComponent from '@teambit/legacy/dist/consumer/component';
53
- import { WatchOptions } from '@teambit/watcher';
54
- import type { ComponentLog } from '@teambit/legacy/dist/scope/models/model-component';
55
- import { SourceFile } from '@teambit/legacy/dist/consumer/component/sources';
56
- import ScopeComponentsImporter from '@teambit/legacy/dist/scope/component-ops/scope-components-importer';
57
- import { MissingBitMapComponent } from '@teambit/legacy/dist/consumer/bit-map/exceptions';
58
- import loader from '@teambit/legacy/dist/cli/loader';
59
- import { Lane, Version } from '@teambit/legacy/dist/scope/models';
60
- import { LaneNotFound } from '@teambit/legacy/dist/api/scope/lib/exceptions/lane-not-found';
61
- import { ScopeNotFoundOrDenied } from '@teambit/legacy/dist/remotes/exceptions/scope-not-found-or-denied';
62
- import { isHash } from '@teambit/component-version';
63
- import { GlobalConfigMain } from '@teambit/global-config';
64
- import { ComponentConfigFile } from './component-config-file';
65
- import {
66
- OnComponentAdd,
67
- OnComponentChange,
68
- OnComponentEventResult,
69
- OnComponentLoad,
70
- OnComponentRemove,
71
- SerializableResults,
72
- } from './on-component-events';
73
- import { WorkspaceExtConfig } from './types';
74
- import { ComponentStatus } from './workspace-component/component-status';
75
- import {
76
- OnAspectsResolve,
77
- OnAspectsResolveSlot,
78
- OnBitmapChange,
79
- OnBitmapChangeSlot,
80
- OnComponentAddSlot,
81
- OnComponentChangeSlot,
82
- OnComponentLoadSlot,
83
- OnComponentRemoveSlot,
84
- OnRootAspectAdded,
85
- OnRootAspectAddedSlot,
86
- } from './workspace.provider';
87
- import { ComponentLoadOptions, WorkspaceComponentLoader } from './workspace-component/workspace-component-loader';
88
- import { GraphFromFsBuilder, ShouldLoadFunc } from './build-graph-from-fs';
89
- import { BitMap } from './bit-map';
90
- import type { MergeOptions as BitmapMergeOptions } from './bit-map';
91
- import { WorkspaceAspect } from './workspace.aspect';
92
- import { GraphIdsFromFsBuilder } from './build-graph-ids-from-fs';
93
- import { AspectsMerger } from './aspects-merger';
94
- import {
95
- AspectPackage,
96
- GetConfiguredUserAspectsPackagesOptions,
97
- WorkspaceAspectsLoader,
98
- WorkspaceLoadAspectsOptions,
99
- } from './workspace-aspects-loader';
100
- import { MergeConflictFile } from './merge-conflict-file';
101
- import { MergeConfigConflict } from './exceptions/merge-config-conflict';
102
- import { CompFiles } from './workspace-component/comp-files';
103
- import { Filter } from './filter';
104
-
105
- export type EjectConfResult = {
106
- configPath: string;
107
- };
108
-
109
- export type ClearCacheOptions = {
110
- skipClearFailedToLoadEnvs?: boolean;
111
- };
112
-
113
- export const AspectSpecificField = '__specific';
114
- export const ComponentAdded = 'componentAdded';
115
- export const ComponentChanged = 'componentChanged';
116
- export const ComponentRemoved = 'componentRemoved';
117
-
118
- export interface EjectConfOptions {
119
- propagate?: boolean;
120
- override?: boolean;
121
- }
122
-
123
- export type ComponentExtensionsOpts = {
124
- loadExtensions?: boolean;
125
- };
126
-
127
- export type ExtensionsOrigin =
128
- | 'BitmapFile'
129
- | 'ModelSpecific'
130
- | 'ModelNonSpecific'
131
- | 'ConfigMerge'
132
- | 'WorkspaceVariants'
133
- | 'ComponentJsonFile'
134
- | 'FinalAfterMerge';
135
-
136
- const DEFAULT_VENDOR_DIR = 'vendor';
137
-
138
- /**
139
- * API of the Bit Workspace
140
- */
141
- export class Workspace implements ComponentFactory {
142
- private warnedAboutMisconfiguredEnvs: string[] = []; // cache env-ids that have been errored about not having "env" type
143
- priority = true;
144
- owner?: string;
145
- componentsScopeDirsMap: ComponentScopeDirMap;
146
- componentLoader: WorkspaceComponentLoader;
147
- bitMap: BitMap;
148
- /**
149
- * Indicate that we are now running installation process
150
- * This is important to know to ignore missing modules across different places
151
- */
152
- inInstallContext = false;
153
- private _cachedListIds?: ComponentID[];
154
- private componentLoadedSelfAsAspects: InMemoryCache<boolean>; // cache loaded components
155
- private aspectsMerger: AspectsMerger;
156
- private componentDefaultScopeFromComponentDirAndNameWithoutConfigFileMemoized;
157
- /**
158
- * Components paths are calculated from the component package names of the workspace
159
- * They are used in webpack configuration to only track changes from these paths inside `node_modules`
160
- */
161
- private componentPathsRegExps: RegExp[] = [];
162
- localAspects: string[] = [];
163
- filter: Filter;
164
- constructor(
165
- /**
166
- * private pubsub.
167
- */
168
- private pubsub: PubsubMain,
169
-
170
- private config: WorkspaceExtConfig,
171
- /**
172
- * private access to the legacy consumer instance.
173
- */
174
- public consumer: Consumer,
175
-
176
- /**
177
- * access to the workspace `Scope` instance
178
- */
179
- readonly scope: ScopeMain,
180
-
181
- /**
182
- * access to the `ComponentProvider` instance
183
- */
184
- private componentAspect: ComponentMain,
185
-
186
- private dependencyResolver: DependencyResolverMain,
187
-
188
- readonly variants: VariantsMain,
189
-
190
- private aspectLoader: AspectLoaderMain,
191
-
192
- readonly logger: Logger,
193
-
194
- private componentList: ComponentsList = new ComponentsList(consumer),
195
-
196
- /**
197
- * private reference to the instance of Harmony.
198
- */
199
- private harmony: Harmony,
200
-
201
- /**
202
- * on component load slot.
203
- */
204
- public onComponentLoadSlot: OnComponentLoadSlot,
205
-
206
- /**
207
- * on component change slot.
208
- */
209
- private onComponentChangeSlot: OnComponentChangeSlot,
210
-
211
- readonly envs: EnvsMain,
212
-
213
- readonly globalConfig: GlobalConfigMain,
214
-
215
- /**
216
- * on component add slot.
217
- */
218
- private onComponentAddSlot: OnComponentAddSlot,
219
-
220
- private onComponentRemoveSlot: OnComponentRemoveSlot,
221
-
222
- private onAspectsResolveSlot: OnAspectsResolveSlot,
223
-
224
- private onRootAspectAddedSlot: OnRootAspectAddedSlot,
225
-
226
- private graphql: GraphqlMain,
227
-
228
- private onBitmapChangeSlot: OnBitmapChangeSlot
229
- ) {
230
- this.componentLoadedSelfAsAspects = createInMemoryCache({ maxSize: getMaxSizeForComponents() });
231
- this.componentLoader = new WorkspaceComponentLoader(this, logger, dependencyResolver, envs, aspectLoader);
232
- this.validateConfig();
233
- this.bitMap = new BitMap(this.consumer.bitMap, this.consumer);
234
- // memoize this method to improve performance.
235
- this.componentDefaultScopeFromComponentDirAndNameWithoutConfigFileMemoized = memoize(
236
- this.componentDefaultScopeFromComponentDirAndNameWithoutConfigFile.bind(this),
237
- {
238
- primitive: true,
239
- promise: true,
240
- maxAge: 60 * 1000, // 1 min
241
- }
242
- );
243
- this.aspectsMerger = new AspectsMerger(this, this.harmony);
244
- this.filter = new Filter(this);
245
- }
246
-
247
- private validateConfig() {
248
- if (this.consumer.isLegacy) return;
249
- if (isEmpty(this.config))
250
- throw new BitError(
251
- `fatal: workspace config is empty. probably one of bit files is missing. consider running "bit init"`
252
- );
253
- const defaultScope = this.config.defaultScope;
254
- if (!defaultScope) throw new BitError('defaultScope is missing');
255
- if (!isValidScopeName(defaultScope)) throw new InvalidScopeName(defaultScope);
256
- }
257
-
258
- /**
259
- * root path of the Workspace.
260
- */
261
- get path() {
262
- return this.consumer.getPath();
263
- }
264
-
265
- /** get the `node_modules` folder of this workspace */
266
- private get modulesPath() {
267
- return path.join(this.path, 'node_modules');
268
- }
269
-
270
- get isLegacy(): boolean {
271
- return this.consumer.isLegacy;
272
- }
273
-
274
- registerOnComponentLoad(loadFn: OnComponentLoad) {
275
- this.onComponentLoadSlot.register(loadFn);
276
- return this;
277
- }
278
-
279
- registerOnComponentChange(onComponentChangeFunc: OnComponentChange) {
280
- this.onComponentChangeSlot.register(onComponentChangeFunc);
281
- return this;
282
- }
283
-
284
- registerOnComponentAdd(onComponentAddFunc: OnComponentAdd) {
285
- this.onComponentAddSlot.register(onComponentAddFunc);
286
- return this;
287
- }
288
-
289
- registerOnComponentRemove(onComponentRemoveFunc: OnComponentRemove) {
290
- this.onComponentRemoveSlot.register(onComponentRemoveFunc);
291
- return this;
292
- }
293
-
294
- registerOnBitmapChange(OnBitmapChangeFunc: OnBitmapChange) {
295
- this.onBitmapChangeSlot.register(OnBitmapChangeFunc);
296
- return this;
297
- }
298
-
299
- registerOnAspectsResolve(onAspectsResolveFunc: OnAspectsResolve) {
300
- this.onAspectsResolveSlot.register(onAspectsResolveFunc);
301
- return this;
302
- }
303
-
304
- registerOnRootAspectAdded(onRootAspectAddedFunc: OnRootAspectAdded) {
305
- this.onRootAspectAddedSlot.register(onRootAspectAddedFunc);
306
- return this;
307
- }
308
-
309
- /**
310
- * name of the workspace as configured in either `workspace.json`.
311
- * defaults to workspace root directory name.
312
- */
313
- get name() {
314
- if (this.config.name) return this.config.name;
315
- const tokenizedPath = this.path.split('/');
316
- return tokenizedPath[tokenizedPath.length - 1];
317
- }
318
-
319
- get icon() {
320
- return this.config.icon;
321
- }
322
-
323
- async hasModifiedDependencies(component: Component) {
324
- const componentsList = new ComponentsList(this.consumer);
325
- const listAutoTagPendingComponents = await componentsList.listAutoTagPendingComponents();
326
- const isAutoTag = listAutoTagPendingComponents.find((consumerComponent) =>
327
- consumerComponent.id.isEqualWithoutVersion(component.id)
328
- );
329
- if (isAutoTag) return true;
330
- return false;
331
- }
332
-
333
- /**
334
- * get Component issues
335
- */
336
- getComponentIssues(component: Component): IssuesList | null {
337
- return component.state._consumer.issues || null;
338
- }
339
-
340
- /**
341
- * provides status of all components in the workspace.
342
- */
343
- async getComponentStatus(component: Component): Promise<ComponentStatus> {
344
- const status = await this.consumer.getComponentStatusById(component.id);
345
- const hasModifiedDependencies = await this.hasModifiedDependencies(component);
346
- return ComponentStatus.fromLegacy(status, hasModifiedDependencies, component.isOutdated());
347
- }
348
-
349
- /**
350
- * list all workspace components.
351
- */
352
- async list(filter?: { offset: number; limit: number }, loadOpts?: ComponentLoadOptions): Promise<Component[]> {
353
- const loadOptsWithDefaults: ComponentLoadOptions = Object.assign({ loadSeedersAsAspects: false }, loadOpts || {});
354
- const legacyIds = this.consumer.bitMap.getAllIdsAvailableOnLane();
355
- const ids = await this.resolveMultipleComponentIds(legacyIds);
356
- const idsToGet = filter && filter.limit ? slice(ids, filter.offset, filter.offset + filter.limit) : ids;
357
- return this.getMany(idsToGet, loadOptsWithDefaults);
358
- }
359
-
360
- async listWithInvalid(loadOpts?: ComponentLoadOptions) {
361
- const legacyIds = this.consumer.bitMap.getAllIdsAvailableOnLane();
362
- return this.componentLoader.getMany(legacyIds, loadOpts, false);
363
- }
364
-
365
- /**
366
- * list all invalid components.
367
- * (see the invalid criteria in ConsumerComponent.isComponentInvalidByErrorType())
368
- */
369
- async listInvalid(): Promise<InvalidComponent[]> {
370
- const legacyIds = this.consumer.bitMap.getAllIdsAvailableOnLane();
371
- const ids = await this.resolveMultipleComponentIds(legacyIds);
372
- return this.componentLoader.getInvalid(ids);
373
- }
374
-
375
- /**
376
- * get ids of all workspace components.
377
- */
378
- async listIds(): Promise<ComponentID[]> {
379
- if (this._cachedListIds && this.bitMap.hasChanged()) {
380
- delete this._cachedListIds;
381
- }
382
- if (!this._cachedListIds) {
383
- this._cachedListIds = await this.resolveMultipleComponentIds(this.consumer.bitmapIdsFromCurrentLane);
384
- }
385
- return this._cachedListIds;
386
- }
387
-
388
- listIdsIncludeRemoved(): ComponentIdList {
389
- return this.consumer.bitmapIdsFromCurrentLaneIncludeRemoved;
390
- }
391
-
392
- /**
393
- * Check if a specific id exist in the workspace
394
- * @param componentId
395
- */
396
- async hasId(componentId: ComponentID): Promise<boolean> {
397
- const ids = await this.listIds();
398
- const found = ids.find((id) => {
399
- return id.isEqual(componentId);
400
- });
401
- return !!found;
402
- }
403
-
404
- /**
405
- * given component-ids, return the ones that are part of the workspace
406
- */
407
- async filterIds(ids: ComponentID[]): Promise<ComponentID[]> {
408
- const workspaceIds = await this.listIds();
409
- return ids.filter((id) => workspaceIds.find((wsId) => wsId.isEqual(id, { ignoreVersion: !id.hasVersion() })));
410
- }
411
-
412
- /**
413
- * whether or not a workspace has a component with the given name
414
- */
415
- async hasName(name: string): Promise<boolean> {
416
- const ids = await this.listIds();
417
- return Boolean(ids.find((id) => id.fullName === name));
418
- }
419
-
420
- /**
421
- * Check if a specific id exist in the workspace or in the scope
422
- * @param componentId
423
- */
424
- async hasIdNested(componentId: ComponentID, includeCache = true): Promise<boolean> {
425
- const found = await this.hasId(componentId);
426
- if (found) return found;
427
- return this.scope.hasIdNested(componentId, includeCache);
428
- }
429
-
430
- /**
431
- * list all modified components in the workspace.
432
- */
433
- async modified(): Promise<Component[]> {
434
- const allComps = await this.list();
435
- const modifiedIncludeNulls = await mapSeries(allComps, async (component) => {
436
- const modified = await this.isModified(component);
437
- return modified ? component : null;
438
- });
439
- return compact(modifiedIncludeNulls);
440
- }
441
-
442
- /**
443
- * list all new components in the workspace.
444
- */
445
- async newComponents() {
446
- const componentIds = await this.newComponentIds();
447
- return this.getMany(componentIds);
448
- }
449
-
450
- async newComponentIds(): Promise<ComponentID[]> {
451
- const allIds = await this.listIds();
452
- return allIds.filter((id) => !id.hasVersion());
453
- }
454
-
455
- async locallyDeletedIds(): Promise<ComponentID[]> {
456
- const locallyDeleted = await this.componentList.listLocallySoftRemoved();
457
- return this.resolveMultipleComponentIds(locallyDeleted);
458
- }
459
-
460
- async duringMergeIds(): Promise<ComponentID[]> {
461
- const duringMerge = this.componentList.listDuringMergeStateComponents();
462
- return this.resolveMultipleComponentIds(duringMerge);
463
- }
464
-
465
- /**
466
- * @deprecated use `listIds()` instead.
467
- * get all workspace component-ids
468
- */
469
- getAllComponentIds(): Promise<ComponentID[]> {
470
- const bitIds = this.consumer.bitMap.getAllBitIds();
471
- return this.resolveMultipleComponentIds(bitIds);
472
- }
473
-
474
- async listTagPendingIds(): Promise<ComponentID[]> {
475
- const newComponents = await this.newComponentIds();
476
- const modifiedComponents = (await this.modified()).map((c) => c.id);
477
- const removedComponents = await this.locallyDeletedIds();
478
- const duringMergeIds = await this.duringMergeIds();
479
- const allIds = [...newComponents, ...modifiedComponents, ...removedComponents, ...duringMergeIds];
480
- const allIdsUniq = uniqBy(allIds, (id) => id.toString());
481
- return allIdsUniq;
482
- }
483
-
484
- /**
485
- * list all components that can be tagged. (e.g. when tagging/snapping with --unmodified).
486
- * which are all components in the workspace, include locally deleted components.
487
- */
488
- async listPotentialTagIds(): Promise<ComponentID[]> {
489
- const deletedIds = await this.locallyDeletedIds();
490
- const allIdsWithoutDeleted = await this.listIds();
491
- return [...deletedIds, ...allIdsWithoutDeleted];
492
- }
493
-
494
- async getNewAndModifiedIds(): Promise<ComponentID[]> {
495
- const ids = await this.listTagPendingIds();
496
- return ids;
497
- }
498
-
499
- async newAndModified(): Promise<Component[]> {
500
- const ids = await this.getNewAndModifiedIds();
501
- return this.getMany(ids);
502
- }
503
-
504
- async getLogs(id: ComponentID, shortHash = false, startsFrom?: string): Promise<ComponentLog[]> {
505
- return this.scope.getLogs(id, shortHash, startsFrom);
506
- }
507
-
508
- async getGraph(ids?: ComponentID[], shouldThrowOnMissingDep = true): Promise<Graph<Component, string>> {
509
- if (!ids || ids.length < 1) ids = await this.listIds();
510
-
511
- return this.buildOneGraphForComponents(ids, undefined, undefined, shouldThrowOnMissingDep);
512
- }
513
-
514
- async getGraphIds(ids?: ComponentID[], shouldThrowOnMissingDep = true): Promise<CompIdGraph> {
515
- if (!ids || ids.length < 1) ids = await this.listIds();
516
-
517
- const graphIdsFromFsBuilder = new GraphIdsFromFsBuilder(
518
- this,
519
- this.logger,
520
- this.dependencyResolver,
521
- shouldThrowOnMissingDep
522
- );
523
- return graphIdsFromFsBuilder.buildGraph(ids);
524
- }
525
-
526
- async getUnavailableOnMainComponents(): Promise<ComponentID[]> {
527
- const currentLaneId = this.consumer.getCurrentLaneId();
528
- if (!currentLaneId.isDefault()) return [];
529
- const allIds = this.consumer.bitMap.getAllBitIdsFromAllLanes();
530
- const availableIds = this.consumer.bitMap.getAllIdsAvailableOnLane();
531
- if (allIds.length === availableIds.length) return [];
532
- const unavailableIds = allIds.filter((id) => !availableIds.hasWithoutVersion(id));
533
- if (!unavailableIds.length) return [];
534
- const removedIds = this.consumer.bitMap.getRemoved();
535
- const compsWithHead: ComponentID[] = [];
536
- await Promise.all(
537
- unavailableIds.map(async (id) => {
538
- if (removedIds.has(id)) return; // we don't care about removed components
539
- const modelComp = await this.scope.legacyScope.getModelComponentIfExist(id);
540
- if (modelComp && modelComp.head) compsWithHead.push(id);
541
- })
542
- );
543
- return this.resolveMultipleComponentIds(compsWithHead);
544
- }
545
-
546
- async getSavedGraphOfComponentIfExist(component: Component) {
547
- let versionObj: Version;
548
- try {
549
- versionObj = await this.scope.legacyScope.getVersionInstance(component.id);
550
- } catch (err) {
551
- return null;
552
- }
553
-
554
- const flattenedEdges = await versionObj.getFlattenedEdges(this.scope.legacyScope.objects);
555
- if (!flattenedEdges.length && versionObj.flattenedDependencies.length) {
556
- // there are flattenedDependencies, so must be edges, if they're empty, it's because the component was tagged
557
- // with a version < ~0.0.901, so this flattenedEdges wasn't exist.
558
- return null;
559
- }
560
- const flattenedBitIdCompIdMap: { [bitIdStr: string]: ComponentID } = {};
561
- const getCurrentVersionAsTagIfPossible = (): string | undefined => {
562
- const currentVer = component.id.version;
563
- if (!currentVer) return undefined;
564
- const isCurrentVerAHash = isHash(currentVer);
565
- if (!isCurrentVerAHash) return currentVer;
566
- const tag = component.tags.byHash(currentVer)?.version.raw;
567
- return tag || currentVer;
568
- };
569
- const currentVersion = getCurrentVersionAsTagIfPossible();
570
-
571
- flattenedBitIdCompIdMap[component.id.changeVersion(currentVersion).toString()] = component.id;
572
- await Promise.all(
573
- versionObj.flattenedDependencies.map(async (bitId) => {
574
- flattenedBitIdCompIdMap[bitId.toString()] = await this.resolveComponentId(bitId);
575
- })
576
- );
577
- const getCompIdByIdStr = (idStr: string): ComponentID => {
578
- const compId = flattenedBitIdCompIdMap[idStr];
579
- if (!compId) {
580
- const suggestWrongSnap = isHash(component.id.version)
581
- ? `\nplease check that .bitmap has the correct versions of ${component.id.toStringWithoutVersion()}.
582
- it's possible that the version ${component.id.version} belong to ${idStr.split('@')[0]}`
583
- : '';
584
- throw new Error(
585
- `id ${idStr} exists in flattenedEdges but not in flattened of ${component.id.toString()}.${suggestWrongSnap}`
586
- );
587
- }
588
- return compId;
589
- };
590
- const nodes = Object.values(flattenedBitIdCompIdMap);
591
- const edges = flattenedEdges.map((edge) => ({
592
- ...edge,
593
- source: getCompIdByIdStr(edge.source.toString()),
594
- target: getCompIdByIdStr(edge.target.toString()),
595
- }));
596
-
597
- const graph = new Graph<ComponentID, DepEdgeType>();
598
- nodes.forEach((node) => graph.setNode(new Node(node.toString(), node)));
599
- edges.forEach((edge) => graph.setEdge(new Edge(edge.source.toString(), edge.target.toString(), edge.type)));
600
- return graph;
601
- }
602
-
603
- /**
604
- * given component ids, find their dependents in the workspace
605
- */
606
- async getDependentsIds(ids: ComponentID[]): Promise<ComponentID[]> {
607
- const workspaceGraph = await DependencyGraph.buildGraphFromWorkspace(this.consumer, true);
608
- const workspaceDependencyGraph = new DependencyGraph(workspaceGraph);
609
- const workspaceDependents = ids.map((id) => workspaceDependencyGraph.getDependentsInfo(id));
610
- const dependentsLegacyIds = workspaceDependents.flat().map((_) => _.id);
611
- const dependentsLegacyNoDup = ComponentIdList.uniqFromArray(dependentsLegacyIds);
612
- const dependentsIds = await this.resolveMultipleComponentIds(dependentsLegacyNoDup);
613
- return dependentsIds;
614
- }
615
-
616
- public async createAspectList(extensionDataList: ExtensionDataList) {
617
- const entiresP = extensionDataList.map((entry) => this.extensionDataEntryToAspectEntry(entry));
618
- const entries: AspectEntry[] = await Promise.all(entiresP);
619
- return this.componentAspect.createAspectListFromEntries(entries);
620
- }
621
-
622
- private async extensionDataEntryToAspectEntry(dataEntry: ExtensionDataEntry): Promise<AspectEntry> {
623
- return new AspectEntry(await this.resolveComponentId(dataEntry.id), dataEntry);
624
- }
625
-
626
- /**
627
- * this is not the complete legacy component (ConsumerComponent), it's missing dependencies and hooks from Harmony
628
- * are skipped. do not trust the data you get from this method unless you know what you're doing.
629
- */
630
- async getLegacyMinimal(id: ComponentID): Promise<ConsumerComponent | undefined> {
631
- try {
632
- const componentMap = this.consumer.bitMap.getComponent(id);
633
- return await ConsumerComponent.loadFromFileSystem({
634
- componentMap,
635
- id,
636
- consumer: this.consumer,
637
- });
638
- } catch (err) {
639
- return undefined;
640
- }
641
- }
642
-
643
- async getFilesModification(id: ComponentID): Promise<CompFiles> {
644
- const bitMapEntry = this.bitMap.getBitmapEntry(id, { ignoreVersion: true });
645
- const compDir = bitMapEntry.getComponentDir();
646
- const compDirAbs = path.join(this.path, compDir);
647
- const sourceFilesVinyls = bitMapEntry.files.map((file) => {
648
- const filePath = path.join(compDirAbs, file.relativePath);
649
- return SourceFile.load(filePath, compDirAbs, this.path, {});
650
- });
651
- const repo = this.scope.legacyScope.objects;
652
- const getHeadFiles = async () => {
653
- const modelComp = await this.scope.legacyScope.getModelComponentIfExist(id);
654
- if (!modelComp) return [];
655
- const head = modelComp.getHeadRegardlessOfLane();
656
- if (!head) return [];
657
-
658
- const verObj = await modelComp.loadVersion(head.toString(), repo);
659
- return verObj.files;
660
- };
661
-
662
- return new CompFiles(id, repo, sourceFilesVinyls, compDir, await getHeadFiles());
663
- }
664
-
665
- /**
666
- * get a component from workspace
667
- * @param id component ID
668
- */
669
- async get(
670
- componentId: ComponentID,
671
- legacyComponent?: ConsumerComponent,
672
- useCache = true,
673
- storeInCache = true,
674
- loadOpts?: ComponentLoadOptions
675
- ): Promise<Component> {
676
- this.logger.debug(`get ${componentId.toString()}`);
677
- const component = await this.componentLoader.get(componentId, legacyComponent, useCache, storeInCache, loadOpts);
678
- // When loading a component if it's an env make sure to load it as aspect as well
679
- // We only want to try load it as aspect if it's the first time we load the component
680
- const tryLoadAsAspect = this.componentLoadedSelfAsAspects.get(component.id.toString()) === undefined;
681
- // const config = this.harmony.get<ConfigMain>('teambit.harmony/config');
682
-
683
- // We are loading the component as aspect if it's an env, in order to be able to run the env-preview-template task which run only on envs.
684
- // Without this loading we will have a problem in case the env is the only component in the workspace. in that case we will load it as component
685
- // then we don't run it's provider so it doesn't register to the env slot, so we don't know it's an env.
686
- if (
687
- tryLoadAsAspect &&
688
- this.envs.isUsingEnvEnv(component) &&
689
- !this.aspectLoader.isCoreAspect(component.id.toStringWithoutVersion()) &&
690
- !this.aspectLoader.isAspectLoaded(component.id.toString()) &&
691
- (await this.hasId(component.id))
692
- // !config.extension(component.id.toStringWithoutVersion(), true)
693
- ) {
694
- try {
695
- this.componentLoadedSelfAsAspects.set(component.id.toString(), true);
696
- this.logger.debug(`trying to load self as aspect with id ${component.id.toString()}`);
697
- // ignore missing modules when loading self
698
- await this.loadAspects([component.id.toString()], undefined, component.id.toString(), {
699
- hideMissingModuleError: true,
700
- });
701
- // In most cases if the load self as aspect failed we don't care about it.
702
- // we only need it in specific cases to work, but this workspace.get runs on different
703
- // cases where it might fail (like when importing aspect, after the import objects
704
- // when we write the package.json we run the applyTransformers which get to pkg which call
705
- // host.get, but the component not written yet to the fs, so it fails.)
706
- } catch (e) {
707
- this.logger.debug(`fail to load self as aspect with id ${component.id.toString()}`);
708
- this.componentLoadedSelfAsAspects.delete(component.id.toString());
709
- return component;
710
- }
711
- }
712
- this.componentLoadedSelfAsAspects.set(component.id.toString(), false);
713
-
714
- return component;
715
- }
716
-
717
- async getConfiguredUserAspectsPackages(options: GetConfiguredUserAspectsPackagesOptions): Promise<AspectPackage[]> {
718
- const workspaceAspectsLoader = this.getWorkspaceAspectsLoader();
719
- return workspaceAspectsLoader.getConfiguredUserAspectsPackages(options);
720
- }
721
-
722
- async clearCache(options: ClearCacheOptions = {}) {
723
- this.aspectLoader.resetFailedLoadAspects();
724
- if (!options.skipClearFailedToLoadEnvs) this.envs.resetFailedToLoadEnvs();
725
- this.logger.debug('clearing the workspace and scope caches');
726
- delete this._cachedListIds;
727
- this.componentLoader.clearCache();
728
- await this.scope.clearCache();
729
- this.componentList = new ComponentsList(this.consumer);
730
- this.componentDefaultScopeFromComponentDirAndNameWithoutConfigFileMemoized.clear();
731
- }
732
-
733
- clearAllComponentsCache() {
734
- this.componentLoader.clearCache();
735
- this.consumer.componentLoader.clearComponentsCache();
736
- this.componentList = new ComponentsList(this.consumer);
737
- }
738
-
739
- clearComponentCache(id: ComponentID) {
740
- this.componentLoader.clearComponentCache(id);
741
- this.consumer.clearOneComponentCache(id);
742
- this.componentList = new ComponentsList(this.consumer);
743
- }
744
-
745
- async warmCache() {
746
- await this.list();
747
- }
748
-
749
- async triggerOnComponentChange(
750
- id: ComponentID,
751
- files: PathOsBasedAbsolute[],
752
- removedFiles: PathOsBasedAbsolute[],
753
- watchOpts: WatchOptions
754
- ): Promise<OnComponentEventResult[]> {
755
- const component = await this.get(id);
756
- const onChangeEntries = this.onComponentChangeSlot.toArray(); // e.g. [ [ 'teambit.bit/compiler', [Function: bound onComponentChange] ] ]
757
- const results: Array<{ extensionId: string; results: SerializableResults }> = [];
758
- await mapSeries(onChangeEntries, async ([extension, onChangeFunc]) => {
759
- const onChangeResult = await onChangeFunc(component, files, removedFiles, watchOpts);
760
- if (onChangeResult) results.push({ extensionId: extension, results: onChangeResult });
761
- });
762
-
763
- // TODO: find way to standardize event names.
764
- await this.graphql.pubsub.publish(ComponentChanged, { componentChanged: { component } });
765
- return results;
766
- }
767
-
768
- async triggerOnComponentAdd(id: ComponentID, watchOpts: WatchOptions): Promise<OnComponentEventResult[]> {
769
- const component = await this.get(id);
770
- const onAddEntries = this.onComponentAddSlot.toArray(); // e.g. [ [ 'teambit.bit/compiler', [Function: bound onComponentChange] ] ]
771
- const results: Array<{ extensionId: string; results: SerializableResults }> = [];
772
- const files = component.state.filesystem.files.map((file) => file.path);
773
- await mapSeries(onAddEntries, async ([extension, onAddFunc]) => {
774
- const onAddResult = await onAddFunc(component, files, watchOpts);
775
- if (onAddResult) results.push({ extensionId: extension, results: onAddResult });
776
- });
777
-
778
- await this.graphql.pubsub.publish(ComponentAdded, { componentAdded: { component } });
779
- return results;
780
- }
781
-
782
- async triggerOnComponentRemove(id: ComponentID): Promise<OnComponentEventResult[]> {
783
- const onRemoveEntries = this.onComponentRemoveSlot.toArray(); // e.g. [ [ 'teambit.bit/compiler', [Function: bound onComponentChange] ] ]
784
- const results: Array<{ extensionId: string; results: SerializableResults }> = [];
785
- await mapSeries(onRemoveEntries, async ([extension, onRemoveFunc]) => {
786
- const onRemoveResult = await onRemoveFunc(id);
787
- results.push({ extensionId: extension, results: onRemoveResult });
788
- });
789
-
790
- await this.graphql.pubsub.publish(ComponentRemoved, { componentRemoved: { componentIds: [id.toObject()] } });
791
- return results;
792
- }
793
-
794
- async triggerOnBitmapChange(): Promise<void> {
795
- const onBitmapChangeEntries = this.onBitmapChangeSlot.toArray(); // e.g. [ [ 'teambit.bit/compiler', [Function: bound onComponentChange] ] ]
796
- await mapSeries(onBitmapChangeEntries, async ([, onBitmapChangeFunc]) => {
797
- await onBitmapChangeFunc();
798
- });
799
- }
800
-
801
- /**
802
- * if needed, add a slot to let other aspects react to this event.
803
- * currently, the purpose is to reload the workspace config when it changes, so entries like "defaultScope" are updated.
804
- * it also updates the DependencyResolver config. I couldn't find a good way to update all aspects in workspace.jsonc.
805
- */
806
- async triggerOnWorkspaceConfigChange(): Promise<void> {
807
- this.logger.debug('triggerOnWorkspaceConfigChange, reloading workspace config');
808
- const config = this.harmony.get<ConfigMain>('teambit.harmony/config');
809
- await config.reloadWorkspaceConfig();
810
- const workspaceConfig = config.workspaceConfig;
811
- if (!workspaceConfig) throw new Error('workspace config is missing from Config aspect');
812
- const configOfWorkspaceAspect = workspaceConfig.extensions.findExtension(WorkspaceAspect.id);
813
- if (!configOfWorkspaceAspect) throw new Error('workspace extension is missing from workspace config');
814
- this.config = configOfWorkspaceAspect.config as WorkspaceExtConfig;
815
- const configOfDepResolverAspect = workspaceConfig.extensions.findExtension(DependencyResolverAspect.id);
816
- if (configOfDepResolverAspect) this.dependencyResolver.setConfig(configOfDepResolverAspect.config as any);
817
- this.dependencyResolver.clearCache();
818
- }
819
-
820
- getState(id: ComponentID, hash: string) {
821
- return this.scope.getState(id, hash);
822
- }
823
-
824
- getSnap(id: ComponentID, hash: string) {
825
- return this.scope.getSnap(id, hash);
826
- }
827
-
828
- getCurrentLaneId(): LaneId {
829
- return this.consumer.getCurrentLaneId();
830
- }
831
-
832
- async getCurrentLaneObject(): Promise<Lane | null> {
833
- return this.consumer.getCurrentLaneObject();
834
- }
835
-
836
- isOnMain(): boolean {
837
- return this.consumer.isOnMain();
838
- }
839
-
840
- isOnLane(): boolean {
841
- return this.consumer.isOnLane();
842
- }
843
-
844
- /**
845
- * if checked out to a lane and the lane exists in the remote,
846
- * return the remote lane. otherwise, return null.
847
- */
848
- async getCurrentRemoteLane(): Promise<Lane | null> {
849
- const currentLaneId = this.getCurrentLaneId();
850
- if (currentLaneId.isDefault()) {
851
- return null;
852
- }
853
- const scopeComponentImporter = ScopeComponentsImporter.getInstance(this.consumer.scope);
854
- try {
855
- const lanes = await scopeComponentImporter.importLanes([currentLaneId]);
856
-
857
- return lanes[0];
858
- } catch (err: any) {
859
- if (
860
- err instanceof InvalidScopeName ||
861
- err instanceof ScopeNotFoundOrDenied ||
862
- err instanceof LaneNotFound ||
863
- err instanceof InvalidScopeNameFromRemote
864
- ) {
865
- const bitMapLaneId = this.bitMap.getExportedLaneId();
866
- if (bitMapLaneId?.isEqual(currentLaneId)) {
867
- throw err; // we know the lane is not new, so the error is legit
868
- }
869
- // the lane could be a local lane so no need to throw an error in such case
870
- loader.stop();
871
- this.logger.warn(`unable to get lane's data from a remote due to an error:\n${err.message}`);
872
- return null;
873
- }
874
- throw err;
875
- }
876
- }
877
-
878
- getDefaultExtensions(): ExtensionDataList {
879
- if (!this.config.extensions) {
880
- return new ExtensionDataList();
881
- }
882
- return ExtensionDataList.fromConfigObject(this.config.extensions);
883
- }
884
-
885
- async ejectMultipleConfigs(ids: ComponentID[], options: EjectConfOptions): Promise<EjectConfResult[]> {
886
- return Promise.all(ids.map((id) => this.ejectConfig(id, options)));
887
- }
888
-
889
- async ejectConfig(id: ComponentID, options: EjectConfOptions): Promise<EjectConfResult> {
890
- const componentId = await this.resolveComponentId(id);
891
- const extensions = await this.getExtensionsFromScopeAndSpecific(id);
892
- const aspects = await this.createAspectList(extensions);
893
- const componentDir = this.componentDir(id, { ignoreVersion: true });
894
- const componentConfigFile = new ComponentConfigFile(componentId, aspects, componentDir, options.propagate);
895
- await componentConfigFile.write({ override: options.override });
896
- // remove config from the .bitmap as it's not needed anymore. it is replaced by the component.json
897
- this.bitMap.removeEntireConfig(id);
898
- await this.bitMap.write(`eject-conf (${id.toString()})`);
899
- return {
900
- configPath: ComponentConfigFile.composePath(componentDir),
901
- };
902
- }
903
-
904
- async getExtensionsFromScopeAndSpecific(id: ComponentID): Promise<ExtensionDataList> {
905
- const componentFromScope = await this.scope.get(id);
906
- const { extensions } = await this.componentExtensions(id, componentFromScope, ['WorkspaceVariants']);
907
-
908
- return extensions;
909
- }
910
-
911
- /**
912
- * see component-aspect, createAspectListFromLegacy() method for a context why this is needed.
913
- */
914
- private async resolveScopeAspectListIds(aspectListFromScope: AspectList): Promise<AspectList> {
915
- const resolvedList = await aspectListFromScope.pmap(async (entry) => {
916
- if (entry.id.scope !== this.scope.name) {
917
- return entry;
918
- }
919
- const newId = await this.resolveComponentId(entry.id.fullName);
920
- const newEntry = new AspectEntry(newId, entry.legacy);
921
- return newEntry;
922
- });
923
- return resolvedList;
924
- }
925
-
926
- /**
927
- * @deprecated use `this.idsByPattern` instead for consistency. also, it supports negation and list of patterns.
928
- *
929
- * load components into the workspace through a variants pattern.
930
- * @param pattern variants.
931
- * @param scope scope name.
932
- */
933
- async byPattern(pattern: string, scope = '**'): Promise<Component[]> {
934
- const ids = await this.listIds();
935
- const finalPattern = `${scope}/${pattern || '**'}`;
936
- const targetIds = ids.filter((id) => {
937
- const spec = isMatchNamespacePatternItem(id.toStringWithoutVersion(), finalPattern);
938
- return spec.match;
939
- });
940
-
941
- const components = await this.getMany(targetIds);
942
- return components;
943
- }
944
-
945
- hasPattern(strArr: string[]) {
946
- return strArr.some((str) => this.isPattern(str));
947
- }
948
-
949
- isPattern(str: string) {
950
- const specialSyntax = ['*', ',', '!', '$', ':'];
951
- return specialSyntax.some((char) => str.includes(char));
952
- }
953
-
954
- /**
955
- * get component-ids matching the given pattern. a pattern can have multiple patterns separated by a comma.
956
- * it supports negate (!) character to exclude ids.
957
- */
958
- async idsByPattern(
959
- pattern: string,
960
- throwForNoMatch = true,
961
- opts: { includeDeleted?: boolean } = {}
962
- ): Promise<ComponentID[]> {
963
- const isId = !this.isPattern(pattern);
964
- if (isId) {
965
- // if it's not a pattern but just id, resolve it without multimatch to support specifying id without scope-name
966
- const id = await this.resolveComponentId(pattern);
967
- if (this.exists(id, { includeDeleted: opts.includeDeleted })) return [id];
968
- if (throwForNoMatch) throw new MissingBitMapComponent(pattern);
969
- return [];
970
- }
971
- const ids = opts.includeDeleted ? this.listIdsIncludeRemoved() : await this.listIds();
972
- return this.filterIdsFromPoolIdsByPattern(pattern, ids, throwForNoMatch);
973
- }
974
-
975
- async filterIdsFromPoolIdsByPattern(pattern: string, ids: ComponentID[], throwForNoMatch = true) {
976
- return this.scope.filterIdsFromPoolIdsByPattern(pattern, ids, throwForNoMatch, this.filter.by.bind(this.filter));
977
- }
978
-
979
- /**
980
- * useful for workspace commands, such as `bit build`, `bit compile`.
981
- * by default, it should be running on new and modified components.
982
- * a user can specify `--all` to run on all components or specify a pattern to limit to specific components.
983
- * some commands such as build/test needs to run also on the dependents.
984
- */
985
- async getComponentsByUserInput(all?: boolean, pattern?: string, includeDependents = false): Promise<Component[]> {
986
- if (all) {
987
- return this.list();
988
- }
989
- if (pattern) {
990
- const ids = await this.idsByPattern(pattern);
991
- return this.getMany(ids);
992
- }
993
- const newAndModified = await this.newAndModified();
994
- if (includeDependents) {
995
- const newAndModifiedIds = newAndModified.map((comp) => comp.id);
996
- const dependentsIds = await this.getDependentsIds(newAndModifiedIds);
997
- const dependentsIdsFiltered = dependentsIds.filter((id) => !newAndModified.find((_) => _.id.isEqual(id)));
998
- const dependents = await this.getMany(dependentsIdsFiltered);
999
- newAndModified.push(...dependents);
1000
- }
1001
- return newAndModified;
1002
- }
1003
-
1004
- async getComponentsUsingEnv(env: string, ignoreVersion = true, throwIfNotFound = false): Promise<Component[]> {
1005
- const allComps = await this.list();
1006
- const allEnvs = await this.envs.createEnvironment(allComps);
1007
- const foundEnv = allEnvs.runtimeEnvs.find((runtimeEnv) => {
1008
- if (runtimeEnv.id === env) return true;
1009
- if (!ignoreVersion) return false;
1010
- const envWithoutVersion = runtimeEnv.id.split('@')[0];
1011
- return env === envWithoutVersion;
1012
- });
1013
- if (!foundEnv && throwIfNotFound) {
1014
- const availableEnvs = allEnvs.runtimeEnvs.map((runtimeEnv) => runtimeEnv.id);
1015
- throw new BitError(`unable to find components that using "${env}" env.
1016
- the following envs are used in this workspace: ${availableEnvs.join(', ')}`);
1017
- }
1018
- return foundEnv?.components || [];
1019
- }
1020
-
1021
- async getMany(ids: Array<ComponentID>, loadOpts?: ComponentLoadOptions): Promise<Component[]> {
1022
- const { components } = await this.componentLoader.getMany(ids, loadOpts);
1023
- return components;
1024
- }
1025
-
1026
- getManyByLegacy(components: ConsumerComponent[], loadOpts?: ComponentLoadOptions): Promise<Component[]> {
1027
- return mapSeries(components, async (component) => {
1028
- const id = await this.resolveComponentId(component.id);
1029
- return this.get(id, component, true, true, loadOpts);
1030
- });
1031
- }
1032
-
1033
- /**
1034
- * don't throw an error if the component was not found, simply return undefined.
1035
- */
1036
- async getIfExist(componentId: ComponentID): Promise<Component | undefined> {
1037
- return this.componentLoader.getIfExist(componentId);
1038
- }
1039
-
1040
- /**
1041
- * whether a component exists in the workspace
1042
- */
1043
- exists(componentId: ComponentID, opts: { includeDeleted?: boolean } = {}): boolean {
1044
- const allIds = opts.includeDeleted ? this.listIdsIncludeRemoved() : this.consumer.bitmapIdsFromCurrentLane;
1045
- return allIds.hasWithoutVersion(componentId);
1046
- }
1047
-
1048
- getIdIfExist(componentId: ComponentID): ComponentID | undefined {
1049
- const id = this.consumer.bitmapIdsFromCurrentLane.find((_) => _.isEqualWithoutVersion(componentId));
1050
- if (!id) return undefined;
1051
- return componentId.changeVersion(id.version);
1052
- }
1053
-
1054
- mergeBitmaps(bitmapContent: string, otherBitmapContent: string, opts: BitmapMergeOptions = {}): string {
1055
- return this.bitMap.mergeBitmaps(bitmapContent, otherBitmapContent, opts);
1056
- }
1057
-
1058
- /**
1059
- * This will make sure to fetch the objects prior to load them
1060
- * do not use it if you are not sure you need it.
1061
- * It will influence the performance
1062
- * currently it used only for get many of aspects
1063
- * @param ids
1064
- */
1065
- async importAndGetMany(
1066
- ids: Array<ComponentID>,
1067
- reason?: string,
1068
- loadOpts?: ComponentLoadOptions
1069
- ): Promise<Component[]> {
1070
- if (!ids.length) return [];
1071
- const lane = await this.importCurrentLaneIfMissing();
1072
- await this.scope.import(ids, {
1073
- reFetchUnBuiltVersion: shouldReFetchUnBuiltVersion(),
1074
- preferDependencyGraph: true,
1075
- // add the lane object although it was imported with all its ids previously.
1076
- // in some cases, this import re-fetch existing ids whose their VersionHistory is incomplete, so it needs the Lane context.
1077
- lane,
1078
- reason,
1079
- });
1080
- return this.getMany(ids, loadOpts);
1081
- }
1082
-
1083
- async importCurrentLaneIfMissing(): Promise<Lane | undefined> {
1084
- const laneId = this.getCurrentLaneId();
1085
- const laneObj = await this.scope.legacyScope.getCurrentLaneObject();
1086
- if (laneId.isDefault() || laneObj) {
1087
- return laneObj || undefined;
1088
- }
1089
- const lane = await this.getCurrentRemoteLane();
1090
- if (!lane) {
1091
- return undefined;
1092
- }
1093
- this.logger.info(`current lane ${laneId.toString()} is missing, importing it`);
1094
- await this.scope.legacyScope.objects.writeObjectsToTheFS([lane]);
1095
- const scopeComponentsImporter = ScopeComponentsImporter.getInstance(this.scope.legacyScope);
1096
- const ids = ComponentIdList.fromArray(this.getExportedFrom(lane.toBitIds()));
1097
- await scopeComponentsImporter.importWithoutDeps(ids.toVersionLatest(), {
1098
- cache: false,
1099
- lane,
1100
- includeVersionHistory: true,
1101
- reason: 'latest of the current lane',
1102
- });
1103
-
1104
- await scopeComponentsImporter.importMany({ ids, lane, reason: 'for making sure the current lane has all ' });
1105
- return lane;
1106
- }
1107
-
1108
- async use(aspectIdStr: string): Promise<string> {
1109
- const workspaceAspectsLoader = this.getWorkspaceAspectsLoader();
1110
- return workspaceAspectsLoader.use(aspectIdStr);
1111
- }
1112
-
1113
- async write(component: Component, rootPath?: string) {
1114
- await Promise.all(
1115
- component.filesystem.files.map(async (file) => {
1116
- const pathToWrite = rootPath ? path.join(this.path, rootPath, file.relative) : file.path;
1117
- await fs.outputFile(pathToWrite, file.contents);
1118
- })
1119
- );
1120
- }
1121
-
1122
- /**
1123
- * @todo: the return path here is Linux when asking for relative and os-based when asking for absolute. fix this to be consistent.
1124
- *
1125
- * Get the component root dir in the file system (relative to workspace or full)
1126
- * @param componentId
1127
- * @param relative return the path relative to the workspace or full path
1128
- */
1129
- componentDir(
1130
- componentId: ComponentID,
1131
- bitMapOptions?: GetBitMapComponentOptions,
1132
- options = { relative: false }
1133
- ): PathOsBased {
1134
- return this.componentDirFromLegacyId(componentId, bitMapOptions, options);
1135
- }
1136
-
1137
- /**
1138
- * component's files in the workspace are symlinked to the node_modules, and a package.json file is generated on that
1139
- * package directory to simulate a valid node package.
1140
- * @returns the package directory inside the node_module.
1141
- * by default the absolute path, unless `options.relative` was set
1142
- */
1143
- componentPackageDir(component: Component, options = { relative: false }): string {
1144
- const packageName = this.componentPackageName(component);
1145
- const packageDir = path.join('node_modules', packageName);
1146
- return options.relative ? packageDir : this.consumer.toAbsolutePath(packageDir);
1147
- }
1148
-
1149
- componentPackageName(component: Component): string {
1150
- return this.dependencyResolver.getPackageName(component);
1151
- }
1152
-
1153
- private componentDirFromLegacyId(
1154
- bitId: ComponentID,
1155
- bitMapOptions?: GetBitMapComponentOptions,
1156
- options = { relative: false }
1157
- ): PathOsBased {
1158
- const componentMap = this.consumer.bitMap.getComponent(bitId, bitMapOptions);
1159
- const relativeComponentDir = componentMap.getComponentDir();
1160
- if (!relativeComponentDir) {
1161
- throw new NoComponentDir(bitId.toString());
1162
- }
1163
- if (options.relative) {
1164
- return relativeComponentDir;
1165
- }
1166
-
1167
- return path.join(this.path, relativeComponentDir);
1168
- }
1169
-
1170
- componentDirToAbsolute(relativeComponentDir: PathOsBasedRelative): PathOsBasedAbsolute {
1171
- return path.join(this.path, relativeComponentDir);
1172
- }
1173
-
1174
- async componentDefaultScope(componentId: ComponentID): Promise<string | undefined> {
1175
- const relativeComponentDir = this.componentDir(componentId, { ignoreVersion: true }, { relative: true });
1176
- return this.componentDefaultScopeFromComponentDirAndName(relativeComponentDir, componentId.fullName);
1177
- }
1178
-
1179
- async componentDefaultScopeFromComponentDirAndName(
1180
- relativeComponentDir: PathOsBasedRelative,
1181
- name: string
1182
- ): Promise<string | undefined> {
1183
- const componentConfigFile = await this.componentConfigFileFromComponentDirAndName(relativeComponentDir, name);
1184
- if (componentConfigFile && componentConfigFile.defaultScope) {
1185
- return componentConfigFile.defaultScope;
1186
- }
1187
- const bitMapId = this.consumer.bitMap.getExistingBitId(name, false);
1188
- const bitMapEntry = bitMapId ? this.consumer.bitMap.getComponent(bitMapId) : undefined;
1189
- if (bitMapEntry && bitMapEntry.defaultScope) {
1190
- return bitMapEntry.defaultScope;
1191
- }
1192
- return this.componentDefaultScopeFromComponentDirAndNameWithoutConfigFileMemoized(relativeComponentDir, name);
1193
- }
1194
-
1195
- get defaultScope() {
1196
- return this.config.defaultScope;
1197
- }
1198
-
1199
- private async componentDefaultScopeFromComponentDirAndNameWithoutConfigFile(
1200
- relativeComponentDir: PathOsBasedRelative,
1201
- name: string
1202
- ): Promise<string | undefined> {
1203
- const variantConfig = this.variants.byRootDirAndName(relativeComponentDir, name);
1204
- if (variantConfig && variantConfig.defaultScope) {
1205
- return variantConfig.defaultScope;
1206
- }
1207
- const isVendor = this.isVendorComponentByComponentDir(relativeComponentDir);
1208
- if (!isVendor) {
1209
- return this.config.defaultScope;
1210
- }
1211
- return undefined;
1212
- }
1213
-
1214
- /**
1215
- * Calculate the component config based on:
1216
- * the config property in the .bitmap file
1217
- * the component.json file in the component folder
1218
- * matching pattern in the variants config
1219
- * defaults extensions from workspace config
1220
- * extensions from the model.
1221
- */
1222
- async componentExtensions(
1223
- componentId: ComponentID,
1224
- componentFromScope?: Component,
1225
- excludeOrigins: ExtensionsOrigin[] = [],
1226
- opts: ComponentExtensionsOpts = {}
1227
- ): Promise<{
1228
- extensions: ExtensionDataList;
1229
- beforeMerge: Array<{ extensions: ExtensionDataList; origin: ExtensionsOrigin; extraData: any }>; // useful for debugging
1230
- errors?: Error[];
1231
- }> {
1232
- const optsWithDefaults: ComponentExtensionsOpts = Object.assign({ loadExtensions: true }, opts);
1233
- const mergeRes = await this.aspectsMerger.merge(componentId, componentFromScope, excludeOrigins);
1234
- if (optsWithDefaults.loadExtensions) {
1235
- await this.loadComponentsExtensions(mergeRes.extensions, componentId);
1236
- const envId = await this.envs.getEnvIdFromEnvsLegacyExtensions(mergeRes.extensions);
1237
- if (envId) {
1238
- await this.warnAboutMisconfiguredEnv(envId);
1239
- }
1240
- }
1241
- return mergeRes;
1242
- }
1243
-
1244
- async warnAboutMisconfiguredEnv(envId: string) {
1245
- if (!envId) return;
1246
- if (this.envs.getCoreEnvsIds().includes(envId)) return;
1247
- if (this.warnedAboutMisconfiguredEnvs.includes(envId)) return;
1248
- let env: Component;
1249
- try {
1250
- const parsedEnvId = await this.resolveComponentId(envId);
1251
- env = await this.get(parsedEnvId);
1252
- } catch (err) {
1253
- return; // unable to get the component for some reason. don't sweat it. forget about the warning
1254
- }
1255
- if (!this.envs.isUsingEnvEnv(env)) {
1256
- this.warnedAboutMisconfiguredEnvs.push(envId);
1257
- this.logger.consoleWarning(
1258
- `env "${envId}" is not of type env. (correct the env's type, or component config with "bit env set ${envId} teambit.envs/env")`
1259
- );
1260
- }
1261
- }
1262
-
1263
- getConfigMergeFilePath(): string {
1264
- return path.join(this.path, MergeConfigFilename);
1265
- }
1266
-
1267
- getConflictMergeFile(): MergeConflictFile {
1268
- return this.aspectsMerger.mergeConflictFile;
1269
- }
1270
-
1271
- getDepsDataOfMergeConfig(id: ComponentID): Record<string, any> | undefined {
1272
- return this.aspectsMerger.getDepsDataOfMergeConfig(id);
1273
- }
1274
-
1275
- getWorkspaceJsonConflictFromMergeConfig(): { data?: Record<string, any>; conflict: boolean } {
1276
- const configMergeFile = this.getConflictMergeFile();
1277
- let data: Record<string, any> | undefined;
1278
- let conflict = false;
1279
- try {
1280
- data = configMergeFile.getConflictParsed('WORKSPACE');
1281
- } catch (err) {
1282
- if (!(err instanceof MergeConfigConflict)) {
1283
- throw err;
1284
- }
1285
- conflict = true;
1286
- this.logger.error(`unable to parse the config file for the workspace due to conflicts`);
1287
- }
1288
- return { data, conflict };
1289
- }
1290
-
1291
- getWorkspaceIssues(): Error[] {
1292
- const errors: Error[] = [];
1293
- const configMergeFile = this.getConflictMergeFile();
1294
- try {
1295
- configMergeFile.getConflictParsed('WORKSPACE');
1296
- } catch (err) {
1297
- if (err instanceof MergeConfigConflict) {
1298
- errors.push(err);
1299
- }
1300
- }
1301
- return errors;
1302
- }
1303
-
1304
- async listComponentsDuringMerge(): Promise<ComponentID[]> {
1305
- const unmergedComps = this.scope.legacyScope.objects.unmergedComponents.getComponents();
1306
- const bitIds = unmergedComps.map((u) => ComponentID.fromObject(u.id));
1307
- return this.resolveMultipleComponentIds(bitIds);
1308
- }
1309
-
1310
- async getUnmergedComponent(componentId: ComponentID): Promise<Component | undefined> {
1311
- const unmerged = this.scope.legacyScope.objects.unmergedComponents.getEntry(componentId.fullName);
1312
- if (unmerged?.head) {
1313
- return this.scope.get(componentId.changeVersion(unmerged?.head.toString()));
1314
- }
1315
- return undefined;
1316
- }
1317
-
1318
- async isModified(component: Component): Promise<boolean> {
1319
- const head = component.head;
1320
- if (!head) {
1321
- return false; // it's a new component
1322
- }
1323
- const consumerComp = component.state._consumer as ConsumerComponent;
1324
- if (typeof consumerComp._isModified === 'boolean') return consumerComp._isModified;
1325
- const componentStatus = await this.consumer.getComponentStatusById(component.id);
1326
- return componentStatus.modified === true;
1327
- }
1328
-
1329
- async isModifiedOrNew(component: Component): Promise<boolean> {
1330
- const head = component.head;
1331
- if (!head) {
1332
- return true; // it's a new component
1333
- }
1334
- return this.isModified(component);
1335
- }
1336
-
1337
- isExported(id: ComponentID): boolean {
1338
- return this.consumer.isExported(id);
1339
- }
1340
- getExportedFrom(ids: ComponentID[]): ComponentID[] {
1341
- const notExported = this.consumer.getNotExportedIds();
1342
- return ids.filter((id) => !notExported.hasWithoutVersion(id));
1343
- }
1344
-
1345
- /**
1346
- * filter the given component-ids and set default-scope only to the new ones.
1347
- * returns the affected components.
1348
- */
1349
- async setDefaultScopeToComponents(componentIds: ComponentID[], scopeName: string): Promise<ComponentID[]> {
1350
- if (!isValidScopeName(scopeName)) {
1351
- throw new InvalidScopeName(scopeName);
1352
- }
1353
- const newComponentIds = componentIds.filter((id) => !id.hasVersion());
1354
- if (!newComponentIds.length) {
1355
- const compIdsStr = componentIds.map((compId) => compId.toString()).join(', ');
1356
- throw new BitError(
1357
- `unable to set default-scope for the following components, as they are not new:\n${compIdsStr}`
1358
- );
1359
- }
1360
- newComponentIds.map((comp) => this.bitMap.setDefaultScope(comp, scopeName));
1361
- await this.bitMap.write('scope-set');
1362
- return newComponentIds;
1363
- }
1364
-
1365
- async setDefaultScope(scopeName: string) {
1366
- if (this.defaultScope === scopeName) {
1367
- throw new Error(`the default-scope is already set as "${scopeName}", nothing to change`);
1368
- }
1369
- if (!isValidScopeName(scopeName)) {
1370
- throw new InvalidScopeName(scopeName);
1371
- }
1372
- const config = this.harmony.get<ConfigMain>('teambit.harmony/config');
1373
- config.workspaceConfig?.setExtension(
1374
- WorkspaceAspect.id,
1375
- { defaultScope: scopeName },
1376
- { mergeIntoExisting: true, ignoreVersion: true }
1377
- );
1378
- // fix also comps using the old default-scope
1379
- this.bitMap.updateDefaultScope(this.config.defaultScope, scopeName);
1380
-
1381
- this.config.defaultScope = scopeName;
1382
- await config.workspaceConfig?.write({ dir: path.dirname(config.workspaceConfig.path) });
1383
- await this.bitMap.write('scope-set');
1384
- }
1385
-
1386
- async addSpecificComponentConfig(
1387
- id: ComponentID,
1388
- aspectId: string,
1389
- config: Record<string, any> = {},
1390
- {
1391
- shouldMergeWithExisting,
1392
- shouldMergeWithPrevious,
1393
- }: {
1394
- shouldMergeWithExisting?: boolean;
1395
- /**
1396
- * relevant only when writing to .bitmap.
1397
- * eject config of the given aspect-id, so then it won't override previous config. (see "adding prod dep, tagging then adding devDep" e2e-test)
1398
- */
1399
- shouldMergeWithPrevious?: boolean;
1400
- } = { shouldMergeWithExisting: false, shouldMergeWithPrevious: false }
1401
- ) {
1402
- const componentConfigFile = await this.componentConfigFile(id);
1403
- if (componentConfigFile) {
1404
- await componentConfigFile.addAspect(
1405
- aspectId,
1406
- config,
1407
- this.resolveComponentId.bind(this),
1408
- shouldMergeWithExisting
1409
- );
1410
- await componentConfigFile.write({ override: true });
1411
- } else {
1412
- if (shouldMergeWithPrevious) {
1413
- const extensions = await this.getExtensionsFromScopeAndSpecific(id);
1414
- const obj = extensions.toConfigObject();
1415
- config = obj[aspectId] ? merge(obj[aspectId], config) : config;
1416
- }
1417
- this.bitMap.addComponentConfig(id, aspectId, config, shouldMergeWithExisting);
1418
- }
1419
- }
1420
-
1421
- async removeSpecificComponentConfig(id: ComponentID, aspectId: string, markWithMinusIfNotExist = false) {
1422
- const componentConfigFile = await this.componentConfigFile(id);
1423
- if (componentConfigFile) {
1424
- await componentConfigFile.removeAspect(aspectId, markWithMinusIfNotExist, this.resolveComponentId.bind(this));
1425
- await componentConfigFile.write({ override: true });
1426
- } else {
1427
- this.bitMap.removeComponentConfig(id, aspectId, markWithMinusIfNotExist);
1428
- }
1429
- }
1430
-
1431
- async getAspectIdFromConfig(
1432
- componentId: ComponentID,
1433
- aspectIdStr: string,
1434
- ignoreAspectVersion = false
1435
- ): Promise<string | undefined> {
1436
- const config = await this.getExtensionsFromScopeAndSpecific(componentId);
1437
- const aspectEntry = config.findExtension(aspectIdStr, ignoreAspectVersion);
1438
- return aspectEntry?.id.toString();
1439
- }
1440
-
1441
- async getSpecificComponentConfig(id: ComponentID, aspectId: string): Promise<any> {
1442
- const componentConfigFile = await this.componentConfigFile(id);
1443
- if (componentConfigFile) {
1444
- return componentConfigFile.aspects.get(aspectId)?.config;
1445
- }
1446
- return this.bitMap.getBitmapEntry(id, { ignoreVersion: true }).config?.[aspectId];
1447
- }
1448
-
1449
- private isVendorComponentByComponentDir(relativeComponentDir: PathOsBasedRelative): boolean {
1450
- const vendorDir = this.config.vendor?.directory || DEFAULT_VENDOR_DIR;
1451
- if (pathIsInside(relativeComponentDir, vendorDir)) {
1452
- return true;
1453
- }
1454
- // TODO: implement
1455
- return false;
1456
- }
1457
-
1458
- /**
1459
- * return the component config from its folder (component.json)
1460
- * @param componentId
1461
- */
1462
- public async componentConfigFile(id: ComponentID): Promise<ComponentConfigFile | undefined> {
1463
- const relativeComponentDir = this.componentDir(id, { ignoreVersion: true }, { relative: true });
1464
- return this.componentConfigFileFromComponentDirAndName(relativeComponentDir, id.fullName);
1465
- }
1466
-
1467
- /**
1468
- * @param componentPath can be relative or absolute. supports Linux and Windows
1469
- */
1470
- async getComponentIdByPath(componentPath: PathOsBased): Promise<ComponentID | undefined> {
1471
- const relativePath = path.isAbsolute(componentPath) ? path.relative(this.path, componentPath) : componentPath;
1472
- const linuxPath = pathNormalizeToLinux(relativePath);
1473
- const bitId = this.consumer.bitMap.getComponentIdByPath(linuxPath);
1474
- if (bitId) {
1475
- return this.resolveComponentId(bitId);
1476
- }
1477
- return undefined;
1478
- }
1479
-
1480
- private async componentConfigFileFromComponentDirAndName(
1481
- relativeComponentDir: PathOsBasedRelative,
1482
- name: string
1483
- ): Promise<ComponentConfigFile | undefined> {
1484
- let componentConfigFile;
1485
- if (relativeComponentDir) {
1486
- const absComponentDir = this.componentDirToAbsolute(relativeComponentDir);
1487
- const defaultScopeFromVariantsOrWs =
1488
- await this.componentDefaultScopeFromComponentDirAndNameWithoutConfigFileMemoized(relativeComponentDir, name);
1489
- componentConfigFile = await ComponentConfigFile.load(
1490
- absComponentDir,
1491
- this.createAspectList.bind(this),
1492
- defaultScopeFromVariantsOrWs
1493
- );
1494
- }
1495
-
1496
- return componentConfigFile;
1497
- }
1498
-
1499
- /**
1500
- * load aspects from the workspace and if not exists in the workspace, load from the scope.
1501
- * keep in mind that the graph may have circles.
1502
- */
1503
- async loadAspects(
1504
- ids: string[] = [],
1505
- throwOnError = false,
1506
- neededFor?: string,
1507
- opts: WorkspaceLoadAspectsOptions = {}
1508
- ): Promise<string[]> {
1509
- const workspaceAspectsLoader = this.getWorkspaceAspectsLoader();
1510
- return workspaceAspectsLoader.loadAspects(ids, throwOnError, neededFor, opts);
1511
- }
1512
-
1513
- async loadComponentsExtensions(
1514
- extensions: ExtensionDataList,
1515
- originatedFrom?: ComponentID,
1516
- opts: WorkspaceLoadAspectsOptions = {}
1517
- ): Promise<void> {
1518
- const workspaceAspectsLoader = this.getWorkspaceAspectsLoader();
1519
- return workspaceAspectsLoader.loadComponentsExtensions(extensions, originatedFrom, opts);
1520
- }
1521
-
1522
- /**
1523
- * returns one graph that includes all dependencies types. each edge has a label of the dependency
1524
- * type. the nodes content is the Component object.
1525
- */
1526
- async buildOneGraphForComponents(
1527
- ids: ComponentID[],
1528
- ignoreIds?: string[],
1529
- shouldLoadFunc?: ShouldLoadFunc,
1530
- shouldThrowOnMissingDep = true
1531
- ): Promise<Graph<Component, string>> {
1532
- const graphFromFsBuilder = new GraphFromFsBuilder(
1533
- this,
1534
- this.logger,
1535
- this.dependencyResolver,
1536
- ignoreIds,
1537
- shouldLoadFunc,
1538
- shouldThrowOnMissingDep
1539
- );
1540
- return graphFromFsBuilder.buildGraph(ids);
1541
- }
1542
-
1543
- async resolveAspects(
1544
- runtimeName?: string,
1545
- componentIds?: ComponentID[],
1546
- opts?: ResolveAspectsOptions
1547
- ): Promise<AspectDefinition[]> {
1548
- const workspaceAspectsLoader = this.getWorkspaceAspectsLoader();
1549
- return workspaceAspectsLoader.resolveAspects(runtimeName, componentIds, opts);
1550
- }
1551
-
1552
- /**
1553
- * Provides a cache folder, unique per key.
1554
- * Return value may be undefined, if workspace folder is unconventional (bare-scope, no node_modules, etc)
1555
- */
1556
- getTempDir(
1557
- /*
1558
- * unique key, i.e. aspect or component id
1559
- */
1560
- id: string
1561
- ) {
1562
- const PREFIX = 'bit';
1563
- const cacheDir = path.join(this.modulesPath, '.cache', PREFIX, id);
1564
-
1565
- // maybe should also check it's a folder and has write permissions
1566
- if (!fs.existsSync(cacheDir)) {
1567
- fs.mkdirSync(cacheDir, { recursive: true });
1568
- }
1569
-
1570
- return cacheDir;
1571
- }
1572
-
1573
- getWorkspaceAspectsLoader(): WorkspaceAspectsLoader {
1574
- let resolveEnvsFromRoots = this.config.resolveEnvsFromRoots;
1575
- if (resolveEnvsFromRoots === undefined) {
1576
- const resolveEnvsFromRootsConfig = this.globalConfig.getSync(CFG_DEFAULT_RESOLVE_ENVS_FROM_ROOTS);
1577
- const defaultResolveEnvsFromRoots: boolean =
1578
- // @ts-ignore
1579
- resolveEnvsFromRootsConfig === 'true' || resolveEnvsFromRootsConfig === true;
1580
- resolveEnvsFromRoots = defaultResolveEnvsFromRoots;
1581
- }
1582
-
1583
- const workspaceAspectsLoader = new WorkspaceAspectsLoader(
1584
- this,
1585
- this.scope,
1586
- this.aspectLoader,
1587
- this.envs,
1588
- this.dependencyResolver,
1589
- this.logger,
1590
- this.globalConfig,
1591
- this.harmony,
1592
- this.onAspectsResolveSlot,
1593
- this.onRootAspectAddedSlot,
1594
- this.config.resolveAspectsFromNodeModules,
1595
- resolveEnvsFromRoots
1596
- );
1597
- return workspaceAspectsLoader;
1598
- }
1599
-
1600
- getCapsulePath() {
1601
- const workspaceAspectsLoader = this.getWorkspaceAspectsLoader();
1602
- return workspaceAspectsLoader.getCapsulePath();
1603
- }
1604
-
1605
- shouldUseHashForCapsules() {
1606
- const workspaceAspectsLoader = this.getWorkspaceAspectsLoader();
1607
- return workspaceAspectsLoader.shouldUseHashForCapsules();
1608
- }
1609
-
1610
- /**
1611
- }
1612
-
1613
- /**
1614
- * this should be rarely in-use.
1615
- * it's currently used by watch extension as a quick workaround to load .bitmap and the components
1616
- */
1617
- async _reloadConsumer() {
1618
- this.consumer = await loadConsumer(this.path, true);
1619
- this.bitMap = new BitMap(this.consumer.bitMap, this.consumer);
1620
- await this.clearCache();
1621
- }
1622
-
1623
- async getComponentPackagePath(component: Component) {
1624
- const inInWs = await this.hasId(component.id);
1625
- const relativePath = this.dependencyResolver.getRuntimeModulePath(component, inInWs);
1626
- return path.join(this.path, relativePath);
1627
- }
1628
-
1629
- // TODO: should we return here the dir as it defined (aka components) or with /{name} prefix (as it used in legacy)
1630
- get defaultDirectory(): string {
1631
- return this.config.defaultDirectory;
1632
- }
1633
-
1634
- get legacyDefaultDirectory(): string {
1635
- if (this.defaultDirectory && !this.defaultDirectory.includes('{name}')) {
1636
- return `${this.defaultDirectory}/{name}`;
1637
- }
1638
- return this.defaultDirectory;
1639
- }
1640
-
1641
- /**
1642
- * Transform the id to ComponentId and get the exact id as appear in bitmap
1643
- */
1644
- async resolveComponentId(id: string | BitId | ComponentID): Promise<ComponentID> {
1645
- if (id instanceof BitId && id.hasScope() && id.hasVersion()) {
1646
- // an optimization to make it faster when BitId is passed
1647
- return ComponentID.fromLegacy(id);
1648
- }
1649
- const getDefaultScope = async (bitId: ComponentID, bitMapOptions?: GetBitMapComponentOptions) => {
1650
- if (bitId.scope) {
1651
- return bitId.scope;
1652
- }
1653
- const relativeComponentDir = this.componentDirFromLegacyId(bitId, bitMapOptions, { relative: true });
1654
- const defaultScope = await this.componentDefaultScopeFromComponentDirAndName(
1655
- relativeComponentDir,
1656
- bitId.fullName
1657
- );
1658
- return defaultScope;
1659
- };
1660
-
1661
- // This is required in case where you have in your workspace a component with the same name as a core aspect
1662
- // let's say you have component called react-native (which is eventually my-org.my-scope/react-native)
1663
- // and you set teambit.react/react-native as your env
1664
- // bit will get here with the string teambit.react/react-native and will try to resolve it from the workspace
1665
- // during this it will find the my-org.my-scope/react-native which is incorrect as the core one doesn't exist in the
1666
- // workspace
1667
- if (this.aspectLoader.isCoreAspect(id.toString())) {
1668
- return ComponentID.fromString(id.toString());
1669
- }
1670
- let legacyId = this.consumer.getParsedIdIfExist(id.toString(), true, true);
1671
- if (legacyId) {
1672
- const defaultScope = await getDefaultScope(legacyId);
1673
- // only reason to strip the scopeName from the given id is when this id has the defaultScope, because .bitmap
1674
- // doesn't have the defaultScope. if the given id doesn't have scope or has scope different than the default,
1675
- // then don't ignore it. search with the scope-name.
1676
- const shouldSearchWithoutScopeInProvidedId = id.toString().startsWith(`${defaultScope}/`);
1677
- legacyId = this.consumer.getParsedIdIfExist(id.toString(), true, shouldSearchWithoutScopeInProvidedId);
1678
- if (legacyId) {
1679
- return ComponentID.fromLegacy(legacyId._legacy, defaultScope);
1680
- }
1681
- }
1682
- try {
1683
- const idWithVersion = id.toString();
1684
- const [idWithoutVersion, version] = id.toString().split('@');
1685
- const _bitMapId = this.consumer.getParsedIdIfExist(idWithoutVersion, false, true);
1686
- // This logic is very specific, and very sensitive for changes please do not touch this without consulting with @ran or @gilad
1687
- // example (partial list) cases which should be handled are:
1688
- // use case 1 - ws component provided with the local scope name:
1689
- // source id : my-scope1/my-name1
1690
- // bitmap res (_id) : my-name1 (comp is tagged but not exported)
1691
- // local scope name : my-scope1
1692
- // scope content : my-name1
1693
- // expected result : my-name1
1694
- // use case 2 - component with same name exist in ws and scope (but with different scope name)
1695
- // source id : my-scope2/my-name1
1696
- // bitmap res (_id) : my-name1 (comp exist in ws but it's actually different component)
1697
- // local scope name : my-scope1
1698
- // scope content : my-scope2/my-name1
1699
- // expected result : my-scope2/my-name1
1700
- // use case 3 - component with same name exist in ws and scope (but with different scope name) - source provided without scope name
1701
- // source id : my-name1
1702
- // bitmap res (_id) : my-name1 (comp exist in ws but it's actually different component)
1703
- // local scope name : my-scope1
1704
- // scope content : my-scope1/my-name1 and my-scope2/my-name1
1705
- // expected result : my-name1 (get the name from the bitmap)
1706
- // use case 4 - component with the same name and different scope are imported into the ws
1707
- // source id : my-name1
1708
- // bitmap res (_id) : my-scope2/my-name1 (comp exist in ws from different scope (imported))
1709
- // local scope name : my-scope1
1710
- // scope content : my-scope2/my-name1
1711
- // expected result : my-scope2/my-name1 (get the name from the bitmap)
1712
-
1713
- // No entry in bitmap at all, search for the original input id
1714
- if (!_bitMapId) {
1715
- return await this.scope.resolveComponentId(id.toString());
1716
- }
1717
- const _bitMapIdWithoutVersion = _bitMapId.toStringWithoutVersion();
1718
- const _bitMapIdWithVersion = _bitMapId.changeVersion(version).toString();
1719
- // The id in the bitmap has prefix which is not in the source id - the bitmap entry has scope name
1720
- // Handle use case 4
1721
- if (_bitMapIdWithoutVersion.endsWith(idWithoutVersion) && _bitMapIdWithoutVersion !== idWithoutVersion) {
1722
- return await this.scope.resolveComponentId(_bitMapIdWithVersion);
1723
- }
1724
- // Handle case when I tagged the component locally with a default scope which is not the local scope
1725
- // but not exported it yet
1726
- // now i'm trying to load it with source id contain the default scope prefix
1727
- // we want to get it from the local first before assuming it's something coming from outside
1728
- if (!_bitMapId.scope) {
1729
- const defaultScopeForBitmapId = await getDefaultScope(_bitMapId, { ignoreVersion: true });
1730
- const getFromBitmapAddDefaultScope = () => {
1731
- let _bitmapIdWithVersionForSource = _bitMapId;
1732
- if (version) {
1733
- _bitmapIdWithVersionForSource = _bitMapId.changeVersion(version);
1734
- }
1735
- return ComponentID.fromLegacy(_bitmapIdWithVersionForSource._legacy, defaultScopeForBitmapId);
1736
- };
1737
- // a case when the given id contains the default scope
1738
- if (idWithVersion.startsWith(`${defaultScopeForBitmapId}/${_bitMapIdWithoutVersion}`)) {
1739
- return getFromBitmapAddDefaultScope();
1740
- }
1741
- // a case when the given id does not contain the default scope
1742
- const fromScope = await this.scope.resolveComponentId(idWithVersion);
1743
- if (!fromScope._legacy.hasScope()) {
1744
- return getFromBitmapAddDefaultScope();
1745
- }
1746
- }
1747
-
1748
- if (idWithoutVersion.endsWith(_bitMapIdWithoutVersion) && _bitMapIdWithoutVersion !== idWithoutVersion) {
1749
- // The id in the bitmap doesn't have scope, the source id has scope
1750
- // Handle use case 2 and use case 1
1751
- if (id.toString().startsWith(this.scope.name)) {
1752
- // Handle use case 1 - the provided id has scope name same as the local scope name
1753
- // we want to send it as it appear in the bitmap
1754
- return await this.scope.resolveComponentId(_bitMapIdWithVersion);
1755
- }
1756
- // Handle use case 2 - the provided id has scope which is not the local scope
1757
- // we want to search by the source id
1758
- return await this.scope.resolveComponentId(idWithVersion);
1759
- }
1760
- // Handle use case 3
1761
- return await this.scope.resolveComponentId(idWithVersion);
1762
- } catch (error: any) {
1763
- return ComponentID.fromString(id.toString());
1764
- }
1765
- }
1766
-
1767
- async resolveMultipleComponentIds(ids: Array<string | ComponentID | ComponentID>): Promise<ComponentID[]> {
1768
- return Promise.all(ids.map(async (id) => this.resolveComponentId(id)));
1769
- }
1770
-
1771
- /**
1772
- * component-id coming from Scope don't have the defaultScope, the legacyComponentId.scope is always populated.
1773
- * in the .bitmap we need to distinguish between the two, so the componentId needs to be corrected with the defaultScope.
1774
- */
1775
- resolveIdWithDefaultScope(componentId: ComponentID): ComponentID {
1776
- const isExported = !this.consumer.getNotExportedIds().searchWithoutVersion(componentId);
1777
- const bitId = componentId._legacy.changeScope(isExported ? componentId.scope : undefined);
1778
- return ComponentID.fromLegacy(bitId, componentId.scope);
1779
- }
1780
-
1781
- /**
1782
- * This will mutate the original extensions list and resolve it's ids
1783
- *
1784
- * @param {ExtensionDataList} extensions
1785
- * @returns {Promise<void[]>}
1786
- * @memberof Workspace
1787
- */
1788
- resolveExtensionsList(extensions: ExtensionDataList): Promise<void[]> {
1789
- const resolveMergedExtensionsP = extensions.map(async (extensionEntry) => {
1790
- if (extensionEntry.extensionId) {
1791
- // const hasVersion = extensionEntry.extensionId.hasVersion();
1792
- // const useBitmapVersion = !hasVersion;
1793
- // const resolvedId = await this.resolveComponentId(extensionEntry.extensionId, true, useBitmapVersion);
1794
-
1795
- // Assuming extensionId always has scope - do not allow extension id without scope
1796
- const resolvedId = await this.resolveComponentId(extensionEntry.extensionId);
1797
- extensionEntry.extensionId = resolvedId;
1798
- }
1799
- });
1800
- return Promise.all(resolveMergedExtensionsP);
1801
- }
1802
-
1803
- /**
1804
- * configure an environment to the given components in the .bitmap file, this configuration overrides other, such as
1805
- * overrides in workspace.jsonc.
1806
- */
1807
- async setEnvToComponents(envId: ComponentID, componentIds: ComponentID[]) {
1808
- const envStrWithPossiblyVersion = await this.resolveEnvIdWithPotentialVersionForConfig(envId);
1809
- const envIdStrNoVersion = envId.toStringWithoutVersion();
1810
- await this.unsetEnvFromComponents(componentIds);
1811
- await Promise.all(
1812
- componentIds.map(async (componentId) => {
1813
- await this.addSpecificComponentConfig(componentId, envStrWithPossiblyVersion);
1814
- await this.addSpecificComponentConfig(componentId, EnvsAspect.id, { env: envIdStrNoVersion });
1815
- })
1816
- );
1817
- await this.bitMap.write(`env-set (${envId.toString()})`);
1818
- }
1819
-
1820
- /**
1821
- * helpful when a user provides an env-string to be set and this env has no version.
1822
- * in the workspace config, a custom-env needs to be set with a version unless it's part of the workspace.
1823
- * (inside envs/envs it's set without a version).
1824
- */
1825
- async resolveEnvIdWithPotentialVersionForConfig(envId: ComponentID): Promise<string> {
1826
- const isCore = this.aspectLoader.isCoreAspect(envId.toStringWithoutVersion());
1827
- const existsOnWorkspace = await this.hasId(envId);
1828
- if (isCore || existsOnWorkspace) {
1829
- // the env needs to be without version
1830
- return envId.toStringWithoutVersion();
1831
- }
1832
- // the env must include a version
1833
- if (envId.hasVersion()) {
1834
- return envId.toString();
1835
- }
1836
- const extensions = this.harmony.get<ConfigMain>('teambit.harmony/config').extensions;
1837
- const found = extensions?.findExtension(envId.toString(), true);
1838
- if (found && found.extensionId?.version) {
1839
- return found.extensionId.toString();
1840
- }
1841
- const comps = await this.importAndGetMany([envId], `to get the env ${envId.toString()}`);
1842
- return comps[0].id.toString();
1843
- }
1844
-
1845
- /**
1846
- * remove env configuration from the .bitmap file, so then other configuration, such as "variants" will take place
1847
- */
1848
- async unsetEnvFromComponents(ids: ComponentID[]): Promise<{ changed: ComponentID[]; unchanged: ComponentID[] }> {
1849
- const changed: ComponentID[] = [];
1850
- const unchanged: ComponentID[] = [];
1851
- await Promise.all(
1852
- ids.map(async (id) => {
1853
- const extensions = await this.getExtensionsFromScopeAndSpecific(id);
1854
- const envsAspect = extensions.findCoreExtension(EnvsAspect.id)?.rawConfig;
1855
- const currentEnv = envsAspect && envsAspect !== REMOVE_EXTENSION_SPECIAL_SIGN ? envsAspect.env : null;
1856
- if (!currentEnv) {
1857
- unchanged.push(id);
1858
- return;
1859
- }
1860
- // the env that gets saved in the .bitmap file config root can be with or without version.
1861
- // e.g. when a custom env is in .bitmap, it's saved without version, but when asking the component for the
1862
- // env by `this.getAspectIdFromConfig`, it returns the env with version.
1863
- // to make sure we remove the env from the .bitmap, we need to remove both with and without version.
1864
- const currentEnvWithPotentialVersion = await this.getAspectIdFromConfig(id, currentEnv, true);
1865
- await this.removeSpecificComponentConfig(id, currentEnv);
1866
- if (currentEnvWithPotentialVersion && currentEnvWithPotentialVersion.includes('@')) {
1867
- await this.removeSpecificComponentConfig(id, currentEnvWithPotentialVersion);
1868
- }
1869
- await this.removeSpecificComponentConfig(id, EnvsAspect.id);
1870
- changed.push(id);
1871
- })
1872
- );
1873
- await this.bitMap.write(`env-unset`);
1874
- return { changed, unchanged };
1875
- }
1876
-
1877
- async updateEnvForComponents(envIdStr?: string, pattern?: string) {
1878
- const allWsComps = await this.list();
1879
- const allWsIds = await this.listIds();
1880
- const isInWs = (envId: ComponentID) => allWsIds.find((id) => id.isEqual(envId, { ignoreVersion: true }));
1881
- const allEnvs = await this.envs.createEnvironment(allWsComps);
1882
- const getEnvWithVersion = async (envId: ComponentID) => {
1883
- if (envId.hasVersion()) return envId;
1884
- if (isInWs(envId)) return envId;
1885
- try {
1886
- const fromRemote = await this.scope.getRemoteComponent(envId);
1887
- return envId.changeVersion(fromRemote.id.version);
1888
- } catch (err) {
1889
- throw new BitError(`unable to find ${envIdStr} in the remote`);
1890
- }
1891
- };
1892
- const getEnvs = async (): Promise<ComponentID[]> => {
1893
- if (envIdStr) {
1894
- const envCompId = await this.resolveComponentId(envIdStr);
1895
- const envWithVer = await getEnvWithVersion(envCompId);
1896
- return [envWithVer];
1897
- }
1898
- const allEnvsIds = allEnvs.runtimeEnvs.map((env) => env.id);
1899
- const allEnvsCompIds = await this.resolveMultipleComponentIds(allEnvsIds);
1900
- // check whether the envId has version, otherwise, it's a core env.
1901
- const nonCoreEnvs = allEnvsCompIds.filter((envId) => envId.hasVersion());
1902
- const envsWithVersions = await mapSeries(nonCoreEnvs, (envId) =>
1903
- getEnvWithVersion(envId.changeVersion(undefined))
1904
- );
1905
- return envsWithVersions;
1906
- };
1907
- const envsWithVerToUpdate = await getEnvs();
1908
-
1909
- const compIdsToUpdate = pattern ? await this.idsByPattern(pattern) : allWsIds;
1910
- const compsToUpdate = await this.getMany(compIdsToUpdate);
1911
- const alreadyUpToDate: ComponentID[] = [];
1912
- const updated: { [envId: string]: ComponentID[] } = {};
1913
- await Promise.all(
1914
- compsToUpdate.map(async (comp) => {
1915
- const compEnvs = compact(
1916
- envsWithVerToUpdate.map((envId) => comp.state.aspects.get(envId.toStringWithoutVersion()))
1917
- );
1918
- if (!compEnvs.length) return;
1919
- const compEnv = compEnvs[0]; // should not be more than one
1920
- const envToUpdate = envsWithVerToUpdate.find((e) => e.isEqual(compEnv.id, { ignoreVersion: true }));
1921
- if (!envToUpdate) throw new Error(`unable to find ${compEnv.id.toString()} in the envs to update`);
1922
- const envIsInWs = isInWs(envToUpdate);
1923
-
1924
- if (!envIsInWs && compEnv.id.version === envToUpdate.version) {
1925
- // nothing to update
1926
- alreadyUpToDate.push(comp.id);
1927
- return;
1928
- }
1929
- if (envIsInWs && !(await this.getSpecificComponentConfig(comp.id, compEnv.id.toString()))) {
1930
- // compEnv has version. If this id with version doesn't exist in .bitmap, either, it's not saved in .bitmap
1931
- // (probably it's in the model) or it's in .bitmap without version (as expected). either way, nothing to update.
1932
- alreadyUpToDate.push(comp.id);
1933
- return;
1934
- }
1935
- // don't mark with minus if not exist in .bitmap. it's not needed. when the component is loaded, the
1936
- // merge-operation of the aspects removes duplicate aspect-id with different versions.
1937
- await this.removeSpecificComponentConfig(comp.id, compEnv.id.toString(), false);
1938
- await this.addSpecificComponentConfig(
1939
- comp.id,
1940
- envIsInWs ? envToUpdate.toStringWithoutVersion() : envToUpdate.toString(),
1941
- compEnv.config
1942
- );
1943
- (updated[envToUpdate.toString()] ||= []).push(comp.id);
1944
- })
1945
- );
1946
- await this.bitMap.write('env-update');
1947
- return { updated, alreadyUpToDate };
1948
- }
1949
-
1950
- getComponentPathsRegExps() {
1951
- return this.componentPathsRegExps;
1952
- }
1953
-
1954
- async setComponentPathsRegExps() {
1955
- const workspaceComponents = await this.list();
1956
- const workspacePackageNames = workspaceComponents.map((c) => this.componentPackageName(c));
1957
- const packageManager = this.dependencyResolver.getPackageManagerName();
1958
- const isPnpmEnabled = typeof packageManager === 'undefined' || packageManager.includes('pnpm');
1959
- const pathsExcluding = [
1960
- generateNodeModulesPattern({
1961
- packages: workspacePackageNames,
1962
- target: PatternTarget.WEBPACK,
1963
- isPnpmEnabled,
1964
- }),
1965
- ];
1966
- this.componentPathsRegExps = [...pathsExcluding.map((stringPattern) => new RegExp(stringPattern))];
1967
- }
1968
-
1969
- getInjectedDirs(component: Component): Promise<string[]> {
1970
- const relativeCompDir = this.componentDir(component.id, undefined, {
1971
- relative: true,
1972
- });
1973
- return this.dependencyResolver.getInjectedDirs(
1974
- this.path,
1975
- relativeCompDir,
1976
- this.dependencyResolver.getPackageName(component)
1977
- );
1978
- }
1979
-
1980
- async getAutoDetectOverrides(configuredExtensions: ExtensionDataList, id: ComponentID, legacyFiles: SourceFile[]) {
1981
- let policy = await this.dependencyResolver.mergeVariantPolicies(configuredExtensions, id, legacyFiles);
1982
- // this is needed for "bit install" to install the dependencies from the merge config (see https://github.com/teambit/bit/pull/6849)
1983
- const depsDataOfMergeConfig = this.getDepsDataOfMergeConfig(id);
1984
- if (depsDataOfMergeConfig) {
1985
- const policiesFromMergeConfig = VariantPolicy.fromConfigObject(depsDataOfMergeConfig, { source: 'auto' });
1986
- policy = VariantPolicy.mergePolices([policy, policiesFromMergeConfig]);
1987
- }
1988
- return policy.toLegacyAutoDetectOverrides();
1989
- }
1990
-
1991
- getAutoDetectConfigMerge(id: ComponentID) {
1992
- const depsDataOfMergeConfig = this.getDepsDataOfMergeConfig(id);
1993
- if (depsDataOfMergeConfig) {
1994
- const policy = VariantPolicy.fromConfigObject(depsDataOfMergeConfig, { source: 'auto' });
1995
- return policy.toLegacyAutoDetectOverrides();
1996
- }
1997
- return undefined;
1998
- }
1999
- }
2000
-
2001
- /**
2002
- * this is a super hacky way to do it. problem is that loadAspect is running as onStart hook, where we don't
2003
- * have the CLI fully loaded yet, so we can't get the command from the CLI aspect, we have to retrieve it from
2004
- * process.argv.
2005
- * in general, we don't want every command to try again and again fetching un-built versions. otherwise, every time
2006
- * Bit loads (even bit --help), it'll fetch them and slow down everything.
2007
- * instead, long-running commands and those that need the artifacts from the Version objects, should try to re-fetch.
2008
- */
2009
- function shouldReFetchUnBuiltVersion() {
2010
- const commandsToReFetch = ['import'];
2011
- return commandsToReFetch.includes(process.argv[2]);
2012
- }
2013
-
2014
- export default Workspace;