@teambit/objects 0.0.0-00042bc99514ea12d897f81bcd0181e2b034c615

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 (121) hide show
  1. package/dist/fixtures/version-model-extended.json +48 -0
  2. package/dist/fixtures/version-model-object.json +87 -0
  3. package/dist/index.d.ts +19 -0
  4. package/dist/index.js +371 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/models/dependencies-graph.d.ts +46 -0
  7. package/dist/models/dependencies-graph.js +105 -0
  8. package/dist/models/dependencies-graph.js.map +1 -0
  9. package/dist/models/detach-heads.d.ts +25 -0
  10. package/dist/models/detach-heads.js +84 -0
  11. package/dist/models/detach-heads.js.map +1 -0
  12. package/dist/models/export-metadata.d.ts +24 -0
  13. package/dist/models/export-metadata.js +74 -0
  14. package/dist/models/export-metadata.js.map +1 -0
  15. package/dist/models/index.d.ts +10 -0
  16. package/dist/models/index.js +125 -0
  17. package/dist/models/index.js.map +1 -0
  18. package/dist/models/lane-history.d.ts +43 -0
  19. package/dist/models/lane-history.js +131 -0
  20. package/dist/models/lane-history.js.map +1 -0
  21. package/dist/models/lane-history.spec.d.ts +1 -0
  22. package/dist/models/lane-history.spec.js +46 -0
  23. package/dist/models/lane-history.spec.js.map +1 -0
  24. package/dist/models/lane.d.ts +128 -0
  25. package/dist/models/lane.js +485 -0
  26. package/dist/models/lane.js.map +1 -0
  27. package/dist/models/model-component.d.ts +338 -0
  28. package/dist/models/model-component.js +1509 -0
  29. package/dist/models/model-component.js.map +1 -0
  30. package/dist/models/model-component.spec.d.ts +1 -0
  31. package/dist/models/model-component.spec.js +71 -0
  32. package/dist/models/model-component.spec.js.map +1 -0
  33. package/dist/models/scopeMeta.d.ts +20 -0
  34. package/dist/models/scopeMeta.js +68 -0
  35. package/dist/models/scopeMeta.js.map +1 -0
  36. package/dist/models/source.d.ts +10 -0
  37. package/dist/models/source.js +42 -0
  38. package/dist/models/source.js.map +1 -0
  39. package/dist/models/symlink.d.ts +30 -0
  40. package/dist/models/symlink.js +91 -0
  41. package/dist/models/symlink.js.map +1 -0
  42. package/dist/models/version-history.d.ts +59 -0
  43. package/dist/models/version-history.js +296 -0
  44. package/dist/models/version-history.js.map +1 -0
  45. package/dist/models/version.d.ts +288 -0
  46. package/dist/models/version.js +780 -0
  47. package/dist/models/version.js.map +1 -0
  48. package/dist/models/version.spec.d.ts +1 -0
  49. package/dist/models/version.spec.js +332 -0
  50. package/dist/models/version.spec.js.map +1 -0
  51. package/dist/objects/bit-object-list.d.ts +24 -0
  52. package/dist/objects/bit-object-list.js +65 -0
  53. package/dist/objects/bit-object-list.js.map +1 -0
  54. package/dist/objects/index.d.ts +5 -0
  55. package/dist/objects/index.js +60 -0
  56. package/dist/objects/index.js.map +1 -0
  57. package/dist/objects/object-list-to-graph.d.ts +13 -0
  58. package/dist/objects/object-list-to-graph.js +93 -0
  59. package/dist/objects/object-list-to-graph.js.map +1 -0
  60. package/dist/objects/object-list.d.ts +58 -0
  61. package/dist/objects/object-list.js +389 -0
  62. package/dist/objects/object-list.js.map +1 -0
  63. package/dist/objects/object.d.ts +35 -0
  64. package/dist/objects/object.js +189 -0
  65. package/dist/objects/object.js.map +1 -0
  66. package/dist/objects/objects-readable-generator.d.ts +31 -0
  67. package/dist/objects/objects-readable-generator.js +203 -0
  68. package/dist/objects/objects-readable-generator.js.map +1 -0
  69. package/dist/objects/raw-object.d.ts +23 -0
  70. package/dist/objects/raw-object.js +145 -0
  71. package/dist/objects/raw-object.js.map +1 -0
  72. package/dist/objects/ref.d.ts +14 -0
  73. package/dist/objects/ref.js +45 -0
  74. package/dist/objects/ref.js.map +1 -0
  75. package/dist/objects/repository.d.ts +165 -0
  76. package/dist/objects/repository.js +866 -0
  77. package/dist/objects/repository.js.map +1 -0
  78. package/dist/objects/scope-index.d.ts +74 -0
  79. package/dist/objects/scope-index.js +255 -0
  80. package/dist/objects/scope-index.js.map +1 -0
  81. package/dist/objects/scope-index.spec.d.ts +1 -0
  82. package/dist/objects/scope-index.spec.js +152 -0
  83. package/dist/objects/scope-index.spec.js.map +1 -0
  84. package/dist/objects.aspect.d.ts +2 -0
  85. package/dist/objects.aspect.js +18 -0
  86. package/dist/objects.aspect.js.map +1 -0
  87. package/dist/objects.main.runtime.d.ts +7 -0
  88. package/dist/objects.main.runtime.js +36 -0
  89. package/dist/objects.main.runtime.js.map +1 -0
  90. package/dist/preview-1781548568469.js +7 -0
  91. package/fixtures/version-model-extended.json +48 -0
  92. package/fixtures/version-model-object.json +87 -0
  93. package/models/dependencies-graph.ts +120 -0
  94. package/models/detach-heads.ts +79 -0
  95. package/models/export-metadata.ts +56 -0
  96. package/models/index.ts +11 -0
  97. package/models/lane-history.spec.ts +35 -0
  98. package/models/lane-history.ts +131 -0
  99. package/models/lane.ts +400 -0
  100. package/models/model-component.spec.ts +55 -0
  101. package/models/model-component.ts +1522 -0
  102. package/models/scopeMeta.ts +58 -0
  103. package/models/source.ts +31 -0
  104. package/models/symlink.ts +66 -0
  105. package/models/version-history.ts +283 -0
  106. package/models/version.spec.ts +280 -0
  107. package/models/version.ts +821 -0
  108. package/objects/bit-object-list.ts +59 -0
  109. package/objects/index.ts +6 -0
  110. package/objects/object-list-to-graph.ts +69 -0
  111. package/objects/object-list.ts +327 -0
  112. package/objects/object.ts +152 -0
  113. package/objects/objects-readable-generator.ts +174 -0
  114. package/objects/raw-object.ts +132 -0
  115. package/objects/ref.ts +45 -0
  116. package/objects/repository.ts +780 -0
  117. package/objects/scope-index.spec.ts +95 -0
  118. package/objects/scope-index.ts +197 -0
  119. package/package.json +97 -0
  120. package/types/asset.d.ts +41 -0
  121. package/types/style.d.ts +42 -0
