@teambit/objects 0.0.0-00133c53667c619f31de3353b1a01a30e323f7bd

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 (117) 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 +40 -0
  19. package/dist/models/lane-history.js +117 -0
  20. package/dist/models/lane-history.js.map +1 -0
  21. package/dist/models/lane.d.ts +125 -0
  22. package/dist/models/lane.js +461 -0
  23. package/dist/models/lane.js.map +1 -0
  24. package/dist/models/model-component.d.ts +320 -0
  25. package/dist/models/model-component.js +1392 -0
  26. package/dist/models/model-component.js.map +1 -0
  27. package/dist/models/model-component.spec.d.ts +1 -0
  28. package/dist/models/model-component.spec.js +71 -0
  29. package/dist/models/model-component.spec.js.map +1 -0
  30. package/dist/models/scopeMeta.d.ts +20 -0
  31. package/dist/models/scopeMeta.js +68 -0
  32. package/dist/models/scopeMeta.js.map +1 -0
  33. package/dist/models/source.d.ts +10 -0
  34. package/dist/models/source.js +42 -0
  35. package/dist/models/source.js.map +1 -0
  36. package/dist/models/symlink.d.ts +30 -0
  37. package/dist/models/symlink.js +91 -0
  38. package/dist/models/symlink.js.map +1 -0
  39. package/dist/models/version-history.d.ts +59 -0
  40. package/dist/models/version-history.js +287 -0
  41. package/dist/models/version-history.js.map +1 -0
  42. package/dist/models/version.d.ts +286 -0
  43. package/dist/models/version.js +774 -0
  44. package/dist/models/version.js.map +1 -0
  45. package/dist/models/version.spec.d.ts +1 -0
  46. package/dist/models/version.spec.js +332 -0
  47. package/dist/models/version.spec.js.map +1 -0
  48. package/dist/objects/bit-object-list.d.ts +24 -0
  49. package/dist/objects/bit-object-list.js +65 -0
  50. package/dist/objects/bit-object-list.js.map +1 -0
  51. package/dist/objects/index.d.ts +5 -0
  52. package/dist/objects/index.js +60 -0
  53. package/dist/objects/index.js.map +1 -0
  54. package/dist/objects/object-list-to-graph.d.ts +13 -0
  55. package/dist/objects/object-list-to-graph.js +93 -0
  56. package/dist/objects/object-list-to-graph.js.map +1 -0
  57. package/dist/objects/object-list.d.ts +52 -0
  58. package/dist/objects/object-list.js +369 -0
  59. package/dist/objects/object-list.js.map +1 -0
  60. package/dist/objects/object.d.ts +35 -0
  61. package/dist/objects/object.js +189 -0
  62. package/dist/objects/object.js.map +1 -0
  63. package/dist/objects/objects-readable-generator.d.ts +31 -0
  64. package/dist/objects/objects-readable-generator.js +192 -0
  65. package/dist/objects/objects-readable-generator.js.map +1 -0
  66. package/dist/objects/raw-object.d.ts +23 -0
  67. package/dist/objects/raw-object.js +145 -0
  68. package/dist/objects/raw-object.js.map +1 -0
  69. package/dist/objects/ref.d.ts +14 -0
  70. package/dist/objects/ref.js +45 -0
  71. package/dist/objects/ref.js.map +1 -0
  72. package/dist/objects/repository.d.ts +165 -0
  73. package/dist/objects/repository.js +851 -0
  74. package/dist/objects/repository.js.map +1 -0
  75. package/dist/objects/scope-index.d.ts +74 -0
  76. package/dist/objects/scope-index.js +255 -0
  77. package/dist/objects/scope-index.js.map +1 -0
  78. package/dist/objects/scope-index.spec.d.ts +1 -0
  79. package/dist/objects/scope-index.spec.js +152 -0
  80. package/dist/objects/scope-index.spec.js.map +1 -0
  81. package/dist/objects.aspect.d.ts +2 -0
  82. package/dist/objects.aspect.js +18 -0
  83. package/dist/objects.aspect.js.map +1 -0
  84. package/dist/objects.main.runtime.d.ts +7 -0
  85. package/dist/objects.main.runtime.js +36 -0
  86. package/dist/objects.main.runtime.js.map +1 -0
  87. package/dist/preview-1763506442019.js +7 -0
  88. package/fixtures/version-model-extended.json +48 -0
  89. package/fixtures/version-model-object.json +87 -0
  90. package/models/dependencies-graph.ts +120 -0
  91. package/models/detach-heads.ts +79 -0
  92. package/models/export-metadata.ts +56 -0
  93. package/models/index.ts +11 -0
  94. package/models/lane-history.ts +106 -0
  95. package/models/lane.ts +368 -0
  96. package/models/model-component.spec.ts +55 -0
  97. package/models/model-component.ts +1407 -0
  98. package/models/scopeMeta.ts +58 -0
  99. package/models/source.ts +31 -0
  100. package/models/symlink.ts +66 -0
  101. package/models/version-history.ts +271 -0
  102. package/models/version.spec.ts +280 -0
  103. package/models/version.ts +815 -0
  104. package/objects/bit-object-list.ts +59 -0
  105. package/objects/index.ts +6 -0
  106. package/objects/object-list-to-graph.ts +69 -0
  107. package/objects/object-list.ts +313 -0
  108. package/objects/object.ts +152 -0
  109. package/objects/objects-readable-generator.ts +167 -0
  110. package/objects/raw-object.ts +132 -0
  111. package/objects/ref.ts +45 -0
  112. package/objects/repository.ts +771 -0
  113. package/objects/scope-index.spec.ts +95 -0
  114. package/objects/scope-index.ts +197 -0
  115. package/package.json +96 -0
  116. package/types/asset.d.ts +41 -0
  117. package/types/style.d.ts +42 -0
