@teambit/workspace 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.
Files changed (86) hide show
  1. package/aspects-merger.ts +319 -0
  2. package/bit-map.ts +277 -0
  3. package/build-graph-from-fs.ts +188 -0
  4. package/build-graph-ids-from-fs.ts +216 -0
  5. package/capsule.cmd.ts +217 -0
  6. package/constants.ts +1 -0
  7. package/dist/aspects-merger.js +13 -22
  8. package/dist/aspects-merger.js.map +1 -1
  9. package/dist/bit-map.d.ts +1 -1
  10. package/dist/build-graph-from-fs.d.ts +2 -2
  11. package/dist/build-graph-from-fs.js +1 -2
  12. package/dist/build-graph-from-fs.js.map +1 -1
  13. package/dist/build-graph-ids-from-fs.js +1 -1
  14. package/dist/build-graph-ids-from-fs.js.map +1 -1
  15. package/dist/capsule.cmd.d.ts +2 -2
  16. package/dist/capsule.cmd.js +1 -2
  17. package/dist/capsule.cmd.js.map +1 -1
  18. package/dist/component-config-file/component-config-file.d.ts +2 -2
  19. package/dist/component-tree.widget.d.ts +2 -2
  20. package/dist/eject-conf.cmd.d.ts +2 -2
  21. package/dist/envs-subcommands/envs-replace.cmd.d.ts +1 -1
  22. package/dist/envs-subcommands/envs-set.cmd.d.ts +1 -1
  23. package/dist/envs-subcommands/envs-unset.cmd.d.ts +1 -1
  24. package/dist/envs-subcommands/envs-update.cmd.d.ts +1 -1
  25. package/dist/filter.d.ts +1 -1
  26. package/dist/filter.js +1 -1
  27. package/dist/filter.js.map +1 -1
  28. package/dist/merge-conflict-file.d.ts +1 -1
  29. package/dist/merge-conflict-file.js +1 -2
  30. package/dist/merge-conflict-file.js.map +1 -1
  31. package/dist/on-component-events.d.ts +6 -6
  32. package/dist/{preview-1703505948637.js → preview-1703647408454.js} +2 -2
  33. package/dist/scope-subcommands/scope-set.cmd.d.ts +1 -1
  34. package/dist/ui/workspace/use-workspace.d.ts +8 -8
  35. package/dist/ui/workspace/use-workspace.js +7 -18
  36. package/dist/ui/workspace/use-workspace.js.map +1 -1
  37. package/dist/ui/workspace/workspace-model.d.ts +3 -3
  38. package/dist/ui/workspace/workspace-overview/workspace-overview.d.ts +2 -2
  39. package/dist/ui/workspace/workspace-overview/workspace-overview.js +1 -2
  40. package/dist/ui/workspace/workspace-overview/workspace-overview.js.map +1 -1
  41. package/dist/ui/workspace/workspace-provider.d.ts +3 -3
  42. package/dist/ui/workspace/workspace.d.ts +3 -3
  43. package/dist/workspace-aspects-loader.d.ts +3 -3
  44. package/dist/workspace-aspects-loader.js +7 -11
  45. package/dist/workspace-aspects-loader.js.map +1 -1
  46. package/dist/workspace-component/comp-files.d.ts +3 -3
  47. package/dist/workspace-component/component-status.d.ts +3 -3
  48. package/dist/workspace-component/workspace-component-loader.d.ts +5 -5
  49. package/dist/workspace-component/workspace-component-loader.js +31 -28
  50. package/dist/workspace-component/workspace-component-loader.js.map +1 -1
  51. package/dist/workspace.composition.d.ts +2 -2
  52. package/dist/workspace.d.ts +6 -6
  53. package/dist/workspace.graphql.d.ts +2 -2
  54. package/dist/workspace.graphql.js +2 -4
  55. package/dist/workspace.graphql.js.map +1 -1
  56. package/dist/workspace.js +16 -23
  57. package/dist/workspace.js.map +1 -1
  58. package/dist/workspace.provider.d.ts +12 -12
  59. package/dist/workspace.provider.js +8 -11
  60. package/dist/workspace.provider.js.map +1 -1
  61. package/dist/workspace.ui.drawer.d.ts +1 -1
  62. package/dist/workspace.ui.drawer.js +5 -6
  63. package/dist/workspace.ui.drawer.js.map +1 -1
  64. package/dist/workspace.ui.runtime.d.ts +1 -1
  65. package/dist/workspace.ui.runtime.js +2 -8
  66. package/dist/workspace.ui.runtime.js.map +1 -1
  67. package/eject-conf.cmd.ts +57 -0
  68. package/filter.ts +139 -0
  69. package/index.ts +22 -0
  70. package/merge-conflict-file.ts +129 -0
  71. package/on-component-events.ts +24 -0
  72. package/package.json +39 -46
  73. package/pattern.cmd.ts +53 -0
  74. package/tsconfig.json +16 -21
  75. package/types/asset.d.ts +15 -3
  76. package/types.ts +71 -0
  77. package/use.cmd.ts +25 -0
  78. package/workspace-aspects-loader.ts +885 -0
  79. package/workspace-component/workspace-component-loader.ts +25 -16
  80. package/workspace-section.ts +14 -0
  81. package/workspace.aspect.ts +9 -0
  82. package/workspace.graphql.ts +133 -0
  83. package/workspace.main.runtime.ts +56 -0
  84. package/workspace.provider.ts +282 -0
  85. package/workspace.ts +2014 -0
  86. package/workspace.ui-root.ts +65 -0