@@ -0,0 +1,1522 @@
1
+ import { forEach, isEmpty, pickBy, mapValues, isEqual, clone } from 'lodash';
2
+ import { Mutex } from 'async-mutex';
3
+ import * as semver from 'semver';
4
+ import { versionParser, isHash, isTag, isSnap, LATEST_VERSION } from '@teambit/component-version';
5
+ import { BitError } from '@teambit/bit-error';
6
+ import { LaneId, DEFAULT_LANE } from '@teambit/lane-id';
7
+ import { ComponentID, ComponentIdList } from '@teambit/component-id';
8
+ import pMapSeries from 'p-map-series';
9
+ import { pMapPool } from '@teambit/toolbox.promise.map-pool';
10
+ import { concurrentComponentsLimit } from '@teambit/harmony.modules.concurrency';
11
+ import type { LegacyComponentLog } from '@teambit/legacy-component-log';
12
+ import { findDuplications } from '@teambit/toolbox.array.duplications-finder';
13
+ import { BitId } from '@teambit/legacy-bit-id';
14
+ import { DEFAULT_BIT_RELEASE_TYPE, DEFAULT_BIT_VERSION, DEFAULT_LANGUAGE, Extensions } from '@teambit/legacy.constants';
15
+ import type { Dependencies, Dependency } from '@teambit/legacy.consumer-component';
16
+ import { ConsumerComponent, SchemaName } from '@teambit/legacy.consumer-component';
17
+ import { License, SourceFile, getRefsFromExtensions } from '@teambit/component.sources';
18
+ import { ComponentOverrides, getBindingPrefixByDefaultScope } from '@teambit/legacy.consumer-config';
19
+ import { ValidationError } from '@teambit/legacy.cli.error';
20
+ import { logger } from '@teambit/legacy.logger';
21
+ import { getStringifyArgs } from '@teambit/legacy.utils';
22
+ import { getLatestVersion, validateVersion } from '@teambit/pkg.modules.semver-helper';
23
+ import type { SnapsDistance } from '@teambit/component.snap-distance';
24
+ import {
25
+ getDivergeData,
26
+ getAllVersionParents,
27
+ getAllVersionsInfo,
28
+ getVersionParentsFromVersion,
29
+ } from '@teambit/component.snap-distance';
30
+ import {
31
+ ComponentObjects,
32
+ ComponentVersion,
33
+ HeadNotFound,
34
+ ParentNotFound,
35
+ VersionAlreadyExists,
36
+ VersionNotFound,
37
+ VersionNotFoundOnFS,
38
+ NoHeadNoVersion,
39
+ errorIsTypeOfMissingObject,
40
+ BitIdCompIdError,
41
+ } from '@teambit/legacy.scope';
42
+ import type { Repository } from '../objects';
43
+ import { BitObject, Ref } from '../objects';
44
+ import type Lane from './lane';
45
+ import ScopeMeta from './scopeMeta';
46
+ import type Source from './source';
47
+ import type Version from './version';
48
+ import type { VersionParents } from './version-history';
49
+ import VersionHistory from './version-history';
50
+ import type { ObjectItem } from '../objects/object-list';
51
+ import type { Scope } from '@teambit/legacy.scope';
52
+ import type { ExtensionDataList } from '@teambit/legacy.extension-data';
53
+ import { DetachedHeads } from './detach-heads';
54
+
55
+ type State = {
56
+ versions?: {
57
+ [version: string]: {
58
+ local?: boolean; // whether a component was changed locally
59
+ };
60
+ };
61
+ };
62
+
63
+ export type AddVersionOpts = {
64
+ addToUpdateDependentsInLane?: boolean;
65
+
66
+ /**
67
+ * kind of rebase.
68
+ * if true, set the head as the parent of the new version.
69
+ * by default, the parent is the currently used version in .bitmap.
70
+ * (this prop takes affect only when the component is checked out to an older version)
71
+ */
72
+ setHeadAsParent?: boolean;
73
+
74
+ detachHead?: boolean;
75
+ overrideHead?: boolean;
76
+ };
77
+
78
+ type Versions = { [version: string]: Ref };
79
+ export type ScopeListItem = { url: string; name: string; date: string };
80
+
81
+ export type ComponentLog = LegacyComponentLog;
82
+
83
+ export type ComponentProps = {
84
+ scope: string;
85
+ name: string;
86
+ versions?: Versions;
87
+ orphanedVersions?: Versions;
88
+ lang: string;
89
+ deprecated: boolean;
90
+ bindingPrefix: string;
91
+ state?: State; // get deleted after export
92
+ scopesList?: ScopeListItem[];
93
+ head?: Ref;
94
+ schema?: string | undefined;
95
+ detachedHeads?: DetachedHeads;
96
+ };
97
+
98
+ export const VERSION_ZERO = '0.0.0';
99
+
100
+ /**
101
+ * we can't rename the class as ModelComponent because old components are already saved in the model
102
+ * with 'Component' in their headers. see object-registrar.types()
103
+ */
104
+ // TODO: FIX me .parser
105
+ export default class Component extends BitObject {
106
+ scope: string;
107
+ name: string;
108
+ versions: Versions;
109
+ orphanedVersions: Versions;
110
+ lang: string;
111
+ /**
112
+ * @deprecated moved to the Version object inside teambit/deprecation aspect
113
+ */
114
+ deprecated: boolean;
115
+ bindingPrefix: string;
116
+ /**
117
+ * @deprecated since 0.12.6 (long long ago :) probably can be removed)
118
+ */
119
+ local: boolean | null | undefined;
120
+ state: State;
121
+ scopesList: ScopeListItem[];
122
+ head?: Ref;
123
+ remoteHead?: Ref | null; // doesn't get saved in the scope, used to easier access the remote main head
124
+ /**
125
+ * doesn't get saved in the scope, used to easier access the local snap head data
126
+ * when checked out to a lane, this prop is either Ref or null. otherwise (when on main), this prop is undefined.
127
+ */
128
+ laneHeadLocal?: Ref | null;
129
+ /**
130
+ * doesn't get saved in the scope, used to easier access the remote snap head data
131
+ * when checked out to a lane, this prop is either Ref or null. otherwise (when on main), this prop is undefined.
132
+ */
133
+ laneHeadRemote?: Ref | null;
134
+
135
+ /**
136
+ * when checked out to a lane, calculate what should be the head on the remote.
137
+ * if the laneHeadRemote is null, for example, when the lane is new, then used the the lane it was forked from.
138
+ * it no head is found on the lane/forked, then use the component.head.
139
+ */
140
+ calculatedRemoteHeadWhenOnLane?: Ref | null;
141
+
142
+ laneId?: LaneId; // doesn't get saved in the scope.
143
+ laneDataIsPopulated = false; // doesn't get saved in the scope, used to improve performance of loading the lane data
144
+ schema: string | undefined;
145
+ detachedHeads: DetachedHeads;
146
+ private divergeData?: SnapsDistance;
147
+ private _populateVersionHistoryMutex?: Mutex;
148
+ constructor(props: ComponentProps) {
149
+ super();
150
+ if (!props.name) throw new TypeError('Model Component constructor expects to get a name parameter');
151
+ if (!props.scope) {
152
+ throw new BitIdCompIdError(props.name);
153
+ }
154
+ this.scope = props.scope;
155
+ this.name = props.name;
156
+ this.versions = props.versions || {};
157
+ this.orphanedVersions = props.orphanedVersions || {};
158
+ this.lang = props.lang || DEFAULT_LANGUAGE;
159
+ this.deprecated = props.deprecated || false;
160
+ this.bindingPrefix = props.bindingPrefix || getBindingPrefixByDefaultScope(props.scope);
161
+ this.state = props.state || {};
162
+ this.scopesList = props.scopesList || [];
163
+ this.head = props.head;
164
+ this.schema = props.schema;
165
+ this.detachedHeads = props.detachedHeads || new DetachedHeads();
166
+ }
167
+
168
+ private get populateVersionHistoryMutex() {
169
+ if (!this._populateVersionHistoryMutex) {
170
+ this._populateVersionHistoryMutex = new Mutex();
171
+ }
172
+ return this._populateVersionHistoryMutex;
173
+ }
174
+
175
+ get versionArray(): Ref[] {
176
+ return Object.values(this.versions);
177
+ }
178
+
179
+ setVersion(tag: string, ref: Ref) {
180
+ this.versions[tag] = ref;
181
+ delete this.orphanedVersions[tag]; // just in case it's there.
182
+ }
183
+
184
+ setOrphanedVersion(tag: string, ref: Ref) {
185
+ if (this.versions[tag]) {
186
+ throw new Error(
187
+ `unable to save orphanedVersion "${tag}" for "${this.id()}" because this tag is already part of the versions prop`
188
+ );
189
+ }
190
+ this.orphanedVersions[tag] = ref;
191
+ }
192
+
193
+ getRef(version: string): Ref | null {
194
+ if (isTag(version)) {
195
+ return this.versionsIncludeOrphaned[version];
196
+ }
197
+ if (isHash(version)) {
198
+ return new Ref(version);
199
+ }
200
+ return null;
201
+ }
202
+
203
+ getHeadStr(): string | null {
204
+ return this.head ? this.head.toString() : null;
205
+ }
206
+
207
+ getHead(): Ref | undefined {
208
+ return this.head;
209
+ }
210
+
211
+ /**
212
+ * returns the head hash. regardless of whether current lane is the default or not.
213
+ * if on a lane, it returns the head of the component on the lane.
214
+ */
215
+ getHeadRegardlessOfLane(): Ref | undefined {
216
+ return this.laneHeadLocal || this.getHead();
217
+ }
218
+
219
+ getHeadAsTagIfExist(): string | undefined {
220
+ if (!this.head) return undefined;
221
+ return this.getTagOfRefIfExists(this.head) || this.head.toString();
222
+ }
223
+
224
+ hasHead() {
225
+ return Boolean(this.head);
226
+ }
227
+
228
+ setHead(head: Ref | undefined) {
229
+ this.head = head;
230
+ }
231
+
232
+ listVersions(sort?: 'ASC' | 'DESC'): string[] {
233
+ const versions = Object.keys(this.versions);
234
+ if (!sort) return versions;
235
+ if (sort === 'ASC') {
236
+ return versions.sort(semver.compare);
237
+ }
238
+
239
+ return versions.sort(semver.compare).reverse();
240
+ }
241
+
242
+ listVersionsIncludeOrphaned(sort?: 'ASC' | 'DESC'): string[] {
243
+ const versions = Object.keys(this.versionsIncludeOrphaned);
244
+ if (!sort) return versions;
245
+ if (sort === 'ASC') {
246
+ return versions.sort(semver.compare);
247
+ }
248
+
249
+ return versions.sort(semver.compare).reverse();
250
+ }
251
+
252
+ async hasVersion(version: string, repo: Repository, includeOrphaned = true): Promise<boolean> {
253
+ if (isTag(version)) {
254
+ return includeOrphaned ? this.hasTagIncludeOrphaned(version) : this.hasTag(version);
255
+ }
256
+ const head = this.getHeadRegardlessOfLane();
257
+ if (!head) {
258
+ return false;
259
+ }
260
+ const versionParents = await getAllVersionParents({ repo, modelComponent: this, heads: [head] });
261
+ // we use "startsWith" because it can be a short hash
262
+ return versionParents.map((v) => v.hash).some((hash) => hash.toString().startsWith(version));
263
+ }
264
+
265
+ hasTag(version: string): boolean {
266
+ return Boolean(this.versions[version]);
267
+ }
268
+
269
+ get versionsIncludeOrphaned(): Versions {
270
+ // for bit-bin with 266 components, it takes about 1,700ms. don't use lodash.merge, it's much faster
271
+ // but mutates `this.versions`.
272
+ return { ...this.versions, ...this.orphanedVersions };
273
+ }
274
+
275
+ hasTagIncludeOrphaned(version: string): boolean {
276
+ return Boolean(this.versions[version] || this.orphanedVersions[version]);
277
+ }
278
+
279
+ /**
280
+ * whether the head is a snap (not a tag)
281
+ */
282
+ isHeadSnap() {
283
+ const tagsHashes = this.versionArray.map((ref) => ref.toString());
284
+ return this.head && !tagsHashes.includes(this.head.toString());
285
+ }
286
+
287
+ /**
288
+ * add a new remote if it is not there already
289
+ */
290
+ addScopeListItem(scopeListItem: ScopeListItem): void {
291
+ if (!scopeListItem.name || !scopeListItem.url || !scopeListItem.date) {
292
+ throw new TypeError(
293
+ `model-component.addRemote get an invalid remote. name: ${scopeListItem.name}, url: ${scopeListItem.url}, date: ${scopeListItem.date}`
294
+ );
295
+ }
296
+ if (!this.scopesList.find((r) => r.url === scopeListItem.url)) {
297
+ this.scopesList.push(scopeListItem);
298
+ }
299
+ }
300
+
301
+ /**
302
+ * on main - it checks local-head (or .bitmap version if given) vs remote-head.
303
+ * on lane - it checks local-head on lane vs remote-head on lane.
304
+ * however, to get an accurate `divergeData.snapsOnSourceOnly`, the above is not enough.
305
+ * for example, comp-a@snap-x from lane-a is merged into lane-b. we don't want this snap-x to be "local", because
306
+ * then, bit-status will show it as "staged" and bit-reset will remove it unexpectedly.
307
+ * if we only check by the local-head and remote-head on lane, it'll be local because the remote-head of lane-b is empty.
308
+ * to address this, we search all remote-refs files for this bit-id and during the local history traversal, if a hash
309
+ * is found there, it'll stop the traversal and not mark it as remote.
310
+ * in this example, during the merge, lane-a was fetched, and the remote-ref of this lane has snap-x as the head.
311
+ */
312
+ async setDivergeData(repo: Repository, throws = true, fromCache = true, workspaceId?: ComponentID): Promise<void> {
313
+ if (!this.divergeData || !fromCache) {
314
+ const remoteHead = (this.laneId ? this.calculatedRemoteHeadWhenOnLane : this.remoteHead) || null;
315
+ // this is for detach-head scenario. it can happen on main only. we want to compare against the .bitmap
316
+ // version (which is the detached head) and not the actual head.
317
+ const workspaceVersion = !this.isOnLane() && workspaceId?.hasVersion() ? workspaceId.version : null;
318
+ this.divergeData = await getDivergeData({
319
+ repo,
320
+ modelComponent: this,
321
+ targetHead: remoteHead,
322
+ sourceHead: workspaceVersion ? this.getRef(workspaceVersion) : undefined,
323
+ throws,
324
+ });
325
+ }
326
+ }
327
+
328
+ isOnLane(): boolean {
329
+ return Boolean(this.laneHeadLocal || this.laneHeadLocal === null);
330
+ }
331
+
332
+ /**
333
+ * this is used (among others) by `bit status` to check whether snaps are local (staged), for `bit reset` to remove them
334
+ * and for `bit export` to push them. for "merge pending" status, use `this.getDivergeDataForMergePending()`.
335
+ */
336
+ getDivergeData(): SnapsDistance {
337
+ if (!this.divergeData)
338
+ throw new Error(
339
+ `getDivergeData() expects divergeData to be populate, please use this.setDivergeData() for id: ${this.id()}`
340
+ );
341
+ return this.divergeData;
342
+ }
343
+
344
+ /**
345
+ * don't use modelComponent.getDivergeData() because in some scenarios when on a lane, it compares the head
346
+ * on the lane against the head on the main, which could show the component as diverged incorrectly.
347
+ */
348
+ async getDivergeDataForMergePending(repo: Repository) {
349
+ return getDivergeData({
350
+ repo,
351
+ modelComponent: this,
352
+ targetHead: (this.laneId ? this.laneHeadRemote : this.remoteHead) || null,
353
+ throws: false,
354
+ });
355
+ }
356
+
357
+ async populateLocalAndRemoteHeads(repo: Repository, lane?: Lane) {
358
+ this.setLaneHeadLocal(lane);
359
+ if (lane) this.laneId = lane.toLaneId();
360
+ if (!this.scope) {
361
+ return; // no remote to update. it's local.
362
+ }
363
+ this.remoteHead = await repo.remoteLanes.getRef(LaneId.from(DEFAULT_LANE, this.scope), this.toComponentId());
364
+ if (!lane) {
365
+ return;
366
+ }
367
+ this.laneHeadRemote = lane.isNew ? null : await repo.remoteLanes.getRef(lane.toLaneId(), this.toComponentId());
368
+
369
+ const calculateRemote = async () => {
370
+ if (this.laneHeadRemote) return this.laneHeadRemote;
371
+ if (lane.isNew && lane.forkedFrom) {
372
+ // For any forked lane — same-scope or cross-scope (e.g. after `bit lane change-scope`) — use
373
+ // the forked-from lane's head as the divergence baseline. The consumer has that ref locally
374
+ // from when they ran `bit lane import` on the original lane. This is correct for both:
375
+ // - same-scope forks: identical to the previous behavior.
376
+ // - cross-scope forks: previously fell through to `this.remoteHead || this.head`, which can
377
+ // crash with `TargetHeadNotFound` when the component's main-head Version isn't local
378
+ // (common after a lean-lane import since main history doesn't live on the lane scope).
379
+ // Returning the fork's head instead reports only true local snaps as staged — not the
380
+ // entire history — which also keeps `bit reset` from over-removing.
381
+ const headFromFork = await repo.remoteLanes.getRef(lane.forkedFrom, this.toComponentId());
382
+ if (headFromFork) return headFromFork;
383
+ if (lane.forkedFrom.scope !== lane.scope) {
384
+ // Cross-scope fork and the forked-from ref isn't local. Returning null over-reports
385
+ // the lane history as staged (divergence has no baseline), but falling through to
386
+ // `this.remoteHead || this.head` would crash with TargetHeadNotFound when the main-
387
+ // head Version is missing locally. The user can recover by running `bit lane fetch`
388
+ // on the forked-from lane to populate the ref.
389
+ return null;
390
+ }
391
+ // Same-scope fork without a fork ref — fall through to the standard fallback below.
392
+ }
393
+ // if no remote-ref was found, because it's checked out to a lane, it's safe to assume that
394
+ // this.head should be on the original-remote. hence, FetchMissingHistory will retrieve it on lane-remote
395
+ return this.remoteHead || this.head;
396
+ };
397
+
398
+ this.calculatedRemoteHeadWhenOnLane = await calculateRemote();
399
+ }
400
+
401
+ setLaneHeadLocal(lane?: Lane) {
402
+ if (lane) {
403
+ // include lane.updateDependents — hidden cascade entries need a lane-local head so the
404
+ // export-pending detector picks them up after a workspace cascade snap.
405
+ this.laneHeadLocal = lane.getCompHeadIncludeUpdateDependents(this.toComponentId()) || null;
406
+ }
407
+ }
408
+
409
+ /**
410
+ * returns only the versions that exist in both components (regardless whether the hash are the same)
411
+ * e.g. this.component = [0.0.1, 0.0.2, 0.0.3], other component = [0.0.3, 0.0.4]. it returns only [0.0.3].
412
+ * also, in case it is coming from 'bit import', the version must be locally changed.
413
+ * otherwise, it doesn't matter whether the hashes are different.
414
+ */
415
+ _getComparableVersionsObjects(
416
+ otherComponent: Component, // in case of merging, the otherComponent is the existing component, and "this" is the incoming component
417
+ local: boolean // for 'bit import' the local is true, for 'bit export' the local is false
418
+ ): { thisComponentVersions: Versions; otherComponentVersions: Versions } {
419
+ const otherLocalVersion = otherComponent.getLocalVersions();
420
+ const otherComponentVersions = pickBy(
421
+ otherComponent.versions,
422
+ (val, key) => Object.keys(this.versions).includes(key) && (!local || otherLocalVersion.includes(key))
423
+ );
424
+ const thisComponentVersions = pickBy(
425
+ this.versions,
426
+ (val, key) => Object.keys(otherComponentVersions).includes(key) && (!local || otherLocalVersion.includes(key))
427
+ );
428
+ return { thisComponentVersions, otherComponentVersions };
429
+ }
430
+
431
+ compatibleWith(component: Component, local: boolean): boolean {
432
+ const { thisComponentVersions, otherComponentVersions } = this._getComparableVersionsObjects(component, local);
433
+ return isEqual(thisComponentVersions, otherComponentVersions);
434
+ }
435
+
436
+ diffWith(component: Component, local: boolean): string[] {
437
+ const { thisComponentVersions, otherComponentVersions } = this._getComparableVersionsObjects(component, local);
438
+ return Object.keys(thisComponentVersions).filter(
439
+ (version) => thisComponentVersions[version].hash !== otherComponentVersions[version].hash
440
+ );
441
+ }
442
+
443
+ isEmpty() {
444
+ return isEmpty(this.versions) && !this.hasHead();
445
+ }
446
+
447
+ /**
448
+ * on main return main head, on lane, return lane head.
449
+ * if the head is also a tag, return the tag, otherwise, return the hash.
450
+ */
451
+ getHeadRegardlessOfLaneAsTagOrHash(returnVersionZeroForNoHead = false): string {
452
+ const head = this.getHeadRegardlessOfLane();
453
+ if (!head) {
454
+ if (!isEmpty(this.versions))
455
+ throw new Error(`error: ${this.id()} has tags but no head, it might be originated from legacy`);
456
+ if (returnVersionZeroForNoHead) return VERSION_ZERO;
457
+ throw new Error(`getHeadRegardlessOfLaneAsTagOrHash() failed finding a head for ${this.id()}`);
458
+ }
459
+ return this.getTagOfRefIfExists(head) || head.toString();
460
+ }
461
+
462
+ /**
463
+ * get the recent head. if locally is ahead, return the local head. otherwise, return the remote head.
464
+ *
465
+ * a user can be checked out to a lane, in which case, `this.laneHeadLocal` and `this.laneHeadRemote`
466
+ * may be populated.
467
+ * `this.head` may not be populated, e.g. when a component was created on
468
+ * this lane and never got snapped on main.
469
+ * it's impossible that `this.head.isEqual(this.laneHeadLocal)`, because when snapping it's either
470
+ * on main, which goes to this.head OR on a lane, which goes to this.laneHeadLocal.
471
+ */
472
+ async headIncludeRemote(repo: Repository): Promise<string> {
473
+ const latestLocally = this.getHeadRegardlessOfLaneAsTagOrHash(true);
474
+ const remoteHead = this.laneHeadRemote || this.remoteHead;
475
+ if (!remoteHead) return latestLocally;
476
+ if (!this.getHeadRegardlessOfLane()) {
477
+ return remoteHead.toString(); // in case a snap was created on another lane
478
+ }
479
+
480
+ // either a user is on main or a lane, check whether the remote is ahead of the local
481
+ if (this.laneId && !this.laneHeadRemote) {
482
+ // when on a lane, setDivergeData is using the `this.calculatedRemoteHeadWhenOnLane`,
483
+ // which takes into account main-head and forked-head. here, we don't want this. we care only about the
484
+ // remote-lane head.
485
+ return latestLocally;
486
+ }
487
+ await this.setDivergeData(repo, false);
488
+ const divergeData = this.getDivergeData();
489
+ if (divergeData.isTargetAhead()) {
490
+ return this.getTagOfRefIfExists(remoteHead) || remoteHead.toString();
491
+ }
492
+ return latestLocally;
493
+ }
494
+
495
+ async getRefOfAncestor(repo: Repository, generationsToGoBack: number): Promise<Ref> {
496
+ const head = this.getHeadRegardlessOfLane();
497
+ if (!head) throw new BitError(`getRefOfAncestor failed to find the head of ${this.id()}`);
498
+ const versionHistory = await this.getAndPopulateVersionHistory(repo, head);
499
+ return versionHistory.getAncestor(generationsToGoBack, head);
500
+ }
501
+
502
+ latestVersion(): string {
503
+ if (isEmpty(this.versions)) return VERSION_ZERO;
504
+ return getLatestVersion(this.listVersions());
505
+ }
506
+
507
+ latestVersionIfExist(): string | undefined {
508
+ if (isEmpty(this.versions)) return undefined;
509
+ return getLatestVersion(this.listVersions());
510
+ }
511
+
512
+ // @todo: make it readable, it's a mess
513
+ isLatestGreaterThan(version: string | null | undefined): boolean {
514
+ if (!version) throw TypeError('isLatestGreaterThan expect to get a Version');
515
+ const latest = this.getHeadRegardlessOfLaneAsTagOrHash(true);
516
+ if (this.isEmpty() && !this.calculatedRemoteHeadWhenOnLane) {
517
+ return false; // in case a snap was created on another lane
518
+ }
519
+ if (isTag(latest) && isTag(version)) {
520
+ return semver.gt(latest, version);
521
+ }
522
+ if (latest === version) return false;
523
+ const latestRef = this.getRef(latest);
524
+ if (!latestRef) throw new Error('isLatestGreaterThan, latestRef was not found');
525
+ const latestHash = latestRef.toString();
526
+ const versionRef = this.getRef(version);
527
+ if (!versionRef) return true; // probably a child
528
+ const versionHash = versionRef.toString();
529
+ if (latestHash === versionHash) return false;
530
+ return true;
531
+ }
532
+
533
+ /**
534
+ * Return the lateset version which actuall exists in the scope
535
+ * (exists means the object itself exists)
536
+ * This relevant for cases when the component version array has few versions
537
+ * but we don't have all the refs in the object
538
+ *
539
+ * @returns {number}
540
+ * @memberof Component
541
+ */
542
+ latestExisting(repository: Repository): string {
543
+ if (isEmpty(this.versions)) return VERSION_ZERO;
544
+ const versions = this.listVersions('ASC');
545
+ let version = null;
546
+ let versionStr = null;
547
+ while (!version && versions && versions.length) {
548
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
549
+ versionStr = versions.pop();
550
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
551
+ version = this.loadVersionSync(versionStr, repository, false);
552
+ }
553
+ return versionStr || VERSION_ZERO;
554
+ }
555
+
556
+ /**
557
+ * get component log and sort by the timestamp in ascending order (from the earliest to the latest)
558
+ */
559
+ async collectLogs(scope: Scope, shortHash = false, startFrom?: Ref): Promise<ComponentLog[]> {
560
+ const repo = scope.objects;
561
+ let versionsInfo = await getAllVersionsInfo({ modelComponent: this, repo, throws: false, startFrom });
562
+
563
+ // due to recent changes of getting version-history object rather than fetching the entire history, some version
564
+ // objects might be missing. import the component from the remote
565
+ if (
566
+ versionsInfo.some((v) => v.error && errorIsTypeOfMissingObject(v.error)) &&
567
+ this.scope !== repo.scopeJson.name
568
+ ) {
569
+ logger.info(`collectLogs is unable to find some objects for ${this.id()}. will try to import them`);
570
+ try {
571
+ const lane = await scope.getCurrentLaneObject();
572
+ await scope.scopeImporter.importWithoutDeps(
573
+ ComponentIdList.fromArray([this.toComponentId()]).toVersionLatest(),
574
+ {
575
+ cache: false,
576
+ includeVersionHistory: true,
577
+ collectParents: true,
578
+ lane: lane || undefined,
579
+ reason: 'to collect logs (including parents)',
580
+ }
581
+ );
582
+ versionsInfo = await getAllVersionsInfo({ modelComponent: this, repo, throws: false, startFrom });
583
+ // Lean-lane-scope fallback: if the lane is on a different scope from the component's
584
+ // home scope (e.g. a feature lane for a component that lives on main in another scope),
585
+ // older main snaps may not be on the lane scope. Re-fetch without lane so the fetcher
586
+ // routes to the component's home scope and brings in the missing main history.
587
+ if (
588
+ lane &&
589
+ lane.scope !== this.scope &&
590
+ versionsInfo.some((v) => v.error && errorIsTypeOfMissingObject(v.error))
591
+ ) {
592
+ await scope.scopeImporter.importWithoutDeps(
593
+ ComponentIdList.fromArray([this.toComponentId()]).toVersionLatest(),
594
+ {
595
+ cache: false,
596
+ includeVersionHistory: true,
597
+ collectParents: true,
598
+ reason: 'to collect logs from component home scope (lean-lane-scope fallback)',
599
+ }
600
+ );
601
+ versionsInfo = await getAllVersionsInfo({ modelComponent: this, repo, throws: false, startFrom });
602
+ }
603
+ } catch (err) {
604
+ logger.error(`collectLogs failed to import ${this.id()} history`, err);
605
+ }
606
+ }
607
+
608
+ const head = this.getHeadRegardlessOfLane();
609
+ const headVersion = head ? ((await repo.load(head)) as unknown as Version) : undefined;
610
+ const removeAspect = headVersion?.extensions.findCoreExtension(Extensions.remove);
611
+ const removeRange = removeAspect?.config.range;
612
+ const removeSnaps = removeAspect?.config.snaps || [];
613
+ const deprecationAspect = headVersion?.extensions.findCoreExtension(Extensions.deprecation);
614
+ const deprecationRange = deprecationAspect?.config.range;
615
+
616
+ const getRef = (ref: Ref) => (shortHash ? ref.toShortString() : ref.toString());
617
+ const results = versionsInfo.map((versionInfo) => {
618
+ const log = versionInfo.version ? versionInfo.version.log : { message: '<no-data-available>' };
619
+ return {
620
+ ...log, // @ts-ignore
621
+ username: log?.username || 'unknown',
622
+ // @ts-ignore
623
+ email: log?.email || 'unknown',
624
+ tag: versionInfo.tag,
625
+ hash: getRef(versionInfo.ref),
626
+ parents: versionInfo.parents.map((parent) => getRef(parent)),
627
+ onLane: versionInfo.onLane,
628
+ deleted:
629
+ (versionInfo.tag && removeRange && semver.satisfies(versionInfo.tag, removeRange)) ||
630
+ (!versionInfo.tag && removeSnaps.includes(versionInfo.ref.toString())),
631
+ deprecated: versionInfo.tag && deprecationRange && semver.satisfies(versionInfo.tag, deprecationRange),
632
+ hidden: versionInfo.version?.hidden,
633
+ };
634
+ });
635
+ // sort from earliest to latest
636
+ const sorted = results.sort((a: ComponentLog, b: ComponentLog) => {
637
+ // @ts-ignore
638
+ if (a.date && b.date) return a.date - b.date;
639
+ return 0;
640
+ });
641
+ return sorted;
642
+ }
643
+
644
+ collectVersions(repo: Repository): Promise<ConsumerComponent[]> {
645
+ return Promise.all(
646
+ this.listVersions().map((versionNum) => {
647
+ return this.toConsumerComponent(versionNum, this.scope, repo);
648
+ })
649
+ );
650
+ }
651
+
652
+ getTagOfRefIfExists(ref: Ref, allTags = this.versionsIncludeOrphaned): string | undefined {
653
+ return Object.keys(allTags).find((versionRef) => allTags[versionRef].isEqual(ref));
654
+ }
655
+
656
+ getTag(version: string): string | undefined {
657
+ if (isTag(version)) return version;
658
+ const ref = Ref.from(version);
659
+ return this.getTagOfRefIfExists(ref);
660
+ }
661
+
662
+ switchHashesWithTagsIfExist(refs: Ref[]): string[] {
663
+ // cache the this.versionsIncludeOrphaned results into "allTags", looks strange but it improved
664
+ // the performance on bit-bin with 188 components during source.merge in 4 seconds.
665
+ const allTags = this.versionsIncludeOrphaned;
666
+ return refs.map((ref) => this.getTagOfRefIfExists(ref, allTags) || ref.toString());
667
+ }
668
+
669
+ /**
670
+ * if exactVersion is defined, add exact version instead of using the semver mechanism
671
+ */
672
+ getVersionToAdd(
673
+ releaseType: semver.ReleaseType = DEFAULT_BIT_RELEASE_TYPE,
674
+ exactVersion?: string | null,
675
+ incrementBy?: number,
676
+ preReleaseId?: string
677
+ ): string {
678
+ if (exactVersion && this.versions[exactVersion]) {
679
+ throw new VersionAlreadyExists(exactVersion, this.id());
680
+ }
681
+ const version = exactVersion || this.version(releaseType, incrementBy, preReleaseId);
682
+ validateVersion(version);
683
+ return version;
684
+ }
685
+
686
+ isEqual(component: Component, considerOrphanedVersions = true): boolean {
687
+ if ((this.hasHead() && !component.hasHead()) || (!this.hasHead() && component.hasHead())) {
688
+ return false; // only one of them has head
689
+ }
690
+ if (this.head && component.head && !this.head.isEqual(component.head)) {
691
+ return false; // the head is not equal.
692
+ }
693
+ // the head is equal or they both don't have head. check the versions
694
+ if (this.versionArray.length !== component.versionArray.length) {
695
+ return false;
696
+ }
697
+ const hasSameVersions = Object.keys(this.versions).every(
698
+ (tag) => component.versions[tag] && component.versions[tag].isEqual(this.versions[tag])
699
+ );
700
+ if (considerOrphanedVersions) {
701
+ if (Object.keys(this.orphanedVersions).length !== Object.keys(component.orphanedVersions).length) {
702
+ return false;
703
+ }
704
+ const hasSameOrphanedVersions = Object.keys(this.orphanedVersions).every(
705
+ (tag) => component.orphanedVersions[tag] && component.orphanedVersions[tag].isEqual(this.orphanedVersions[tag])
706
+ );
707
+ if (!hasSameOrphanedVersions) {
708
+ return false;
709
+ }
710
+ }
711
+
712
+ return hasSameVersions;
713
+ }
714
+
715
+ // eslint-disable-next-line complexity
716
+ addVersion(
717
+ version: Version,
718
+ versionToAdd: string,
719
+ lane?: Lane,
720
+ previouslyUsedVersion?: string,
721
+ { addToUpdateDependentsInLane, setHeadAsParent, detachHead, overrideHead }: AddVersionOpts = {}
722
+ ): string {
723
+ if (detachHead && overrideHead) {
724
+ throw new Error(`addVersion expects either detachHead or overrideHead to be true, not both`);
725
+ }
726
+ if (lane) {
727
+ if (isTag(versionToAdd)) {
728
+ throw new BitError(
729
+ 'unable to tag when checked out to a lane, please switch to main, merge the lane and then tag again'
730
+ );
731
+ }
732
+ const currentBitId = this.toComponentId();
733
+ const versionToAddRef = Ref.from(versionToAdd);
734
+ const parent = previouslyUsedVersion ? this.getRef(previouslyUsedVersion) : null;
735
+ if (!parent) {
736
+ const existingComponentInLane = lane.getComponent(currentBitId);
737
+ const currentHead = (existingComponentInLane && existingComponentInLane.head) || this.getHead();
738
+ if (currentHead) {
739
+ throw new Error(
740
+ `component ${currentBitId.toString()} has a head (${currentHead.toString()}) but previouslyUsedVersion is empty`
741
+ );
742
+ }
743
+ }
744
+ if (parent && !parent.isEqual(versionToAddRef)) {
745
+ version.addAsOnlyParent(parent);
746
+ }
747
+ // When the caller didn't explicitly opt in or out, preserve the existing entry's bucket so
748
+ // a merge-from-main producing a new snap for a hidden updateDependent keeps it hidden
749
+ // rather than promoting it into workspace-tracked state.
750
+ const existingHidden = lane.findUpdateDependent(currentBitId);
751
+ const existingVisible = lane.getComponent(currentBitId);
752
+ const shouldBeHidden = addToUpdateDependentsInLane ?? (Boolean(existingHidden) && !existingVisible);
753
+ if (shouldBeHidden) {
754
+ if (existingVisible) lane.removeComponent(currentBitId);
755
+ lane.addComponentToUpdateDependents(currentBitId.changeVersion(versionToAddRef.toString()));
756
+ // Only brand-new hidden insertions raise the wire flag — that's the `_snap --update-dependents`
757
+ // path adding a component that wasn't already on the lane. Cascades update an existing
758
+ // hidden entry (wasAlreadyHidden=true) and must NOT raise the flag, otherwise origin would
759
+ // re-add entries the Cloud UI explicitly dropped.
760
+ if (!existingHidden) lane.setOverrideUpdateDependents(true);
761
+ } else {
762
+ if (existingHidden) lane.removeComponentFromUpdateDependentsIfExist(currentBitId);
763
+ lane.addComponent({
764
+ id: currentBitId,
765
+ head: versionToAddRef,
766
+ isDeleted: version.isRemoved(),
767
+ });
768
+ }
769
+
770
+ if (lane.readmeComponent && lane.readmeComponent.id.fullName === currentBitId.fullName) {
771
+ lane.setReadmeComponent(currentBitId);
772
+ }
773
+ this.laneHeadLocal = versionToAddRef;
774
+ return versionToAdd;
775
+ }
776
+ // user on main
777
+ const head = this.getHead();
778
+ const parent = previouslyUsedVersion ? this.getRef(previouslyUsedVersion) : null;
779
+ if (
780
+ head &&
781
+ head.toString() !== versionToAdd &&
782
+ !this.hasTag(versionToAdd) // happens with auto-snap
783
+ ) {
784
+ // if this is a tag and this tag exists, the same version was added before with a different hash.
785
+ // adding the current head into the parent will result in a non-exist hash in the parent.
786
+ // if this is a hash and it's the same hash as the current head, adding it as a parent
787
+ // results in a parent and a version has the same hash.
788
+ // @todo: fix it in a more elegant way
789
+ const parentToSet = setHeadAsParent ? head : parent;
790
+ version.addAsOnlyParent(parentToSet || head);
791
+ }
792
+ if (parent && head && !parent.isEqual(head) && !overrideHead) {
793
+ if (detachHead) this.detachedHeads.setHead(version.hash());
794
+ else
795
+ throw new Error(`unable to add a new version for "${this.id()}" on main.
796
+ this version started from an older version (${previouslyUsedVersion}), and not from the head (${head}).
797
+ please run "bit checkout head" to be up to date, then snap/tag your changes.
798
+ if this is done intentionally, you can use --detach-head (or --override-head if available), but make sure you understand the implications as this is an experimental feature that may not be fully stable.`);
799
+ } else {
800
+ this.setHead(version.hash());
801
+ this.detachedHeads.clearCurrent();
802
+ }
803
+ if (isTag(versionToAdd)) {
804
+ this.setVersion(versionToAdd, version.hash());
805
+ }
806
+ this.markVersionAsLocal(versionToAdd);
807
+ return versionToAdd;
808
+ }
809
+
810
+ version(releaseType: semver.ReleaseType = DEFAULT_BIT_RELEASE_TYPE, incrementBy = 1, preReleaseId?: string): string {
811
+ const increment = (ver: string) => {
812
+ try {
813
+ // don't use "semver.inc" function, it'll swallow the error and return null.
814
+ const incResult = new semver.SemVer(ver).inc(releaseType, preReleaseId);
815
+ return incResult.version;
816
+ } catch (err: any) {
817
+ throw new Error(`unable to increment version "${ver}" with releaseType "${releaseType}" and preReleaseId "${preReleaseId}".
818
+ Error from "semver": ${err.message}`);
819
+ }
820
+ };
821
+
822
+ const latest = this.latestVersion();
823
+ if (!latest) {
824
+ const isPreReleaseLike = ['prerelease', 'premajor', 'preminor', 'prepatch'].includes(releaseType);
825
+ return isPreReleaseLike ? increment(DEFAULT_BIT_VERSION) : DEFAULT_BIT_VERSION;
826
+ }
827
+ let result = increment(latest);
828
+ if (incrementBy === 1) return result;
829
+ for (let i = 1; i < incrementBy; i += 1) {
830
+ result = increment(result);
831
+ }
832
+ return result;
833
+ }
834
+
835
+ id(): string {
836
+ return this.scope ? [this.scope, this.name].join('/') : this.name;
837
+ }
838
+
839
+ /**
840
+ * @deprecated use toComponentId() instead
841
+ */
842
+ toBitId(): BitId {
843
+ return new BitId({ scope: this.scope, name: this.name });
844
+ }
845
+
846
+ toComponentId(): ComponentID {
847
+ if (!this.scope) throw new Error(`ModelComponent: scope is missing from "${this.name}"`);
848
+ return new ComponentID(this.toBitId());
849
+ }
850
+
851
+ /**
852
+ * @deprecated use toComponentIdWithLatestVersion() instead
853
+ */
854
+ toBitIdWithLatestVersion(): BitId {
855
+ return new BitId({ scope: this.scope, name: this.name, version: this.getHeadRegardlessOfLaneAsTagOrHash(true) });
856
+ }
857
+
858
+ toComponentIdWithLatestVersion(): ComponentID {
859
+ return ComponentID.fromObject({
860
+ scope: this.scope,
861
+ name: this.name,
862
+ version: this.getHeadRegardlessOfLaneAsTagOrHash(true),
863
+ });
864
+ }
865
+
866
+ toComponentIdWithHead(): ComponentID {
867
+ return ComponentID.fromObject({ scope: this.scope, name: this.name, version: this.head?.toString() });
868
+ }
869
+
870
+ toBitIdWithLatestVersionAllowNull(): ComponentID {
871
+ const id = this.toComponentIdWithLatestVersion();
872
+ return id.version === VERSION_ZERO ? id.changeVersion(undefined) : id;
873
+ }
874
+
875
+ toObject() {
876
+ function versions(vers: Versions) {
877
+ const obj = {};
878
+ forEach(vers, (ref, version) => {
879
+ obj[version] = ref.toString();
880
+ });
881
+ return obj;
882
+ }
883
+
884
+ const componentObject = {
885
+ name: this.name,
886
+ scope: this.scope,
887
+ versions: versions(this.versions),
888
+ lang: this.lang,
889
+ deprecated: this.deprecated,
890
+ bindingPrefix: this.bindingPrefix,
891
+ remotes: this.scopesList,
892
+ schema: this.schema,
893
+ detachedHeads: this.detachedHeads.toObject(),
894
+ };
895
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
896
+ if (this.local) componentObject.local = this.local;
897
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
898
+ if (!isEmpty(this.state)) componentObject.state = this.state;
899
+ // @ts-ignore
900
+ if (!isEmpty(this.orphanedVersions)) componentObject.orphanedVersions = versions(this.orphanedVersions);
901
+ const headStr = this.getHeadStr();
902
+ // @ts-ignore
903
+ if (headStr) componentObject.head = headStr;
904
+
905
+ return componentObject;
906
+ }
907
+
908
+ async loadVersion(versionStr: string, repository: Repository, throws = true): Promise<Version> {
909
+ const versionRef = this.getRef(versionStr);
910
+ if (!versionRef) throw new VersionNotFound(versionStr, this.id());
911
+ const version = await repository.load(versionRef, false);
912
+ if (!version && throws) throw new VersionNotFoundOnFS(versionStr, this.id());
913
+ return version as Version;
914
+ }
915
+
916
+ loadVersionSync(version: string, repository: Repository, throws = true): Version {
917
+ const versionRef = this.getRef(version);
918
+ if (!versionRef) throw new VersionNotFound(version, this.id());
919
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
920
+ return versionRef.loadSync(repository, throws);
921
+ }
922
+
923
+ async collectVersionsObjects(
924
+ repo: Repository,
925
+ versions: string[],
926
+ throwForMissingLocalArtifacts = false,
927
+ workspaceId?: ComponentID
928
+ ): Promise<ObjectItem[]> {
929
+ const refsWithoutArtifacts: Ref[] = [];
930
+ const artifactsRefs: Ref[] = [];
931
+ const artifactsRefsFromExportedVersions: Ref[] = [];
932
+ const locallyChangedVersions = await this.getLocalTagsOrHashes(repo, workspaceId);
933
+ const locallyChangedHashes = locallyChangedVersions.map((v) =>
934
+ isTag(v) ? this.versionsIncludeOrphaned[v].hash : v
935
+ );
936
+ const versionsRefs = versions.map((version) => this.getRef(version) as Ref);
937
+ refsWithoutArtifacts.push(...versionsRefs);
938
+
939
+ const versionsObjects: Version[] = await Promise.all(
940
+ versionsRefs.map((versionRef) => this.loadVersion(versionRef.toString(), repo))
941
+ );
942
+ versionsObjects.forEach((versionObject) => {
943
+ const refs = versionObject.refsWithOptions(false, false);
944
+ refsWithoutArtifacts.push(...refs);
945
+ const refsFromExtensions = getRefsFromExtensions(versionObject.extensions);
946
+ locallyChangedHashes.includes(versionObject.hash().toString())
947
+ ? artifactsRefs.push(...refsFromExtensions)
948
+ : artifactsRefsFromExportedVersions.push(...refsFromExtensions);
949
+ });
950
+ const loadedRefs: ObjectItem[] = [];
951
+ try {
952
+ const loaded = await repo.loadManyRaw(refsWithoutArtifacts);
953
+ loadedRefs.push(...loaded);
954
+ } catch (err: any) {
955
+ if (err.code === 'ENOENT') {
956
+ throw new Error(`unable to find an object file "${err.path}"
957
+ for a component "${this.id()}", versions: ${versions.join(', ')}`);
958
+ }
959
+ throw err;
960
+ }
961
+ try {
962
+ const loaded = throwForMissingLocalArtifacts
963
+ ? await repo.loadManyRaw(artifactsRefs)
964
+ : await repo.loadManyRawIgnoreMissing(artifactsRefs);
965
+ loadedRefs.push(...loaded);
966
+ // ignore missing artifacts when exporting old versions that were exported in the past and are now exported to a
967
+ // different scope. this is happening for example when exporting a lane that has components from different
968
+ // remotes. it's ok to not have all artifacts from the other remotes to this remote.
969
+ const loadedExportedArtifacts = await repo.loadManyRawIgnoreMissing(artifactsRefsFromExportedVersions);
970
+ loadedRefs.push(...loadedExportedArtifacts);
971
+ } catch (err: any) {
972
+ if (err.code === 'ENOENT') {
973
+ throw new Error(`unable to find an artifact object file "${err.path}"
974
+ for a component "${this.id()}", versions: ${versions.join(', ')}
975
+ consider using --ignore-missing-artifacts flag if you're sure the artifacts are in the remote`);
976
+ }
977
+ throw err;
978
+ }
979
+ return loadedRefs;
980
+ }
981
+
982
+ async collectObjects(repo: Repository): Promise<ComponentObjects> {
983
+ try {
984
+ const [rawComponent, objects] = await Promise.all([this.asRaw(repo), this.collectRaw(repo)]);
985
+ return new ComponentObjects(
986
+ rawComponent,
987
+ objects.map((o) => o.buffer)
988
+ );
989
+ } catch (err: any) {
990
+ if (err.code === 'ENOENT') {
991
+ throw new Error(
992
+ `fatal: an object of "${this.id()}" was not found at ${err.path}\nplease try to re-import the component`
993
+ );
994
+ }
995
+ throw err;
996
+ }
997
+ }
998
+
999
+ /**
1000
+ * to delete a version from a component, don't call this method directly. Instead, use sources.removeVersion()
1001
+ */
1002
+ removeVersion(version: string): Ref {
1003
+ const objectRef = this.getRef(version);
1004
+ if (!objectRef) throw new Error(`removeVersion failed finding version ${version}`);
1005
+ delete this.versions[version];
1006
+ if (this.state.versions && this.state.versions[version]) delete this.state.versions[version];
1007
+ return objectRef;
1008
+ }
1009
+
1010
+ toComponentVersion(versionStr?: string): ComponentVersion {
1011
+ const versionParsed = versionParser(versionStr);
1012
+ const versionNum = versionParsed.latest
1013
+ ? this.getHeadRegardlessOfLaneAsTagOrHash(true)
1014
+ : (versionParsed.versionNum as string);
1015
+ if (versionNum === VERSION_ZERO) {
1016
+ throw new NoHeadNoVersion(this.id());
1017
+ }
1018
+ if (isTag(versionNum) && !this.hasTagIncludeOrphaned(versionNum)) {
1019
+ throw new BitError(
1020
+ `the version ${versionNum} of "${this.id()}" does not exist in ${this.listVersionsIncludeOrphaned().join(
1021
+ '\n'
1022
+ )}, versions array.`
1023
+ );
1024
+ }
1025
+ return new ComponentVersion(this, versionNum);
1026
+ }
1027
+
1028
+ /**
1029
+ * if no "specificVersion" is given, it returns according to the head
1030
+ */
1031
+ async isDeprecated(repo: Repository, specificVersion?: string) {
1032
+ // backward compatibility
1033
+ if (this.deprecated) {
1034
+ return true;
1035
+ }
1036
+ const head = this.getHeadRegardlessOfLane();
1037
+ if (!head) {
1038
+ // it's legacy, or new. If legacy, the "deprecated" prop should do. if it's new, the workspace should
1039
+ // have the answer.
1040
+ return false;
1041
+ }
1042
+ const headVersion = (await repo.load(head)) as Version;
1043
+ if (!headVersion) {
1044
+ // the head Version doesn't exist locally, there is no way to know whether it's deprecated
1045
+ return null;
1046
+ }
1047
+ const deprecationAspect = headVersion.extensions.findCoreExtension(Extensions.deprecation);
1048
+ if (!deprecationAspect) {
1049
+ return false;
1050
+ }
1051
+ if (deprecationAspect.config.deprecate) {
1052
+ return true;
1053
+ }
1054
+ if (specificVersion && deprecationAspect.config.range) {
1055
+ const tag = this.getTag(specificVersion);
1056
+ if (!tag) return false; // it's a snap. "range" doesn't support deprecating snaps. only semver.
1057
+ return semver.satisfies(tag, deprecationAspect.config.range);
1058
+ }
1059
+ return false;
1060
+ }
1061
+
1062
+ /**
1063
+ * whether the head is marked as internal. internal components are still versioned and exported,
1064
+ * but are hidden by default in the UI (workspace, scope and Bit Cloud).
1065
+ */
1066
+ async isInternal(repo: Repository): Promise<boolean | null> {
1067
+ const head = this.getHeadRegardlessOfLane();
1068
+ if (!head) {
1069
+ // it's new. the workspace should have the answer.
1070
+ return false;
1071
+ }
1072
+ const headVersion = (await repo.load(head)) as Version;
1073
+ if (!headVersion) {
1074
+ // the head Version doesn't exist locally, there is no way to know whether it's internal
1075
+ return null;
1076
+ }
1077
+ const internalizeAspect = headVersion.extensions.findCoreExtension(Extensions.internalize);
1078
+ if (!internalizeAspect) {
1079
+ return false;
1080
+ }
1081
+ return Boolean(internalizeAspect.config.internal);
1082
+ }
1083
+
1084
+ async isRemoved(repo: Repository, specificVersion?: string): Promise<boolean | null> {
1085
+ const getHead = () => {
1086
+ if (!this.laneHeadLocal) return this.getHead();
1087
+ // you're checked out to a lane.
1088
+ if (!specificVersion) return this.laneHeadLocal;
1089
+ // it's possible that this specificVersion is from main.
1090
+ if (specificVersion === this.laneHeadLocal.toString()) return this.laneHeadLocal;
1091
+ return this.getHead();
1092
+ };
1093
+ const head = getHead();
1094
+ if (!head) {
1095
+ // it's new or only on lane
1096
+ return false;
1097
+ }
1098
+ const headVersion = (await repo.load(head)) as Version;
1099
+ if (!headVersion) {
1100
+ // the head Version doesn't exist locally, there is no way to know whether it's removed
1101
+ return null;
1102
+ }
1103
+ const removeAspect = headVersion.extensions.findCoreExtension(Extensions.remove);
1104
+ if (!removeAspect) {
1105
+ return false;
1106
+ }
1107
+ if (removeAspect.config.removed) {
1108
+ return true;
1109
+ }
1110
+ if (specificVersion) {
1111
+ if (removeAspect.config.range) {
1112
+ const tag = this.getTag(specificVersion);
1113
+ if (tag) return semver.satisfies(tag, removeAspect.config.range);
1114
+ }
1115
+ if (removeAspect.config.snaps && Array.isArray(removeAspect.config.snaps)) {
1116
+ return removeAspect.config.snaps.includes(specificVersion);
1117
+ }
1118
+ }
1119
+ return false;
1120
+ }
1121
+
1122
+ async isLaneReadmeOf(repo: Repository): Promise<string[]> {
1123
+ const head = this.getHeadRegardlessOfLane();
1124
+ if (!head) {
1125
+ // we dont support lanes in legacy
1126
+ return [];
1127
+ }
1128
+ const version = (await repo.load(head)) as Version;
1129
+ if (!version) {
1130
+ // the head Version doesn't exist locally, there is no way to know whether it is a lane readme component
1131
+ return [];
1132
+ }
1133
+ const lanesAspect = version.extensions.findCoreExtension(Extensions.lanes);
1134
+ if (!lanesAspect || !lanesAspect.config.readme) {
1135
+ return [];
1136
+ }
1137
+ return Object.keys(lanesAspect.config.readme);
1138
+ }
1139
+ /**
1140
+ * convert a ModelComponent of a specific version to ConsumerComponent
1141
+ * @see sources.consumerComponentToVersion() for the opposite action.
1142
+ */
1143
+ async toConsumerComponent(versionStr: string, scopeName: string, repository: Repository): Promise<ConsumerComponent> {
1144
+ logger.trace(`model-component, converting ${this.id()}, version: ${versionStr} to ConsumerComponent`);
1145
+ let componentVersion = this.toComponentVersion(versionStr);
1146
+ const version: Version = await componentVersion.getVersion(repository);
1147
+ // in case the the version is a short-hash, it should be converted to a full hash.
1148
+ if (
1149
+ versionStr !== LATEST_VERSION &&
1150
+ !isTag(versionStr) &&
1151
+ !isSnap(versionStr) &&
1152
+ version.hash().toString() !== versionStr
1153
+ ) {
1154
+ componentVersion = new ComponentVersion(this, version.hash().toString());
1155
+ }
1156
+ const resolvedVersion = componentVersion.version;
1157
+ const loadFileInstance = (ClassName) => async (file) => {
1158
+ const loadP = file.file.load(repository);
1159
+ const content: Source = await loadP;
1160
+ if (!content)
1161
+ throw new BitError(
1162
+ `failed loading file ${file.relativePath} (ref: ${file.file.toString()}) from the model of ${this.id()}@${resolvedVersion}.
1163
+ The Source object is missing from the local scope.
1164
+ To fix, run:
1165
+ bit import ${this.id()}@${resolvedVersion} --objects --all-history`
1166
+ );
1167
+ return new ClassName({ base: '.', path: file.relativePath, contents: content.contents, test: file.test });
1168
+ };
1169
+ const filesP = version.files ? Promise.all(version.files.map(loadFileInstance(SourceFile))) : null;
1170
+ // @todo: this is weird. why the scopeMeta would be taken from the current scope and not he component scope?
1171
+ const scopeMetaP = scopeName ? ScopeMeta.fromScopeName(scopeName).load(repository) : Promise.resolve();
1172
+ const log = version.log || null;
1173
+ const [files, scopeMeta] = await Promise.all([filesP, scopeMetaP]);
1174
+
1175
+ const extensions = version.extensions.clone();
1176
+ // when generating a new ConsumerComponent out of Version, it is critical to make sure that
1177
+ // all objects are cloned and not copied by reference. Otherwise, every time the
1178
+ // ConsumerComponent instance is changed, the Version will be changed as well, and since
1179
+ // the Version instance is saved in the Repository._cache, the next time a Version instance
1180
+ // is retrieved, it'll be different than the first time.
1181
+ const consumerComponent = new ConsumerComponent({
1182
+ name: this.name,
1183
+ version: componentVersion.version,
1184
+ scope: this.toComponentId()._legacy.scope,
1185
+ defaultScope: this.scope,
1186
+ lang: this.lang,
1187
+ bindingPrefix: this.bindingPrefix,
1188
+ mainFile: version.mainFile,
1189
+ dependencies: this.addDepsInfoFromDepsResolver(version.dependencies, extensions),
1190
+ devDependencies: this.addDepsInfoFromDepsResolver(version.devDependencies, extensions),
1191
+ flattenedDependencies: version.flattenedDependencies.clone(),
1192
+ packageDependencies: clone(version.packageDependencies),
1193
+ devPackageDependencies: clone(version.devPackageDependencies),
1194
+ peerPackageDependencies: clone(version.peerPackageDependencies),
1195
+ // @ts-ignore
1196
+ files,
1197
+ docs: version.docs,
1198
+ // @ts-ignore
1199
+ license: scopeMeta ? License.deserialize(scopeMeta.license) : undefined, // todo: make sure we have license in case of local scope
1200
+ log,
1201
+ overrides: ComponentOverrides.loadFromScope(version.overrides),
1202
+ packageJsonChangedProps: clone(version.packageJsonChangedProps),
1203
+ deprecated: this.deprecated,
1204
+ removed: version.isRemoved(),
1205
+ scopesList: clone(this.scopesList),
1206
+ schema: version.schema,
1207
+ extensions,
1208
+ buildStatus: version.buildStatus,
1209
+ });
1210
+
1211
+ return consumerComponent;
1212
+ }
1213
+
1214
+ private addDepsInfoFromDepsResolver(dependencies: Dependencies, extensions: ExtensionDataList): Dependency[] {
1215
+ const cloned = dependencies.getClone();
1216
+ const depsResolverData = extensions.find((ext) => ext.name === 'teambit.dependencies/dependency-resolver');
1217
+ if (!depsResolverData) return cloned;
1218
+ cloned.forEach((dependency) => {
1219
+ if (dependency.packageName) return;
1220
+ const matchedEntry = depsResolverData.data?.dependencies?.find((entry) => {
1221
+ return dependency.id.toString() === entry.id;
1222
+ });
1223
+ if (matchedEntry) {
1224
+ dependency.packageName = matchedEntry.packageName;
1225
+ }
1226
+ });
1227
+ return cloned;
1228
+ }
1229
+
1230
+ // @todo: make sure it doesn't have the same ref twice, once as a version and once as a head
1231
+ refs(): Ref[] {
1232
+ const versions = Object.values(this.versionsIncludeOrphaned);
1233
+ if (this.head) versions.push(this.head);
1234
+ return versions;
1235
+ }
1236
+
1237
+ validateBeforePersisting(componentStr: string): void {
1238
+ logger.trace(`validating component object: ${this.hash().hash} ${this.id()}`);
1239
+ const component = Component.parse(componentStr);
1240
+ component.validate();
1241
+ }
1242
+
1243
+ toBuffer(pretty: boolean) {
1244
+ const args = getStringifyArgs(pretty);
1245
+ const obj = this.toObject();
1246
+ const str = JSON.stringify(obj, ...args);
1247
+ if (this.validateBeforePersist) this.validateBeforePersisting(str);
1248
+ return Buffer.from(str);
1249
+ }
1250
+
1251
+ /**
1252
+ * Clear data that is relevant only for the local scope and should not be moved to the remote scope
1253
+ */
1254
+ clearStateData() {
1255
+ this.local = false; // backward compatibility for components created before 0.12.6
1256
+ this.state = {};
1257
+ }
1258
+
1259
+ markVersionAsLocal(version: string) {
1260
+ if (!this.state.versions) this.state = { versions: {} };
1261
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
1262
+ if (!this.state.versions[version]) this.state.versions[version] = {};
1263
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
1264
+ this.state.versions[version].local = true;
1265
+ }
1266
+
1267
+ /**
1268
+ * local versions that are not exported on the main lane.
1269
+ * @see `this.getLocalTagsOrHashes()`, to get local snaps on the current lane
1270
+ */
1271
+ getLocalVersions(): string[] {
1272
+ if (isEmpty(this.state) || isEmpty(this.state.versions)) return [];
1273
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
1274
+ return Object.keys(this.state.versions).filter((version) => this.state.versions[version].local);
1275
+ }
1276
+
1277
+ hasLocalTag(tag: string): boolean {
1278
+ const localVersions = this.getLocalVersions();
1279
+ return localVersions.includes(tag);
1280
+ }
1281
+
1282
+ async getLocalTagsOrHashes(repo: Repository, workspaceId?: ComponentID, lane?: Lane): Promise<string[]> {
1283
+ const localHashes = await this.getLocalHashes(repo, workspaceId, lane);
1284
+ if (!localHashes.length) return [];
1285
+ return this.switchHashesWithTagsIfExist(localHashes).reverse(); // reverse to get the older first
1286
+ }
1287
+
1288
+ /**
1289
+ * Raw divergence (`snapsOnSourceOnly`). When `lane` is provided, applies the lean-lane filter:
1290
+ * drops refs whose Version is main-origin. Those refs already live on the component's home
1291
+ * scope (and on the destination too in the same-scope case), so `bit export` shouldn't be
1292
+ * re-pushing them. Pass `lane` from status/export/reset to share the same "what's actually
1293
+ * local on this lane" view.
1294
+ *
1295
+ * The lane's recorded head for this component is always kept, even if it's main-origin — the
1296
+ * lane object references it and the destination scope must be able to resolve the hash. Versions
1297
+ * marked `squashed` or `unrelated` are kept as well — they're locally-mutated and the
1298
+ * destination needs them to reconstruct the lane history.
1299
+ */
1300
+ async getLocalHashes(repo: Repository, workspaceId?: ComponentID, lane?: Lane): Promise<Ref[]> {
1301
+ await this.setDivergeData(repo, undefined, undefined, workspaceId);
1302
+ const divergeData = this.getDivergeData();
1303
+ const localHashes = divergeData.snapsOnSourceOnly;
1304
+
1305
+ // When there's a detached head, divergeData only includes the detached head lineage.
1306
+ // We also need to include unexported versions from the main head lineage.
1307
+ const hasDetachedHead = this.detachedHeads && this.detachedHeads.getAllHeads().length > 0;
1308
+ if (hasDetachedHead && this.head) {
1309
+ // Calculate divergence from the main head as well
1310
+ const mainHeadDivergeData = await getDivergeData({
1311
+ repo,
1312
+ modelComponent: this,
1313
+ targetHead: (this.laneId ? this.calculatedRemoteHeadWhenOnLane : this.remoteHead) || null,
1314
+ sourceHead: this.head,
1315
+ throws: false,
1316
+ });
1317
+ // Add main head local versions that aren't already in localHashes
1318
+ for (const hash of mainHeadDivergeData.snapsOnSourceOnly) {
1319
+ if (!localHashes.find((h) => h.isEqual(hash))) {
1320
+ localHashes.push(hash);
1321
+ }
1322
+ }
1323
+ }
1324
+
1325
+ if (!localHashes.length) return [];
1326
+ const filtered = lane ? await this.filterLeanLaneRefs(repo, lane, localHashes) : localHashes;
1327
+ return filtered.reverse(); // reverse to get the older first
1328
+ }
1329
+
1330
+ private async filterLeanLaneRefs(repo: Repository, lane: Lane, refs: Ref[]): Promise<Ref[]> {
1331
+ const laneHead = lane.getCompHeadIncludeUpdateDependents(this.toComponentId());
1332
+ const keptRefs = await pMapPool(
1333
+ refs,
1334
+ async (ref) => {
1335
+ if (laneHead && ref.isEqual(laneHead)) return ref;
1336
+ const obj = (await ref.load(repo)) as Version | undefined;
1337
+ if (!obj) return null;
1338
+ const isLaneOrigin = Boolean(obj.originLaneId);
1339
+ const isLocallyMutated = Boolean(obj.squashed) || Boolean(obj.unrelated);
1340
+ if (!isLaneOrigin && !isLocallyMutated) return null;
1341
+ return ref;
1342
+ },
1343
+ { concurrency: concurrentComponentsLimit() }
1344
+ );
1345
+ return keptRefs.filter((ref): ref is Ref => ref !== null);
1346
+ }
1347
+
1348
+ /**
1349
+ * for most cases, use `isLocallyChanged`, which takes into account lanes.
1350
+ * this is for cases when we only care about the versions exist in the `state` prop.
1351
+ */
1352
+ isLocallyChangedRegardlessOfLanes(): boolean {
1353
+ return Boolean(this.getLocalVersions().length);
1354
+ }
1355
+
1356
+ /**
1357
+ * whether the component was locally changed, either by adding a new snap/tag or by merging
1358
+ * components from different lanes.
1359
+ */
1360
+ async isLocallyChanged(repo: Repository, lane?: Lane | null, workspaceId?: ComponentID): Promise<boolean> {
1361
+ if (lane) await this.populateLocalAndRemoteHeads(repo, lane);
1362
+ await this.setDivergeData(repo, undefined, undefined, workspaceId);
1363
+ const divergeData = this.getDivergeData();
1364
+ return divergeData.isSourceAhead();
1365
+ }
1366
+
1367
+ async getVersionHistory(repo: Repository): Promise<VersionHistory> {
1368
+ const emptyVersionHistory = VersionHistory.fromId(this.name, this.scope);
1369
+ const versionHistory = await repo.load(emptyVersionHistory.hash());
1370
+ return (versionHistory || emptyVersionHistory) as VersionHistory;
1371
+ }
1372
+
1373
+ async getAndPopulateVersionHistory(repo: Repository, head: Ref): Promise<VersionHistory> {
1374
+ const versionHistory = await this.getVersionHistory(repo);
1375
+ const { err } = await this.populateVersionHistoryIfMissingGracefully(repo, versionHistory, head);
1376
+ if (err) {
1377
+ logger.error(`rethrowing an error ${err.message}, current stuck`, new Error(err.message));
1378
+ throw err;
1379
+ }
1380
+ return versionHistory;
1381
+ }
1382
+
1383
+ /**
1384
+ * careful! the `versions` passed here can belong to other components, not necessarily to this one.
1385
+ * that's why it checks whether the version-hash exists in the VersionHistory, and if it's not,
1386
+ * it won't update it.
1387
+ */
1388
+ async updateRebasedVersionHistory(repo: Repository, versions: Version[]): Promise<VersionHistory | undefined> {
1389
+ const versionHistory = await this.getVersionHistory(repo);
1390
+ const hasUpdated = versions.some((version) => {
1391
+ const versionData = versionHistory.getVersionData(version.hash());
1392
+ if (!versionData) return false;
1393
+ versionHistory.addFromVersionsObjects([version]);
1394
+ return true;
1395
+ });
1396
+
1397
+ return hasUpdated ? versionHistory : undefined;
1398
+ }
1399
+
1400
+ async updateVersionHistory(repo: Repository, versions: Version[]): Promise<VersionHistory> {
1401
+ const versionHistory = await this.getVersionHistory(repo);
1402
+ versionHistory.addFromVersionsObjects(versions);
1403
+ logger.debug(`updating version history of ${this.id()} with ${versions.length} versions`);
1404
+ return versionHistory;
1405
+ }
1406
+
1407
+ async populateVersionHistoryIfMissingGracefully(
1408
+ repo: Repository,
1409
+ versionHistory: VersionHistory,
1410
+ head: Ref,
1411
+ /**
1412
+ * during traversal, if a hash is found in the VersionHistory it probably means that it has all history until this
1413
+ * point, so we can stop there for better performance. In some rare cases (e.g. the export was interrupted), we
1414
+ * need the ability of full traversal to repair the VersionHistory.
1415
+ */
1416
+ exitWhenFind = true
1417
+ ): Promise<{ err?: Error; added?: VersionParents[] }> {
1418
+ const headExists = versionHistory.hasHash(head);
1419
+ if (exitWhenFind && headExists) return {};
1420
+ const getVersionObj = async (ref: Ref) => (await ref.load(repo)) as Version | undefined;
1421
+ const versionsToAdd: Version[] = [];
1422
+ let err: Error | undefined;
1423
+ const addParentsRecursively = async (version: Version) => {
1424
+ await pMapSeries(version.parents, async (parent) => {
1425
+ const foundParent = versionHistory.hasHash(parent) || versionsToAdd.find((v) => v.hash().isEqual(parent));
1426
+ if (exitWhenFind && foundParent) {
1427
+ return;
1428
+ }
1429
+ const parentVersion = await getVersionObj(parent);
1430
+ if (!parentVersion) {
1431
+ const tag = this.getTagOfRefIfExists(parent);
1432
+ err = tag
1433
+ ? new VersionNotFound(tag, this.id())
1434
+ : new ParentNotFound(this.id(), version.hash().toString(), parent.toString());
1435
+ return;
1436
+ }
1437
+ versionsToAdd.push(parentVersion);
1438
+ await addParentsRecursively(parentVersion);
1439
+ });
1440
+ };
1441
+ const headVer = await getVersionObj(head);
1442
+ if (!headVer) {
1443
+ return { err: new HeadNotFound(this.id(), head.toString()) };
1444
+ }
1445
+ return this.populateVersionHistoryMutex.runExclusive(async () => {
1446
+ if (!headExists) versionsToAdd.push(headVer);
1447
+ await addParentsRecursively(headVer);
1448
+ const added = versionsToAdd.map((v) => getVersionParentsFromVersion(v));
1449
+ if (err) {
1450
+ return { err, added };
1451
+ }
1452
+ versionHistory.addFromVersionsObjects(versionsToAdd);
1453
+ logger.debug(
1454
+ `populateVersionHistoryIfMissingGracefully, updating ${this.id()} with ${versionsToAdd.length} versions`
1455
+ );
1456
+ await repo.writeObjectsToTheFS([versionHistory]);
1457
+ return { added };
1458
+ });
1459
+ }
1460
+
1461
+ static parse(contents: string): Component {
1462
+ const rawComponent = JSON.parse(contents);
1463
+ return Component.from({
1464
+ name: rawComponent.box ? `${rawComponent.box}/${rawComponent.name}` : rawComponent.name,
1465
+ scope: rawComponent.scope,
1466
+ versions: mapValues(rawComponent.versions as Record<string, string>, (val) => Ref.from(val)),
1467
+ lang: rawComponent.lang,
1468
+ deprecated: rawComponent.deprecated,
1469
+ bindingPrefix: rawComponent.bindingPrefix,
1470
+ state: rawComponent.state,
1471
+ orphanedVersions: mapValues(rawComponent.orphanedVersions || {}, (val) => Ref.from(val)),
1472
+ scopesList: rawComponent.remotes,
1473
+ head: rawComponent.head ? Ref.from(rawComponent.head) : undefined,
1474
+ schema: rawComponent.schema || (rawComponent.head ? SchemaName.Harmony : SchemaName.Legacy),
1475
+ detachedHeads: DetachedHeads.fromObject(rawComponent.detachedHeads),
1476
+ });
1477
+ }
1478
+
1479
+ static from(props: ComponentProps): Component {
1480
+ return new Component(props);
1481
+ }
1482
+
1483
+ static fromBitId(bitId: ComponentID): Component {
1484
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
1485
+ return new Component({
1486
+ name: bitId.fullName,
1487
+ scope: bitId.scope,
1488
+ });
1489
+ }
1490
+
1491
+ get isLegacy(): boolean {
1492
+ return !this.schema || this.schema === SchemaName.Legacy;
1493
+ }
1494
+
1495
+ validate(): void {
1496
+ const message = `unable to save Component object "${this.id()}"`;
1497
+ if (!this.name) throw new BitError(`${message} the name is missing`);
1498
+ if (this.state && this.state.versions) {
1499
+ Object.keys(this.state.versions).forEach((version) => {
1500
+ if (isTag(version) && !this.hasTag(version)) {
1501
+ throw new ValidationError(`${message}, the version ${version} is marked as staged but is not available`);
1502
+ }
1503
+ });
1504
+ }
1505
+ const hashDuplications = findDuplications(this.versionArray.map((v) => v.toString()));
1506
+ if (hashDuplications.length) {
1507
+ throw new ValidationError(`${message}, the following hash(es) are duplicated ${hashDuplications.join(', ')}`);
1508
+ }
1509
+ Object.keys(this.orphanedVersions).forEach((version) => {
1510
+ if (this.versions[version]) {
1511
+ throw new ValidationError(
1512
+ `${message}, the version "${version}" exists in orphanedVersions but it exits also in "versions" prop`
1513
+ );
1514
+ }
1515
+ });
1516
+ if (!this.isLegacy && !this.head && this.versionArray.length) {
1517
+ // legacy don't have head. also, when snapping on a lane the first time, there is no head.
1518
+ // tags are done on default lane only, so if there are versions (tag), it must have head
1519
+ throw new ValidationError(`${message}, the "head" prop is missing`);
1520
+ }
1521
+ }
1522
+ }