@@ -0,0 +1,851 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ function _fsExtra() {
8
+ const data = _interopRequireDefault(require("fs-extra"));
9
+ _fsExtra = function () {
10
+ return data;
11
+ };
12
+ return data;
13
+ }
14
+ function _uidNumber() {
15
+ const data = _interopRequireDefault(require("uid-number"));
16
+ _uidNumber = function () {
17
+ return data;
18
+ };
19
+ return data;
20
+ }
21
+ function _asyncMutex() {
22
+ const data = require("async-mutex");
23
+ _asyncMutex = function () {
24
+ return data;
25
+ };
26
+ return data;
27
+ }
28
+ function _lodash() {
29
+ const data = require("lodash");
30
+ _lodash = function () {
31
+ return data;
32
+ };
33
+ return data;
34
+ }
35
+ function _bitError() {
36
+ const data = require("@teambit/bit-error");
37
+ _bitError = function () {
38
+ return data;
39
+ };
40
+ return data;
41
+ }
42
+ function _componentVersion() {
43
+ const data = require("@teambit/component-version");
44
+ _componentVersion = function () {
45
+ return data;
46
+ };
47
+ return data;
48
+ }
49
+ function path() {
50
+ const data = _interopRequireWildcard(require("path"));
51
+ path = function () {
52
+ return data;
53
+ };
54
+ return data;
55
+ }
56
+ function _toolboxPromise() {
57
+ const data = require("@teambit/toolbox.promise.map-pool");
58
+ _toolboxPromise = function () {
59
+ return data;
60
+ };
61
+ return data;
62
+ }
63
+ function _legacy() {
64
+ const data = require("@teambit/legacy.constants");
65
+ _legacy = function () {
66
+ return data;
67
+ };
68
+ return data;
69
+ }
70
+ function _legacy2() {
71
+ const data = require("@teambit/legacy.logger");
72
+ _legacy2 = function () {
73
+ return data;
74
+ };
75
+ return data;
76
+ }
77
+ function _legacy3() {
78
+ const data = require("@teambit/legacy.utils");
79
+ _legacy3 = function () {
80
+ return data;
81
+ };
82
+ return data;
83
+ }
84
+ function _toolboxFs() {
85
+ const data = require("@teambit/toolbox.fs.remove-empty-dir");
86
+ _toolboxFs = function () {
87
+ return data;
88
+ };
89
+ return data;
90
+ }
91
+ function _harmonyModules() {
92
+ const data = require("@teambit/harmony.modules.concurrency");
93
+ _harmonyModules = function () {
94
+ return data;
95
+ };
96
+ return data;
97
+ }
98
+ function _legacy4() {
99
+ const data = require("@teambit/legacy.scope");
100
+ _legacy4 = function () {
101
+ return data;
102
+ };
103
+ return data;
104
+ }
105
+ function _scopeIndex() {
106
+ const data = require("./scope-index");
107
+ _scopeIndex = function () {
108
+ return data;
109
+ };
110
+ return data;
111
+ }
112
+ function _object() {
113
+ const data = _interopRequireDefault(require("./object"));
114
+ _object = function () {
115
+ return data;
116
+ };
117
+ return data;
118
+ }
119
+ function _objectList() {
120
+ const data = require("./object-list");
121
+ _objectList = function () {
122
+ return data;
123
+ };
124
+ return data;
125
+ }
126
+ function _rawObject() {
127
+ const data = _interopRequireDefault(require("./raw-object"));
128
+ _rawObject = function () {
129
+ return data;
130
+ };
131
+ return data;
132
+ }
133
+ function _ref() {
134
+ const data = _interopRequireDefault(require("./ref"));
135
+ _ref = function () {
136
+ return data;
137
+ };
138
+ return data;
139
+ }
140
+ function _harmonyModules2() {
141
+ const data = require("@teambit/harmony.modules.in-memory-cache");
142
+ _harmonyModules2 = function () {
143
+ return data;
144
+ };
145
+ return data;
146
+ }
147
+ function _models() {
148
+ const data = require("../models");
149
+ _models = function () {
150
+ return data;
151
+ };
152
+ return data;
153
+ }
154
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
155
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
156
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
157
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
158
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
159
+ const OBJECTS_BACKUP_DIR = `${_legacy().OBJECTS_DIR}.bak`;
160
+ const TRASH_DIR = 'trash';
161
+ class Repository {
162
+ constructor(scopePath, scopeJson) {
163
+ _defineProperty(this, "objects", {});
164
+ _defineProperty(this, "objectsToRemove", []);
165
+ _defineProperty(this, "scopeJson", void 0);
166
+ _defineProperty(this, "onRead", void 0);
167
+ _defineProperty(this, "onPersist", void 0);
168
+ _defineProperty(this, "scopePath", void 0);
169
+ _defineProperty(this, "scopeIndex", void 0);
170
+ _defineProperty(this, "cache", void 0);
171
+ _defineProperty(this, "remoteLanes", void 0);
172
+ _defineProperty(this, "unmergedComponents", void 0);
173
+ _defineProperty(this, "_persistMutex", void 0);
174
+ this.scopePath = scopePath;
175
+ this.scopeJson = scopeJson;
176
+ this.onRead = content => Repository.onPostObjectRead?.(content) || content;
177
+ this.onPersist = content => Repository.onPreObjectPersist?.(content) || content;
178
+ this.cache = (0, _harmonyModules2().createInMemoryCache)({
179
+ maxSize: (0, _harmonyModules2().getMaxSizeForObjects)()
180
+ });
181
+ }
182
+ get persistMutex() {
183
+ if (!this._persistMutex) {
184
+ this._persistMutex = new (_asyncMutex().Mutex)();
185
+ }
186
+ return this._persistMutex;
187
+ }
188
+ static async load({
189
+ scopePath,
190
+ scopeJson
191
+ }) {
192
+ const repository = new Repository(scopePath, scopeJson);
193
+ await repository.init();
194
+ return repository;
195
+ }
196
+ async init() {
197
+ const scopeIndex = await this.loadOptionallyCreateScopeIndex();
198
+ this.scopeIndex = scopeIndex;
199
+ this.remoteLanes = new (_legacy4().RemoteLanes)(this.scopePath);
200
+ this.unmergedComponents = await _legacy4().UnmergedComponents.load(this.scopePath);
201
+ }
202
+ static async create({
203
+ scopePath,
204
+ scopeJson
205
+ }) {
206
+ const repository = new Repository(scopePath, scopeJson);
207
+ const scopeIndex = _scopeIndex().ScopeIndex.create(scopePath);
208
+ repository.scopeIndex = scopeIndex;
209
+ repository.unmergedComponents = await _legacy4().UnmergedComponents.load(scopePath);
210
+ repository.remoteLanes = new (_legacy4().RemoteLanes)(scopePath);
211
+ return repository;
212
+ }
213
+ static reset(scopePath) {
214
+ return _scopeIndex().ScopeIndex.reset(scopePath);
215
+ }
216
+ static getPathByScopePath(scopePath) {
217
+ return path().join(scopePath, _legacy().OBJECTS_DIR);
218
+ }
219
+ async reLoadScopeIndex() {
220
+ this.scopeIndex = await this.loadOptionallyCreateScopeIndex();
221
+ }
222
+
223
+ /**
224
+ * current scope index difference with <scope_folder>/index.json content, reload it
225
+ * @deprecated use Scope aspect `watchSystemFiles` instead, it's way more efficient.
226
+ */
227
+ async reloadScopeIndexIfNeed(force = false) {
228
+ const latestScopeIndex = await this.loadOptionallyCreateScopeIndex();
229
+ if (force) {
230
+ this.scopeIndex = latestScopeIndex;
231
+ return;
232
+ }
233
+ const currentAllScopeIndexItems = this.scopeIndex.getAll();
234
+ const latestAllScopeIndexItems = latestScopeIndex.getAll();
235
+ if (currentAllScopeIndexItems.length !== latestAllScopeIndexItems.length) {
236
+ this.scopeIndex = latestScopeIndex;
237
+ return;
238
+ }
239
+ if ((0, _lodash().differenceWith)(currentAllScopeIndexItems, latestAllScopeIndexItems, _lodash().isEqual).length) {
240
+ this.scopeIndex = latestScopeIndex;
241
+ }
242
+ }
243
+ ensureDir() {
244
+ return _fsExtra().default.ensureDir(this.getPath());
245
+ }
246
+ getPath() {
247
+ return Repository.getPathByScopePath(this.scopePath);
248
+ }
249
+ getBackupPath(dirName) {
250
+ const backupPath = path().join(this.scopePath, OBJECTS_BACKUP_DIR);
251
+ return dirName ? path().join(backupPath, dirName) : backupPath;
252
+ }
253
+ getTrashDir() {
254
+ return path().join(this.scopePath, TRASH_DIR);
255
+ }
256
+ getLicense() {
257
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
258
+ return this.scopeJson.getPopulatedLicense();
259
+ }
260
+ async getScopeMetaObject() {
261
+ const license = await this.getLicense();
262
+ const object = _models().ScopeMeta.fromObject({
263
+ license,
264
+ name: this.scopeJson.name
265
+ });
266
+ return {
267
+ ref: object.hash(),
268
+ buffer: await object.compress()
269
+ };
270
+ }
271
+ objectPath(ref) {
272
+ return path().join(this.getPath(), this.hashPath(ref));
273
+ }
274
+ async has(ref) {
275
+ const objectPath = this.objectPath(ref);
276
+ return _fsExtra().default.pathExists(objectPath);
277
+ }
278
+ async hasMultiple(refs) {
279
+ const concurrency = (0, _harmonyModules().concurrentIOLimit)();
280
+ const existingRefs = await (0, _toolboxPromise().pMapPool)(refs, async ref => {
281
+ const pathExists = await this.has(ref);
282
+ return pathExists ? ref : null;
283
+ }, {
284
+ concurrency
285
+ });
286
+ return (0, _lodash().compact)(existingRefs);
287
+ }
288
+ async load(ref, throws = false) {
289
+ // during tag, the updated objects are in `this.objects`.
290
+ // `this.cache` is less reliable, because if it reaches its max, then it loads from the filesystem, which may not
291
+ // be there yet (in case of "version" object), or may be out-of-date (in case of "component" object).
292
+ const inMemoryObjects = this.objects[ref.hash.toString()];
293
+ if (inMemoryObjects) return inMemoryObjects;
294
+ if (ref.hash.length < _componentVersion().HASH_SIZE) {
295
+ ref = await this.getFullRefFromShortHash(ref);
296
+ }
297
+ const cached = this.getCache(ref);
298
+ if (cached) {
299
+ return cached;
300
+ }
301
+ let fileContentsRaw;
302
+ const objectPath = this.objectPath(ref);
303
+ try {
304
+ fileContentsRaw = await _fsExtra().default.readFile(objectPath);
305
+ } catch (err) {
306
+ if (err.code !== 'ENOENT') {
307
+ _legacy2().logger.error(`Failed reading a ref file ${objectPath}. Error: ${err.message}`);
308
+ throw err;
309
+ }
310
+ _legacy2().logger.trace(`Failed finding a ref file ${objectPath}.`);
311
+ if (throws) {
312
+ // if we just `throw err` we loose the stack trace.
313
+ // see https://stackoverflow.com/questions/68022123/no-stack-in-fs-promises-readfile-enoent-error
314
+ const msg = `fatal: failed finding an object file ${objectPath} in the filesystem at ${err.path}`;
315
+ throw Object.assign(err, {
316
+ stack: new Error(msg).stack
317
+ });
318
+ }
319
+ // @ts-ignore @todo: fix! it should return BitObject | null.
320
+ return null;
321
+ }
322
+ const size = fileContentsRaw.byteLength;
323
+ const fileContents = this.onRead(fileContentsRaw);
324
+ // uncomment to debug the transformed objects by onRead
325
+ // console.log('transformedContent load', ref.toString(), BitObject.parseSync(fileContents).getType());
326
+ const parsedObject = await _object().default.parseObject(fileContents, objectPath);
327
+ const maxSizeToCache = 100 * 1024; // 100KB
328
+ if (size < maxSizeToCache) {
329
+ // don't cache big files (mainly artifacts) to prevent out-of-memory
330
+ this.setCache(parsedObject);
331
+ }
332
+ return parsedObject;
333
+ }
334
+
335
+ /**
336
+ * this is restricted to provide objects according to the given types. Otherwise, big scopes (>1GB) could crush.
337
+ * example usage: `this.list([ModelComponent, Symlink, Lane])`
338
+ */
339
+ async list(types) {
340
+ const refs = await this.listRefs();
341
+ const concurrency = (0, _harmonyModules().concurrentIOLimit)();
342
+ _legacy2().logger.debug(`Repository.list, ${refs.length} refs are going to be loaded, searching for types: ${types.map(t => t.name).join(', ')}`);
343
+ const objects = [];
344
+ const loadGracefully = process.argv.includes('--never-exported');
345
+ const isTypeIncluded = obj => types.some(type => type.name === obj.constructor.name); // avoid using "obj instanceof type" for Harmony to call this function successfully
346
+ await (0, _toolboxPromise().pMapPool)(refs, async ref => {
347
+ const object = loadGracefully ? await this.loadRefDeleteIfInvalid(ref) : await this.loadRefOnlyIfType(ref, types);
348
+ if (!object) return;
349
+ if (loadGracefully && !isTypeIncluded(object)) return;
350
+ objects.push(object);
351
+ }, {
352
+ concurrency,
353
+ onCompletedChunk: completed => {
354
+ if (completed % 1000 === 0) _legacy2().logger.debug(`Repository.list, completed ${completed} out of ${refs.length}`);
355
+ }
356
+ });
357
+ return objects;
358
+ }
359
+ async loadRefDeleteIfInvalid(ref) {
360
+ try {
361
+ return await this.load(ref, true);
362
+ } catch (err) {
363
+ // this is needed temporarily to allow `bit reset --never-exported` to fix the bit-id-comp-id error.
364
+ // in a few months, we can remove this condition (around min 2024)
365
+ if (err.constructor.name === 'BitIdCompIdError' || err.constructor.name === 'MissingScope') {
366
+ _legacy2().logger.debug(`bit-id-comp-id error, moving an object to trash ${ref.toString()}`);
367
+ await this.moveOneObjectToTrash(ref);
368
+ return undefined;
369
+ }
370
+ throw err;
371
+ }
372
+ }
373
+ async loadRefOnlyIfType(ref, types) {
374
+ const objectPath = this.objectPath(ref);
375
+ const fileContentsRaw = await _fsExtra().default.readFile(objectPath);
376
+ const fileContents = this.onRead(fileContentsRaw);
377
+ const typeNames = types.map(type => type.name);
378
+ const parsedObject = await _object().default.parseObjectOnlyIfType(fileContents, typeNames, objectPath);
379
+ return parsedObject;
380
+ }
381
+ async listRefs(cwd = this.getPath()) {
382
+ const matches = await (0, _legacy3().glob)(path().join('*', '*'), {
383
+ cwd
384
+ });
385
+ const refs = matches.map(str => {
386
+ const hash = str.replace(path().sep, '');
387
+ if (!(0, _componentVersion().isSnap)(hash)) {
388
+ _legacy2().logger.error(`fatal: the file "${str}" is not a valid bit object path`);
389
+ return null;
390
+ }
391
+ return new (_ref().default)(hash);
392
+ });
393
+ return (0, _lodash().compact)(refs);
394
+ }
395
+ async listRefsStartWith(shortHash) {
396
+ const pathPrefix = this.hashPath(shortHash);
397
+ const matches = await (0, _legacy3().glob)(`${pathPrefix}*`, {
398
+ cwd: this.getPath()
399
+ });
400
+ const refs = matches.map(str => {
401
+ const hash = str.replace(path().sep, '');
402
+ if (!(0, _componentVersion().isSnap)(hash)) {
403
+ _legacy2().logger.error(`fatal: the file "${str}" is not a valid bit object path`);
404
+ return null;
405
+ }
406
+ return new (_ref().default)(hash);
407
+ });
408
+ return (0, _lodash().compact)(refs);
409
+ }
410
+ async listRawObjects() {
411
+ const refs = await this.listRefs();
412
+ const concurrency = (0, _harmonyModules().concurrentIOLimit)();
413
+ return (0, _toolboxPromise().pMapPool)(refs, async ref => {
414
+ try {
415
+ const buffer = await this.loadRaw(ref);
416
+ const bitRawObject = await _rawObject().default.fromDeflatedBuffer(buffer, ref.hash);
417
+ return bitRawObject;
418
+ } catch {
419
+ _legacy2().logger.error(`Couldn't load the ref ${ref} this object is probably corrupted and should be delete`);
420
+ return null;
421
+ }
422
+ }, {
423
+ concurrency
424
+ });
425
+ }
426
+ async listObjectsFromIndex(indexType, filter) {
427
+ const hashes = filter ? this.scopeIndex.getHashesByQuery(indexType, filter) : this.scopeIndex.getHashes(indexType);
428
+ return this._getBitObjectsByHashes(hashes);
429
+ }
430
+ getHashFromIndex(indexType, filter) {
431
+ const hashes = this.scopeIndex.getHashesByQuery(indexType, filter);
432
+ if (hashes.length > 2) throw new Error('getHashFromIndex expect to get zero or one result');
433
+ return hashes.length ? hashes[0] : null;
434
+ }
435
+ async _getBitObjectsByHashes(hashes) {
436
+ const missingIndexItems = [];
437
+ const bitObjects = await Promise.all(hashes.map(async hash => {
438
+ const bitObject = await this.load(new (_ref().default)(hash));
439
+ if (!bitObject) {
440
+ const indexItem = this.scopeIndex.find(hash);
441
+ if (!indexItem) throw new Error(`_getBitObjectsByHashes failed finding ${hash}`);
442
+ missingIndexItems.push(indexItem);
443
+ return;
444
+ }
445
+ return bitObject;
446
+ }));
447
+ if (missingIndexItems.length) {
448
+ this.scopeIndex.removeMany(missingIndexItems.map(item => new (_ref().default)(item.hash)));
449
+ await this.scopeIndex.write();
450
+ const missingStringified = missingIndexItems.map(item => item.toIdentifierString());
451
+ throw new (_legacy4().OutdatedIndexJson)(missingStringified);
452
+ }
453
+ return (0, _lodash().compact)(bitObjects);
454
+ }
455
+ async loadOptionallyCreateScopeIndex() {
456
+ try {
457
+ const scopeIndex = await _scopeIndex().ScopeIndex.load(this.scopePath);
458
+ return scopeIndex;
459
+ } catch (err) {
460
+ if (err.code === 'ENOENT') {
461
+ const bitObjects = await this.list([_models().ModelComponent, _models().Lane]);
462
+ const scopeIndex = _scopeIndex().ScopeIndex.create(this.scopePath);
463
+ const added = scopeIndex.addMany(bitObjects);
464
+ if (added) await scopeIndex.write();
465
+ return scopeIndex;
466
+ }
467
+ throw err;
468
+ }
469
+ }
470
+ async loadRaw(ref) {
471
+ if (ref.hash.length < _componentVersion().HASH_SIZE) {
472
+ ref = await this.getFullRefFromShortHash(ref);
473
+ }
474
+ const raw = await _fsExtra().default.readFile(this.objectPath(ref));
475
+ // Run hook to transform content pre reading
476
+ const transformedContent = this.onRead(raw);
477
+ // uncomment to debug the transformed objects by onRead
478
+ // console.log('transformedContent loadRaw', ref.toString(), BitObject.parseSync(transformedContent).getType());
479
+ return transformedContent;
480
+ }
481
+ async getFullRefFromShortHash(ref) {
482
+ const refs = await this.listRefsStartWith(ref);
483
+ if (refs.length > 1) {
484
+ throw new Error(`found ${refs.length} objects with the same short hash ${ref.toString()}, please use longer hash`);
485
+ }
486
+ if (refs.length === 0) {
487
+ throw new Error(`failed finding an object with the short hash ${ref.toString()}`);
488
+ }
489
+ return refs[0];
490
+ }
491
+ async loadManyRaw(refs) {
492
+ const concurrency = (0, _harmonyModules().concurrentIOLimit)();
493
+ const uniqRefs = (0, _lodash().uniqBy)(refs, 'hash');
494
+ return (0, _toolboxPromise().pMapPool)(uniqRefs, async ref => ({
495
+ ref,
496
+ buffer: await this.loadRaw(ref)
497
+ }), {
498
+ concurrency
499
+ });
500
+ }
501
+ async loadManyRawIgnoreMissing(refs) {
502
+ const concurrency = (0, _harmonyModules().concurrentIOLimit)();
503
+ const results = await (0, _toolboxPromise().pMapPool)(refs, async ref => {
504
+ try {
505
+ const buffer = await this.loadRaw(ref);
506
+ return {
507
+ ref,
508
+ buffer
509
+ };
510
+ } catch (err) {
511
+ if (err.code === 'ENOENT') return null;
512
+ throw err;
513
+ }
514
+ }, {
515
+ concurrency
516
+ });
517
+ return (0, _lodash().compact)(results);
518
+ }
519
+ async loadRawObject(ref) {
520
+ const buffer = await this.loadRaw(ref);
521
+ const bitRawObject = await _rawObject().default.fromDeflatedBuffer(buffer, ref.hash);
522
+ return bitRawObject;
523
+ }
524
+
525
+ /**
526
+ * prefer using `this.load()` for an async version, which also writes to the cache
527
+ */
528
+ loadSync(ref, throws = true) {
529
+ try {
530
+ const objectFile = _fsExtra().default.readFileSync(this.objectPath(ref));
531
+ // Run hook to transform content pre reading
532
+ const transformedContent = this.onRead(objectFile);
533
+ return _object().default.parseSync(transformedContent);
534
+ } catch {
535
+ if (throws) {
536
+ throw new (_legacy4().HashNotFound)(ref.toString());
537
+ }
538
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
539
+ return null;
540
+ }
541
+ }
542
+ setCache(object) {
543
+ this.cache.set(object.hash().toString(), object);
544
+ return this;
545
+ }
546
+ getCache(ref) {
547
+ return this.cache.get(ref.toString());
548
+ }
549
+ removeFromCache(ref) {
550
+ this.cache.delete(ref.toString());
551
+ }
552
+ async clearCache() {
553
+ _legacy2().logger.debug('repository.clearCache');
554
+ this.cache.deleteAll();
555
+ await this.init();
556
+ }
557
+ clearObjectsFromCache() {
558
+ _legacy2().logger.debug('repository.clearObjectsFromCache');
559
+ this.cache.deleteAll();
560
+ }
561
+ backup(dirName) {
562
+ const backupDir = this.getBackupPath(dirName);
563
+ const objectsDir = this.getPath();
564
+ _legacy2().logger.debug(`making a backup of all objects from ${objectsDir} to ${backupDir}`);
565
+ _fsExtra().default.emptyDirSync(backupDir);
566
+ _fsExtra().default.copySync(objectsDir, backupDir);
567
+ }
568
+ add(object) {
569
+ // console.trace(`repository: adding object ${object?.hash().toString()}`);
570
+ if (!object) return this;
571
+ // leave the following commented log message, it is very useful for debugging but too verbose when not needed.
572
+ // logger.debug(`repository: adding object ${object.hash().toString()} which consist of the following id: ${object.id()}`);
573
+ this.objects[object.hash().toString()] = object;
574
+ this.setCache(object);
575
+ return this;
576
+ }
577
+ addMany(objects) {
578
+ if (!objects || !objects.length) return this;
579
+ objects.forEach(obj => this.add(obj));
580
+ return this;
581
+ }
582
+ removeObject(ref) {
583
+ this.objectsToRemove.push(ref);
584
+ }
585
+ removeManyObjects(refs) {
586
+ if (!refs || !refs.length) return;
587
+ refs.forEach(ref => this.removeObject(ref));
588
+ }
589
+ findMany(refs) {
590
+ return Promise.all(refs.map(ref => this.load(ref)));
591
+ }
592
+
593
+ /**
594
+ * important! use this method only for commands that are non running on an http server.
595
+ *
596
+ * it's better to remove/delete objects directly and not using the `objects` member.
597
+ * it helps to avoid multiple processes running concurrently on an http server.
598
+ *
599
+ * persist objects changes (added and removed) into the filesystem
600
+ * do not call this function multiple times in parallel, otherwise, it'll damage the index.json file.
601
+ * call this function only once after you added and removed all applicable objects.
602
+ */
603
+ async persist(validate = true) {
604
+ // do not let two requests enter this critical area, otherwise, refs/index.json/objects could
605
+ // be corrupted
606
+ _legacy2().logger.debug(`Repository.persist, going to acquire a lock`);
607
+ await this.persistMutex.runExclusive(async () => {
608
+ _legacy2().logger.debug(`Repository.persist, validate = ${validate.toString()}, a lock has been acquired`);
609
+ await this.deleteObjectsFromFS(this.objectsToRemove);
610
+ this.validateObjects(validate, Object.values(this.objects));
611
+ await this.writeObjectsToTheFS(Object.values(this.objects));
612
+ await this.writeRemoteLanes();
613
+ await this.unmergedComponents.write();
614
+ });
615
+ _legacy2().logger.debug(`Repository.persist, completed. the lock has been released`);
616
+ this.clearObjects();
617
+ if (Repository.onPostObjectsPersist) {
618
+ Repository.onPostObjectsPersist().catch(err => {
619
+ _legacy2().logger.error('fatal: onPostObjectsPersist encountered an error (this error does not stop the process)', err);
620
+ });
621
+ }
622
+ }
623
+ async writeRemoteLanes() {
624
+ await this.remoteLanes.write();
625
+ }
626
+
627
+ /**
628
+ * this is especially critical for http server, where one process lives long and serves multiple
629
+ * exports. without this, the objects get accumulated over time and being rewritten over and over
630
+ * again.
631
+ */
632
+ clearObjects() {
633
+ this.objects = {};
634
+ this.objectsToRemove = [];
635
+ }
636
+
637
+ /**
638
+ * normally, the validation step takes place just before the acutal writing of the file.
639
+ * however, this can be an issue where a component has an invalid version. the component could
640
+ * be saved before validating the version (see #1727). that's why we validate here before writing
641
+ * anything to the filesystem.
642
+ * the open question here is whether should we validate again before the actual writing or it
643
+ * should be enough to validate here?
644
+ * for now, it does validate again before saving, only to be 100% sure nothing happens in a few
645
+ * lines of code until the actual writing. however, if the performance penalty is noticeable, we
646
+ * can easily revert it by changing `bitObject.validateBeforePersist = false` line run regardless
647
+ * the `validate` argument.
648
+ */
649
+ validateObjects(validate, objects) {
650
+ objects.forEach(bitObject => {
651
+ // @ts-ignore some BitObject classes have validate() method
652
+ if (validate && bitObject.validate) {
653
+ // @ts-ignore
654
+ bitObject.validate();
655
+ }
656
+ if (!validate) {
657
+ bitObject.validateBeforePersist = false;
658
+ }
659
+ });
660
+ }
661
+ async deleteObjectsFromFS(refs) {
662
+ if (!refs.length) return;
663
+ const uniqRefs = (0, _lodash().uniqBy)(refs, 'hash');
664
+ _legacy2().logger.debug(`Repository._deleteMany: deleting ${uniqRefs.length} objects`);
665
+ const concurrency = (0, _harmonyModules().concurrentIOLimit)();
666
+ await (0, _toolboxPromise().pMapPool)(uniqRefs, ref => this._deleteOne(ref), {
667
+ concurrency
668
+ });
669
+ const removed = this.scopeIndex.removeMany(uniqRefs);
670
+ if (removed) await this.scopeIndex.write();
671
+ }
672
+ async moveObjectsToDir(refs, dir) {
673
+ if (!refs.length) return;
674
+ const uniqRefs = (0, _lodash().uniqBy)(refs, 'hash');
675
+ _legacy2().logger.debug(`Repository.moveObjectsToDir: ${uniqRefs.length} objects`);
676
+ const concurrency = (0, _harmonyModules().concurrentIOLimit)();
677
+ await (0, _toolboxPromise().pMapPool)(uniqRefs, ref => this.moveOneObjectToDir(ref, dir), {
678
+ concurrency
679
+ });
680
+ const removed = this.scopeIndex.removeMany(uniqRefs);
681
+ if (removed) await this.scopeIndex.write();
682
+ }
683
+ async moveObjectsToTrash(refs) {
684
+ await this.moveObjectsToDir(refs, TRASH_DIR);
685
+ }
686
+ async listTrash() {
687
+ return this.listRefs(this.getTrashDir());
688
+ }
689
+ async getFromTrash(refs) {
690
+ const objectsFromTrash = await Promise.all(refs.map(async ref => {
691
+ const trashObjPath = path().join(this.getTrashDir(), this.hashPath(ref));
692
+ let buffer;
693
+ try {
694
+ buffer = await _fsExtra().default.readFile(trashObjPath);
695
+ } catch (err) {
696
+ if (err.code === 'ENOENT') {
697
+ throw new (_bitError().BitError)(`unable to find the object ${ref.toString()} in the trash`);
698
+ }
699
+ throw err;
700
+ }
701
+ return _object().default.parseObject(buffer, trashObjPath);
702
+ }));
703
+ return objectsFromTrash;
704
+ }
705
+ async restoreFromTrash(refs) {
706
+ _legacy2().logger.debug(`Repository.restoreFromTrash: ${refs.length} objects`);
707
+ const objectsFromTrash = await this.getFromTrash(refs);
708
+ await this.writeObjectsToTheFS(objectsFromTrash);
709
+ }
710
+ async restoreFromDir(dir, overwrite = false) {
711
+ await _fsExtra().default.copy(path().join(this.scopePath, dir), this.getPath(), {
712
+ overwrite
713
+ });
714
+ }
715
+ async moveOneObjectToDir(ref, dir) {
716
+ const currentPath = this.objectPath(ref);
717
+ const absDir = path().join(this.scopePath, dir);
718
+ const fullPath = path().join(absDir, this.hashPath(ref));
719
+ await _fsExtra().default.move(currentPath, fullPath, {
720
+ overwrite: true
721
+ });
722
+ this.removeFromCache(ref);
723
+ }
724
+ async moveOneObjectToTrash(ref) {
725
+ await this.moveOneObjectToDir(ref, TRASH_DIR);
726
+ }
727
+ async deleteRecordsFromUnmergedComponents(compIds) {
728
+ this.unmergedComponents.removeMultipleComponents(compIds);
729
+ await this.unmergedComponents.write();
730
+ }
731
+
732
+ /**
733
+ * write all objects to the FS and index the components/lanes/symlink objects
734
+ */
735
+ async writeObjectsToTheFS(objects) {
736
+ const count = objects.length;
737
+ if (!count) return;
738
+ _legacy2().logger.trace(`Repository.writeObjectsToTheFS: started writing ${count} objects`);
739
+ const concurrency = (0, _harmonyModules().concurrentIOLimit)();
740
+ await (0, _toolboxPromise().pMapPool)(objects, obj => this._writeOne(obj), {
741
+ concurrency
742
+ });
743
+ _legacy2().logger.trace(`Repository.writeObjectsToTheFS: completed writing ${count} objects`);
744
+ const added = this.scopeIndex.addMany(objects);
745
+ if (added) await this.scopeIndex.write();
746
+ }
747
+
748
+ /**
749
+ * do not call this method directly. always call this.removeObject() and once done with all objects,
750
+ * call this.persist()
751
+ */
752
+ _deleteOne(ref) {
753
+ this.removeFromCache(ref);
754
+ const pathToDelete = this.objectPath(ref);
755
+ _legacy2().logger.trace(`repository._deleteOne: deleting ${pathToDelete}`);
756
+ return removeFile(pathToDelete, true);
757
+ }
758
+
759
+ /**
760
+ * always prefer this.persist() or this.writeObjectsToTheFS()
761
+ * this method doesn't write to scopeIndex. so using this method for ModelComponent or
762
+ * Symlink makes the index outdated.
763
+ */
764
+ async _writeOne(object) {
765
+ const contents = await object.compress();
766
+ const options = {};
767
+ if (this.scopeJson.groupName) options.gid = await resolveGroupId(this.scopeJson.groupName);
768
+ const hash = object.hash();
769
+ if (this.cache.has(hash.toString())) this.cache.set(hash.toString(), object); // update the cache
770
+ const objectPath = this.objectPath(hash);
771
+ _legacy2().logger.trace(`repository._writeOne: ${objectPath}`);
772
+ // Run hook to transform content pre persisting
773
+ const transformedContent = this.onPersist(contents);
774
+ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
775
+ return (0, _legacy3().writeFile)(objectPath, transformedContent, options);
776
+ }
777
+ async writeObjectsToPendingDir(objectList, pendingDir) {
778
+ const options = {};
779
+ if (this.scopeJson.groupName) options.gid = await resolveGroupId(this.scopeJson.groupName);
780
+ await Promise.all(objectList.objects.map(async object => {
781
+ const objPath = path().join(pendingDir, this.hashPath(object.ref));
782
+ await (0, _legacy3().writeFile)(objPath, object.buffer, options);
783
+ }));
784
+ }
785
+ async readObjectsFromPendingDir(pendingDir) {
786
+ const refs = await this.listRefs(pendingDir);
787
+ const objects = await Promise.all(refs.map(async ref => {
788
+ const buffer = await _fsExtra().default.readFile(path().join(pendingDir, this.hashPath(ref)));
789
+ return {
790
+ ref,
791
+ buffer
792
+ };
793
+ }));
794
+ return new (_objectList().ObjectList)(objects);
795
+ }
796
+ hashPath(ref) {
797
+ const hash = ref.toString();
798
+ return path().join(hash.slice(0, 2), hash.slice(2));
799
+ }
800
+ }
801
+ exports.default = Repository;
802
+ _defineProperty(Repository, "onPostObjectsPersist", void 0);
803
+ /**
804
+ * Hook for transforming content before objects are persisted to the filesystem.
805
+ * Note: This function cannot be async because it's used by the synchronous `loadSync` method
806
+ * which needs to maintain sync behavior for compatibility with existing code.
807
+ */
808
+ _defineProperty(Repository, "onPreObjectPersist", void 0);
809
+ /**
810
+ * Hook for transforming content after objects are read from the filesystem.
811
+ * Note: This function cannot be async because it's used by the synchronous `loadSync` method
812
+ * which needs to maintain sync behavior for compatibility with existing code.
813
+ */
814
+ _defineProperty(Repository, "onPostObjectRead", void 0);
815
+ async function removeFile(filePath, propagateDirs = false) {
816
+ try {
817
+ await _fsExtra().default.unlink(filePath);
818
+ } catch (err) {
819
+ if (err.code === 'ENOENT') {
820
+ // the file doesn't exist, that's fine, no need to do anything
821
+ return false;
822
+ }
823
+ throw err;
824
+ }
825
+ if (!propagateDirs) return true;
826
+ const {
827
+ dir
828
+ } = path().parse(filePath);
829
+ await (0, _toolboxFs().removeEmptyDir)(dir);
830
+ return true;
831
+ }
832
+ function resolveGroupId(groupName) {
833
+ return new Promise((resolve, reject) => {
834
+ (0, _uidNumber().default)(null, groupName, (err, uid, gid) => {
835
+ if (err) {
836
+ _legacy2().logger.error('resolveGroupId', err);
837
+ if (err.message.includes('EPERM')) {
838
+ return reject(new (_bitError().BitError)(`unable to resolve group id of "${groupName}", current user does not have sufficient permissions`));
839
+ }
840
+ if (err.message.includes('group id does not exist')) {
841
+ return reject(new (_bitError().BitError)(`unable to resolve group id of "${groupName}", the group does not exist`));
842
+ }
843
+ return reject(new (_bitError().BitError)(`unable to resolve group id of "${groupName}", got an error ${err.message}`));
844
+ }
845
+ // on Windows it'll always be null
846
+ return resolve(gid);
847
+ });
848
+ });
849
+ }
850
+
851
+ //# sourceMappingURL=repository.js.map