@@ -0,0 +1,319 @@
1
+ import { Harmony } from '@teambit/harmony';
2
+ import { Component } from '@teambit/component';
3
+ import { UnmergedComponent } from '@teambit/legacy/dist/scope/lanes/unmerged-components';
4
+ import { ComponentID } from '@teambit/component-id';
5
+ import { EnvsAspect } from '@teambit/envs';
6
+ import { DependencyResolverAspect } from '@teambit/dependency-resolver';
7
+ import { ExtensionDataList, getCompareExtPredicate } from '@teambit/legacy/dist/consumer/config/extension-data';
8
+ import { partition, mergeWith, merge, uniq, uniqWith } from 'lodash';
9
+ import { MergeConfigConflict } from './exceptions/merge-config-conflict';
10
+ import { AspectSpecificField, ExtensionsOrigin, Workspace } from './workspace';
11
+ import { MergeConflictFile } from './merge-conflict-file';
12
+
13
+ export class AspectsMerger {
14
+ readonly mergeConflictFile: MergeConflictFile;
15
+ private mergeConfigDepsResolverDataCache: { [compIdStr: string]: Record<string, any> } = {};
16
+ constructor(private workspace: Workspace, private harmony: Harmony) {
17
+ this.mergeConflictFile = new MergeConflictFile(workspace.path);
18
+ }
19
+
20
+ getDepsDataOfMergeConfig(id: ComponentID) {
21
+ return this.mergeConfigDepsResolverDataCache[id.toString()];
22
+ }
23
+
24
+ /**
25
+ * Calculate the component config based on:
26
+ * the config property in the .bitmap file
27
+ * the component.json file in the component folder
28
+ * matching pattern in the variants config
29
+ * defaults extensions from workspace config
30
+ * extensions from the model.
31
+ */
32
+ // eslint-disable-next-line complexity
33
+ async merge(
34
+ componentId: ComponentID,
35
+ componentFromScope?: Component,
36
+ excludeOrigins: ExtensionsOrigin[] = []
37
+ ): Promise<{
38
+ extensions: ExtensionDataList;
39
+ beforeMerge: Array<{ extensions: ExtensionDataList; origin: ExtensionsOrigin; extraData: any }>; // useful for debugging
40
+ errors?: Error[];
41
+ }> {
42
+ // TODO: consider caching this result
43
+ let configFileExtensions: ExtensionDataList | undefined;
44
+ let variantsExtensions: ExtensionDataList | undefined;
45
+ const mergeFromScope = true;
46
+ const errors: Error[] = [];
47
+
48
+ const bitMapEntry = this.workspace.consumer.bitMap.getComponentIfExist(componentId);
49
+ const bitMapExtensions = bitMapEntry?.config;
50
+
51
+ let configMerge: Record<string, any> | undefined;
52
+ try {
53
+ configMerge = this.mergeConflictFile.getConflictParsed(componentId.toStringWithoutVersion());
54
+ } catch (err) {
55
+ if (!(err instanceof MergeConfigConflict)) {
56
+ throw err;
57
+ }
58
+ this.workspace.logger.error(`unable to parse the config file for ${componentId.toString()} due to conflicts`);
59
+ errors.push(err);
60
+ }
61
+
62
+ const adjustEnvsOnConfigMerge = (conf: Record<string, any>) => {
63
+ const env = conf[EnvsAspect.id]?.env;
64
+ if (!env) return;
65
+ const [id] = env.split('@');
66
+ conf[EnvsAspect.id] = { env: id };
67
+ conf[env] = {};
68
+ };
69
+
70
+ const unmergedData = this.getUnmergedData(componentId);
71
+ const unmergedDataMergeConf = unmergedData?.mergedConfig;
72
+ const getMergeConfigCombined = () => {
73
+ if (!configMerge && !unmergedDataMergeConf) return undefined;
74
+ if (!configMerge) return unmergedDataMergeConf;
75
+ if (!unmergedDataMergeConf) return configMerge;
76
+
77
+ return mergeWith(configMerge, unmergedDataMergeConf, (objValue, srcValue) => {
78
+ if (Array.isArray(objValue)) {
79
+ // critical for dependencyResolver.policy.*dependencies. otherwise, it will override the array
80
+ return objValue.concat(srcValue);
81
+ }
82
+ return undefined;
83
+ });
84
+ };
85
+ const mergeConfigCombined = getMergeConfigCombined();
86
+ adjustEnvsOnConfigMerge(mergeConfigCombined || {});
87
+
88
+ const configMergeExtensions = mergeConfigCombined
89
+ ? ExtensionDataList.fromConfigObject(mergeConfigCombined)
90
+ : undefined;
91
+
92
+ this.removeAutoDepsFromConfig(componentId, configMergeExtensions);
93
+ const scopeExtensions = this.getComponentFromScopeWithoutDuplications(componentFromScope);
94
+ // backward compatibility. previously, it was saved as an array into the model (when there was merge-config)
95
+ this.removeAutoDepsFromConfig(componentId, scopeExtensions, true);
96
+ const [specific, nonSpecific] = partition(scopeExtensions, (entry) => entry.config[AspectSpecificField] === true);
97
+ const scopeExtensionsNonSpecific = new ExtensionDataList(...nonSpecific);
98
+ const scopeExtensionsSpecific = new ExtensionDataList(...specific);
99
+
100
+ const componentConfigFile = await this.workspace.componentConfigFile(componentId);
101
+ if (componentConfigFile) {
102
+ configFileExtensions = componentConfigFile.aspects.toLegacy();
103
+ }
104
+ const relativeComponentDir = this.workspace.componentDir(componentId, { ignoreVersion: true }, { relative: true });
105
+ const variantConfig = this.workspace.variants.byRootDirAndName(relativeComponentDir, componentId.fullName);
106
+ if (variantConfig) {
107
+ variantsExtensions = variantConfig.extensions.clone();
108
+ // Do not merge from scope when there is specific variant (which is not *) that match the component
109
+ // if (variantConfig.maxSpecificity > 0) {
110
+ // mergeFromScope = false;
111
+ // }
112
+ }
113
+ // We don't stop on each step because we want to merge the default scope even if propagate=false but the default scope is not defined
114
+ // in the case the same extension pushed twice, the former takes precedence (opposite of Object.assign)
115
+ const extensionsToMerge: Array<{ origin: ExtensionsOrigin; extensions: ExtensionDataList; extraData: any }> = [];
116
+ let envWasFoundPreviously = false;
117
+ const removedExtensionIds: string[] = [];
118
+
119
+ const addExtensionsToMerge = async (extensions: ExtensionDataList, origin: ExtensionsOrigin, extraData?: any) => {
120
+ if (!extensions.length) {
121
+ return;
122
+ }
123
+ removedExtensionIds.push(...extensions.filter((extData) => extData.isRemoved).map((extData) => extData.stringId));
124
+ const extsWithoutRemoved = extensions.filterRemovedExtensions();
125
+ const selfInMergedExtensions = extsWithoutRemoved.findExtension(componentId.toStringWithoutVersion(), true);
126
+ const extsWithoutSelf = selfInMergedExtensions?.extensionId
127
+ ? extsWithoutRemoved.remove(selfInMergedExtensions.extensionId)
128
+ : extsWithoutRemoved;
129
+ const preferWorkspaceVersion = origin !== 'BitmapFile' && origin !== 'ComponentJsonFile';
130
+ // it's important to do this resolution before the merge, otherwise we have issues with extensions
131
+ // coming from scope with local scope name, as opposed to the same extension comes from the workspace with default scope name
132
+ // also, it's important to do it before filtering the env, because when the env was not exported, it's saved with scope-name
133
+ // inside the "env" prop of teambit.envs/env, but without scope-name in the root.
134
+ const extsWithUpdatedIds = await this.resolveExtensionListIds(extsWithoutSelf, preferWorkspaceVersion);
135
+ const { extensionDataListFiltered, envIsCurrentlySet } = await this.filterEnvsFromExtensionsIfNeeded(
136
+ extsWithUpdatedIds,
137
+ envWasFoundPreviously,
138
+ origin
139
+ );
140
+ if (envIsCurrentlySet) {
141
+ envWasFoundPreviously = true;
142
+ }
143
+
144
+ extensionsToMerge.push({ origin, extensions: extensionDataListFiltered, extraData });
145
+ };
146
+ const setDataListAsSpecific = (extensions: ExtensionDataList) => {
147
+ extensions.forEach((dataEntry) => (dataEntry.config[AspectSpecificField] = true));
148
+ };
149
+ if (bitMapExtensions && !excludeOrigins.includes('BitmapFile')) {
150
+ const extensionDataList = ExtensionDataList.fromConfigObject(bitMapExtensions);
151
+ setDataListAsSpecific(extensionDataList);
152
+ await addExtensionsToMerge(extensionDataList, 'BitmapFile');
153
+ }
154
+ // config-merge is after the .bitmap. because normally if you have config set in .bitmap, you won't
155
+ // be able to lane-merge. (unless you specify --ignore-config-changes).
156
+ // so, if there is config in .bitmap, it probably happened after lane-merge.
157
+ if (configMergeExtensions && !excludeOrigins.includes('ConfigMerge')) {
158
+ await addExtensionsToMerge(ExtensionDataList.fromArray(configMergeExtensions), 'ConfigMerge');
159
+ }
160
+ if (configFileExtensions && !excludeOrigins.includes('ComponentJsonFile')) {
161
+ setDataListAsSpecific(configFileExtensions);
162
+ await addExtensionsToMerge(configFileExtensions, 'ComponentJsonFile');
163
+ }
164
+ if (!excludeOrigins.includes('ModelSpecific')) {
165
+ await addExtensionsToMerge(ExtensionDataList.fromArray(scopeExtensionsSpecific), 'ModelSpecific');
166
+ }
167
+ let continuePropagating = componentConfigFile?.propagate ?? true;
168
+ if (variantsExtensions && continuePropagating && !excludeOrigins.includes('WorkspaceVariants')) {
169
+ const appliedRules = variantConfig?.sortedMatches.map(({ pattern, specificity }) => ({ pattern, specificity }));
170
+ await addExtensionsToMerge(variantsExtensions, 'WorkspaceVariants', { appliedRules });
171
+ }
172
+ continuePropagating = continuePropagating && (variantConfig?.propagate ?? true);
173
+ if (mergeFromScope && continuePropagating && !excludeOrigins.includes('ModelNonSpecific')) {
174
+ await addExtensionsToMerge(scopeExtensionsNonSpecific, 'ModelNonSpecific');
175
+ }
176
+
177
+ const afterMerge = ExtensionDataList.mergeConfigs(extensionsToMerge.map((ext) => ext.extensions));
178
+ const withoutRemoved = afterMerge.filter((extData) => !removedExtensionIds.includes(extData.stringId));
179
+ const extensions = ExtensionDataList.fromArray(withoutRemoved);
180
+ return {
181
+ extensions,
182
+ beforeMerge: extensionsToMerge,
183
+ errors,
184
+ };
185
+ }
186
+
187
+ /**
188
+ * before version 0.0.882 it was possible to save Version object with the same extension twice.
189
+ */
190
+ private getComponentFromScopeWithoutDuplications(componentFromScope?: Component) {
191
+ if (!componentFromScope) return new ExtensionDataList();
192
+ const scopeExtensions = componentFromScope.config.extensions;
193
+ const scopeExtIds = scopeExtensions.ids;
194
+ const scopeExtHasDuplications = scopeExtIds.length !== uniq(scopeExtIds).length;
195
+ if (!scopeExtHasDuplications) {
196
+ return scopeExtensions;
197
+ }
198
+ // let's remove this duplicated extension blindly without trying to merge. (no need to merge coz it's old data from scope
199
+ // which will be overridden anyway by the workspace or other config strategies).
200
+ const arr = uniqWith(scopeExtensions, getCompareExtPredicate(true));
201
+ return ExtensionDataList.fromArray(arr);
202
+ }
203
+
204
+ /**
205
+ * from the merge-config we get the dep-resolver policy as an array, because it needs to support "force" prop.
206
+ * however, when we save the config, we want to save it as an object, so we need split the data into two:
207
+ * 1. force: true, which gets saved into the config.
208
+ * 2. force: false, which gets saved into the data.dependencies later on. see the workspace.getAutoDetectOverrides()
209
+ */
210
+ private removeAutoDepsFromConfig(componentId: ComponentID, conf?: ExtensionDataList, fromScope = false) {
211
+ if (!conf) return;
212
+ const policy = conf.findCoreExtension(DependencyResolverAspect.id)?.config.policy;
213
+ if (!policy) return;
214
+
215
+ const mergeConfigObj = {};
216
+ ['dependencies', 'devDependencies', 'peerDependencies'].forEach((key) => {
217
+ if (!policy[key]) return;
218
+ // this is only relevant when it is saved as an array. otherwise, it's always force: true.
219
+ if (!Array.isArray(policy[key])) return;
220
+
221
+ mergeConfigObj[key] = policy[key].filter((dep) => !dep.force);
222
+ policy[key] = policy[key].filter((dep) => dep.force);
223
+
224
+ if (!policy[key].length) {
225
+ delete policy[key];
226
+ return;
227
+ }
228
+ // convert to object
229
+ policy[key] = policy[key].reduce((acc, current) => {
230
+ acc[current.name] = current.version;
231
+ return acc;
232
+ }, {});
233
+ });
234
+
235
+ if (!fromScope) {
236
+ if (!this.mergeConfigDepsResolverDataCache[componentId.toString()]) {
237
+ this.mergeConfigDepsResolverDataCache[componentId.toString()] = {};
238
+ }
239
+ this.mergeConfigDepsResolverDataCache[componentId.toString()] = merge(
240
+ this.mergeConfigDepsResolverDataCache[componentId.toString()],
241
+ mergeConfigObj
242
+ );
243
+ }
244
+ }
245
+
246
+ private getUnmergedData(componentId: ComponentID): UnmergedComponent | undefined {
247
+ return this.workspace.scope.legacyScope.objects.unmergedComponents.getEntry(componentId.fullName);
248
+ }
249
+
250
+ private async filterEnvsFromExtensionsIfNeeded(
251
+ extensionDataList: ExtensionDataList,
252
+ envWasFoundPreviously: boolean,
253
+ origin: ExtensionsOrigin
254
+ ) {
255
+ const envAspect = extensionDataList.findExtension(EnvsAspect.id);
256
+ const envFromEnvsAspect: string | undefined = envAspect?.config.env || envAspect?.data.id;
257
+ const aspectsRegisteredAsEnvs = extensionDataList
258
+ .filter((aspect) =>
259
+ this.workspace.envs.getEnvDefinitionByStringId(aspect.newExtensionId?.toString() || aspect.stringId)
260
+ )
261
+ .map((aspect) => aspect.stringId);
262
+ if (envWasFoundPreviously && (envAspect || aspectsRegisteredAsEnvs.length)) {
263
+ const nonEnvs = extensionDataList.filter((e) => {
264
+ // normally the env-id inside the envs aspect doesn't have a version, but the aspect itself has a version.
265
+ // also, the env-id inside the envs aspect includes the default-scope, but the aspect itself doesn't.
266
+ if (
267
+ (envFromEnvsAspect && e.stringId === envFromEnvsAspect) ||
268
+ (envFromEnvsAspect && e.extensionId?.toStringWithoutVersion() === envFromEnvsAspect) ||
269
+ aspectsRegisteredAsEnvs.includes(e.stringId)
270
+ ) {
271
+ return false;
272
+ }
273
+ return true;
274
+ });
275
+ // still, aspect env may have other data other then config.env.
276
+ if (envAspect) delete envAspect.config.env;
277
+ return { extensionDataListFiltered: new ExtensionDataList(...nonEnvs), envIsCurrentlySet: true };
278
+ }
279
+ if (envFromEnvsAspect && (origin === 'ModelNonSpecific' || origin === 'ModelSpecific')) {
280
+ // if env was found, search for this env in the workspace and if found, replace the env-id with the one from the workspace
281
+ const envAspectExt = extensionDataList.find((e) => e.extensionId?.toStringWithoutVersion() === envFromEnvsAspect);
282
+ const ids = await this.workspace.listIds();
283
+ const envAspectId = envAspectExt?.extensionId;
284
+ const found = envAspectId && ids.find((id) => id.isEqualWithoutVersion(envAspectId));
285
+ if (found) {
286
+ envAspectExt.extensionId = found;
287
+ }
288
+ }
289
+ return { extensionDataListFiltered: extensionDataList, envIsCurrentlySet: Boolean(envFromEnvsAspect) };
290
+ }
291
+
292
+ /**
293
+ * This will mutate the entries with extensionId prop to have resolved legacy id
294
+ * This should be worked on the extension data list not the new aspect list
295
+ * @param extensionList
296
+ */
297
+ private async resolveExtensionListIds(
298
+ extensionList: ExtensionDataList,
299
+ preferWorkspaceVersion = false
300
+ ): Promise<ExtensionDataList> {
301
+ const promises = extensionList.map(async (entry) => {
302
+ if (entry.extensionId) {
303
+ // don't pass `entry.extensionId` (as ComponentID) to `resolveComponentId` because then it'll use the optimization
304
+ // of parsing it to ComponentID without checking the workspace. Normally, this optimization is good, but here
305
+ // in case the extension wasn't exported, the ComponentID is wrong, it has the scope-name due to incorrect ComponentID.fromString
306
+ // in configEntryToDataEntry() function. It'd be ideal to fix it from there but it's not easy.
307
+ const componentId = await this.workspace.resolveComponentId(entry.extensionId.toString());
308
+ const idFromWorkspace = preferWorkspaceVersion ? this.workspace.getIdIfExist(componentId) : undefined;
309
+ const id = idFromWorkspace || componentId;
310
+ entry.extensionId = id;
311
+ entry.newExtensionId = id;
312
+ }
313
+
314
+ return entry;
315
+ });
316
+ await Promise.all(promises);
317
+ return extensionList;
318
+ }
319
+ }
package/bit-map.ts ADDED
@@ -0,0 +1,277 @@
1
+ import { isEqual, merge } from 'lodash';
2
+ import { ComponentID } from '@teambit/component-id';
3
+ import LegacyBitMap from '@teambit/legacy/dist/consumer/bit-map';
4
+ import { Consumer } from '@teambit/legacy/dist/consumer';
5
+ import { GetBitMapComponentOptions } from '@teambit/legacy/dist/consumer/bit-map/bit-map';
6
+ import ComponentMap from '@teambit/legacy/dist/consumer/bit-map/component-map';
7
+ import { REMOVE_EXTENSION_SPECIAL_SIGN } from '@teambit/legacy/dist/consumer/config';
8
+ import { BitError } from '@teambit/bit-error';
9
+ import { LaneId } from '@teambit/lane-id';
10
+ import EnvsAspect from '@teambit/envs';
11
+ import { getPathStatIfExist } from '@teambit/legacy/dist/utils/fs/last-modified';
12
+ import { PathOsBasedAbsolute } from '@teambit/legacy/dist/utils/path';
13
+
14
+ export type MergeOptions = {
15
+ mergeStrategy?: 'theirs' | 'ours' | 'manual';
16
+ };
17
+ /**
18
+ * consider extracting to a new component.
19
+ * (pro: making Workspace aspect smaller. con: it's an implementation details of the workspace)
20
+ */
21
+ export class BitMap {
22
+ constructor(private legacyBitMap: LegacyBitMap, private consumer: Consumer) {}
23
+
24
+ mergeBitmaps(bitmapContent: string, otherBitmapContent: string, opts: MergeOptions = {}): string {
25
+ return LegacyBitMap.mergeContent(bitmapContent, otherBitmapContent, opts);
26
+ }
27
+
28
+ getPath(): PathOsBasedAbsolute {
29
+ return this.legacyBitMap.mapPath;
30
+ }
31
+
32
+ /**
33
+ * adds component config to the .bitmap file.
34
+ * later, upon `bit tag`, the data is saved in the scope.
35
+ * returns a boolean indicating whether a change has been made.
36
+ */
37
+ addComponentConfig(
38
+ id: ComponentID,
39
+ aspectId: string,
40
+ config: Record<string, any> = {},
41
+ shouldMergeConfig = false
42
+ ): boolean {
43
+ if (!aspectId || typeof aspectId !== 'string') throw new Error(`expect aspectId to be string, got ${aspectId}`);
44
+ const bitMapEntry = this.getBitmapEntry(id, { ignoreVersion: true });
45
+ const currentConfig = (bitMapEntry.config ||= {})[aspectId];
46
+ if (isEqual(currentConfig, config)) {
47
+ return false; // no changes
48
+ }
49
+ const getNewConfig = () => {
50
+ if (!config) return null;
51
+ if (!shouldMergeConfig) return config;
52
+ // should merge
53
+ if (!currentConfig) return config;
54
+ if (currentConfig === '-') return config;
55
+ // lodash merge performs a deep merge. (the native concatenation don't)
56
+ return merge(currentConfig, config);
57
+ };
58
+ const newConfig = getNewConfig();
59
+ if (newConfig) {
60
+ bitMapEntry.config[aspectId] = newConfig;
61
+ } else {
62
+ delete bitMapEntry.config[aspectId];
63
+ }
64
+ this.legacyBitMap.markAsChanged();
65
+
66
+ return true; // changes have been made
67
+ }
68
+
69
+ updateDefaultScope(oldScope: string, newScope: string) {
70
+ const changedId: ComponentID[] = [];
71
+ this.legacyBitMap.components.forEach((componentMap) => {
72
+ // only new components (not snapped/tagged) can be changed
73
+ if (componentMap.defaultScope === oldScope && !componentMap.id.hasVersion()) {
74
+ componentMap.defaultScope = newScope;
75
+ changedId.push(componentMap.id);
76
+ }
77
+ });
78
+ if (changedId.length) {
79
+ this.legacyBitMap.markAsChanged();
80
+ }
81
+ return changedId;
82
+ }
83
+
84
+ markAsChanged() {
85
+ this.legacyBitMap.markAsChanged();
86
+ }
87
+
88
+ removeComponentConfig(id: ComponentID, aspectId: string, markWithMinusIfNotExist: boolean): boolean {
89
+ if (!aspectId || typeof aspectId !== 'string') throw new Error(`expect aspectId to be string, got ${aspectId}`);
90
+ const bitMapEntry = this.getBitmapEntry(id, { ignoreVersion: true });
91
+ const currentConfig = (bitMapEntry.config ||= {})[aspectId];
92
+ if (currentConfig) {
93
+ delete bitMapEntry.config[aspectId];
94
+ } else {
95
+ if (!markWithMinusIfNotExist) {
96
+ return false; // no changes
97
+ }
98
+ bitMapEntry.config[aspectId] = REMOVE_EXTENSION_SPECIAL_SIGN;
99
+ }
100
+
101
+ this.legacyBitMap.markAsChanged();
102
+
103
+ return true; // changes have been made
104
+ }
105
+
106
+ removeEntireConfig(id: ComponentID): boolean {
107
+ const bitMapEntry = this.getBitmapEntry(id, { ignoreVersion: true });
108
+ if (!bitMapEntry.config) return false;
109
+ delete bitMapEntry.config;
110
+ this.legacyBitMap.markAsChanged();
111
+ return true;
112
+ }
113
+
114
+ setEntireConfig(id: ComponentID, config: Record<string, any>) {
115
+ const bitMapEntry = this.getBitmapEntry(id, { ignoreVersion: true });
116
+ bitMapEntry.config = config;
117
+ this.legacyBitMap.markAsChanged();
118
+ }
119
+
120
+ removeDefaultScope(id: ComponentID) {
121
+ const bitMapEntry = this.getBitmapEntry(id, { ignoreVersion: true });
122
+ if (bitMapEntry.defaultScope) {
123
+ delete bitMapEntry.defaultScope;
124
+ this.legacyBitMap.markAsChanged();
125
+ }
126
+ }
127
+
128
+ setDefaultScope(id: ComponentID, defaultScope: string) {
129
+ const bitMapEntry = this.getBitmapEntry(id, { ignoreVersion: true });
130
+ bitMapEntry.defaultScope = defaultScope;
131
+ bitMapEntry.id = bitMapEntry.id.changeDefaultScope(defaultScope);
132
+ this.legacyBitMap.markAsChanged();
133
+ }
134
+
135
+ /**
136
+ * write .bitmap object to the filesystem
137
+ * optionally pass a reason for the change to be saved in the local scope `bitmap-history-metadata.txt` file.
138
+ */
139
+ async write(reasonForChange?: string) {
140
+ await this.consumer.writeBitMap(reasonForChange);
141
+ }
142
+
143
+ /**
144
+ * get the data saved in the .bitmap file for this component-id.
145
+ * throws if not found
146
+ * @see this.getBitmapEntryIfExist
147
+ */
148
+ getBitmapEntry(id: ComponentID, { ignoreVersion }: GetBitMapComponentOptions = {}): ComponentMap {
149
+ return this.legacyBitMap.getComponent(id, { ignoreVersion });
150
+ }
151
+
152
+ getBitmapEntryIfExist(id: ComponentID, { ignoreVersion }: GetBitMapComponentOptions = {}): ComponentMap | undefined {
153
+ return this.legacyBitMap.getComponentIfExist(id, { ignoreVersion });
154
+ }
155
+
156
+ getAspectIdFromConfig(
157
+ componentId: ComponentID,
158
+ aspectId: ComponentID,
159
+ ignoreAspectVersion = false
160
+ ): string | undefined {
161
+ const bitMapEntry = this.getBitmapEntry(componentId);
162
+ const config = bitMapEntry.config;
163
+ if (!config) {
164
+ return undefined;
165
+ }
166
+ if (config[aspectId.toString()]) {
167
+ return aspectId.toString();
168
+ }
169
+ if (!ignoreAspectVersion) {
170
+ return undefined;
171
+ }
172
+ const allVersions = Object.keys(config).filter((id) => id.startsWith(`${aspectId.toStringWithoutVersion()}@`));
173
+ if (allVersions.length > 1) {
174
+ throw new BitError(
175
+ `error: the same aspect ${
176
+ aspectId.toStringWithoutVersion
177
+ } configured multiple times for "${componentId.toString()}"\n${allVersions.join('\n')}`
178
+ );
179
+ }
180
+ return allVersions.length === 1 ? allVersions[0] : undefined;
181
+ }
182
+
183
+ /**
184
+ * components that were not tagged yet are safe to rename them from the .bitmap file.
185
+ */
186
+ renameNewComponent(sourceId: ComponentID, targetId: ComponentID) {
187
+ const bitMapEntry = this.getBitmapEntry(sourceId);
188
+ if (bitMapEntry.id.hasVersion()) {
189
+ throw new Error(`unable to rename tagged or exported component: ${bitMapEntry.id.toString()}`);
190
+ }
191
+ if (sourceId.isEqual(targetId)) {
192
+ throw new Error(`source-id and target-id are equal: "${sourceId.toString()}"`);
193
+ }
194
+ if (sourceId.fullName !== targetId.fullName) {
195
+ this.legacyBitMap.removeComponent(bitMapEntry.id);
196
+ bitMapEntry.id = targetId;
197
+ this.legacyBitMap.setComponent(bitMapEntry.id, bitMapEntry);
198
+ }
199
+ if (sourceId.scope !== targetId.scope) {
200
+ this.setDefaultScope(sourceId, targetId.scope);
201
+ }
202
+ }
203
+
204
+ /**
205
+ * helpful when reaming an aspect and this aspect is used in the config of other components.
206
+ */
207
+ renameAspectInConfig(sourceId: ComponentID, targetId: ComponentID) {
208
+ this.legacyBitMap.components.forEach((componentMap) => {
209
+ const config = componentMap.config;
210
+ if (!config) return;
211
+ Object.keys(config).forEach((aspectId) => {
212
+ if (aspectId === sourceId.toString()) {
213
+ config[targetId.toString()] = config[aspectId];
214
+ delete config[aspectId];
215
+ this.markAsChanged();
216
+ }
217
+ if (aspectId === EnvsAspect.id) {
218
+ const envConfig = config[aspectId];
219
+ if (envConfig !== REMOVE_EXTENSION_SPECIAL_SIGN && envConfig.env === sourceId.toString()) {
220
+ envConfig.env = targetId.toString();
221
+ this.markAsChanged();
222
+ }
223
+ }
224
+ });
225
+ componentMap.config = config;
226
+ });
227
+ }
228
+
229
+ removeComponent(id: ComponentID) {
230
+ this.legacyBitMap.removeComponent(id);
231
+ }
232
+
233
+ /**
234
+ * this is the lane-id of the recently exported lane. in case of a new lane, which was not exported yet, this will be
235
+ * empty.
236
+ */
237
+ getExportedLaneId(): LaneId | undefined {
238
+ return this.legacyBitMap.isLaneExported ? this.legacyBitMap.laneId : undefined;
239
+ }
240
+
241
+ makeComponentsAvailableOnMain(ids: ComponentID[]) {
242
+ ids.forEach((id) => {
243
+ const componentMap = this.getBitmapEntry(id);
244
+ componentMap.isAvailableOnCurrentLane = true;
245
+ delete componentMap.onLanesOnly;
246
+ });
247
+ this.legacyBitMap.markAsChanged();
248
+ }
249
+
250
+ /**
251
+ * whether .bitmap file has changed in-memory
252
+ */
253
+ hasChanged(): boolean {
254
+ return this.legacyBitMap.hasChanged;
255
+ }
256
+
257
+ takeSnapshot(): ComponentMap[] {
258
+ return this.legacyBitMap.components.map((comp) => comp.clone());
259
+ }
260
+
261
+ restoreFromSnapshot(componentMaps: ComponentMap[]) {
262
+ this.legacyBitMap.components = componentMaps;
263
+ this.legacyBitMap._invalidateCache();
264
+ }
265
+
266
+ /**
267
+ * .bitmap file could be changed by other sources (e.g. manually or by "git pull") not only by bit.
268
+ * this method returns the timestamp when the .bitmap has changed through bit. (e.g. as part of snap/tag/export/merge
269
+ * process)
270
+ */
271
+ async getLastModifiedBitmapThroughBit(): Promise<number | undefined> {
272
+ const bitmapHistoryDir = this.consumer.getBitmapHistoryDir();
273
+ const stat = await getPathStatIfExist(bitmapHistoryDir);
274
+ if (!stat) return undefined;
275
+ return stat.mtimeMs;
276
+ }
277
+ }