@teambit/pnpm 1.0.1169 → 1.0.1171

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.
@@ -25,6 +25,13 @@ function _lodash() {
25
25
  };
26
26
  return data;
27
27
  }
28
+ function nodeApi() {
29
+ const data = _interopRequireWildcard(require("@pnpm/napi"));
30
+ nodeApi = function () {
31
+ return data;
32
+ };
33
+ return data;
34
+ }
28
35
  function _dependenciesPnpm() {
29
36
  const data = require("@teambit/dependencies.pnpm.dep-path");
30
37
  _dependenciesPnpm = function () {
@@ -39,21 +46,8 @@ function _preserveLoadedVirtualStoreDirs() {
39
46
  };
40
47
  return data;
41
48
  }
49
+ 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); }
42
50
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
43
- let lockfileFsPromise;
44
- function loadLockfileFs() {
45
- lockfileFsPromise ??= (async () => {
46
- const {
47
- loadEsm
48
- } = require('./load-pnpm-esm.cjs');
49
- const {
50
- lockfileFs
51
- } = await loadEsm();
52
- return lockfileFs;
53
- })();
54
- return lockfileFsPromise;
55
- }
56
-
57
51
  /**
58
52
  * Reads the private lockfile at node_modules/.pnpm/lock.yaml
59
53
  * and removes any directories from node_modules/.pnpm that are not listed in the lockfile.
@@ -62,13 +56,19 @@ async function pnpmPruneModules(rootDir) {
62
56
  const virtualStoreDir = _path().default.join(rootDir, 'node_modules/.pnpm');
63
57
  const pkgDirs = await readPackageDirsFromVirtualStore(virtualStoreDir);
64
58
  if (pkgDirs.length === 0) return;
65
- const {
66
- readCurrentLockfile
67
- } = await loadLockfileFs();
68
- const lockfile = await readCurrentLockfile(virtualStoreDir, {
69
- ignoreIncompatible: false
59
+ const lockfile = await nodeApi().readLockfile({
60
+ dir: rootDir,
61
+ kind: 'current'
70
62
  });
71
- const dirsShouldBePresent = Object.keys(lockfile?.packages ?? {}).map(depPath => (0, _dependenciesPnpm().depPathToDirName)(depPath));
63
+ // No current lockfile means nothing is known about what was materialized,
64
+ // not that nothing belongs here — pruning against an empty set would empty
65
+ // the virtual store and leave the workspace needing a reinstall.
66
+ if (lockfile == null) return;
67
+ // The virtual store's directory names come from the peer-suffixed dep
68
+ // paths, which is what `snapshots` is keyed by; `packages` is keyed
69
+ // without the suffix and would not match.
70
+ const snapshots = lockfile.snapshots ?? {};
71
+ const dirsShouldBePresent = Object.keys(snapshots).map(depPath => (0, _dependenciesPnpm().depPathToDirName)(depPath));
72
72
  const extraneous = (0, _lodash().difference)(pkgDirs, dirsShouldBePresent);
73
73
  // the usual case, and the one worth keeping cheap: scanning the loaded modules below is
74
74
  // proportional to how much this process has loaded, and with nothing to remove it decides nothing
@@ -1 +1 @@
1
- {"version":3,"names":["_fsExtra","data","_interopRequireDefault","require","_path","_lodash","_dependenciesPnpm","_preserveLoadedVirtualStoreDirs","e","__esModule","default","lockfileFsPromise","loadLockfileFs","loadEsm","lockfileFs","pnpmPruneModules","rootDir","virtualStoreDir","path","join","pkgDirs","readPackageDirsFromVirtualStore","length","readCurrentLockfile","lockfile","ignoreIncompatible","dirsShouldBePresent","Object","keys","packages","map","depPath","depPathToDirName","extraneous","difference","loadedByThisProcess","loadedVirtualStoreDirNames","Promise","all","filter","dir","has","fs","remove","allDirs","readdir","err","code"],"sources":["pnpm-prune-modules.ts"],"sourcesContent":["import fs from 'fs-extra';\nimport path from 'path';\nimport { difference } from 'lodash';\nimport type * as LockfileFs from '@pnpm/lockfile.fs';\nimport { depPathToDirName } from '@teambit/dependencies.pnpm.dep-path';\nimport { loadedVirtualStoreDirNames } from './preserve-loaded-virtual-store-dirs';\n\ntype LockfileFsModule = typeof LockfileFs;\nlet lockfileFsPromise: Promise<LockfileFsModule> | undefined;\n\nfunction loadLockfileFs(): Promise<LockfileFsModule> {\n lockfileFsPromise ??= (async () => {\n const { loadEsm } = require('./load-pnpm-esm.cjs') as {\n loadEsm: () => Promise<{ lockfileFs: LockfileFsModule }>;\n };\n const { lockfileFs } = await loadEsm();\n return lockfileFs;\n })();\n return lockfileFsPromise;\n}\n\n/**\n * Reads the private lockfile at node_modules/.pnpm/lock.yaml\n * and removes any directories from node_modules/.pnpm that are not listed in the lockfile.\n */\nexport async function pnpmPruneModules(rootDir: string): Promise<void> {\n const virtualStoreDir = path.join(rootDir, 'node_modules/.pnpm');\n const pkgDirs = await readPackageDirsFromVirtualStore(virtualStoreDir);\n if (pkgDirs.length === 0) return;\n const { readCurrentLockfile } = await loadLockfileFs();\n const lockfile = await readCurrentLockfile(virtualStoreDir, { ignoreIncompatible: false });\n const dirsShouldBePresent = Object.keys(lockfile?.packages ?? {}).map((depPath) => depPathToDirName(depPath));\n const extraneous = difference(pkgDirs, dirsShouldBePresent);\n // the usual case, and the one worth keeping cheap: scanning the loaded modules below is\n // proportional to how much this process has loaded, and with nothing to remove it decides nothing\n if (extraneous.length === 0) return;\n // never remove a directory the running process has loaded modules from. an install that re-keys\n // a loaded package to a new peer hash restores the old directory so deferred requires keep\n // working (see preserve-loaded-virtual-store-dirs.ts); that directory is intentionally absent\n // from the lockfile, and deleting it here would re-break exactly what the restore fixed. a later\n // command's prune, whose process has nothing loaded from it, cleans it up.\n const loadedByThisProcess = loadedVirtualStoreDirNames(virtualStoreDir);\n await Promise.all(\n extraneous\n .filter((dir) => !loadedByThisProcess.has(dir))\n .map((dir) => fs.remove(path.join(virtualStoreDir, dir)))\n );\n}\n\n/**\n * The project-local virtual store may hold no package directories at all: with the global virtual\n * store enabled the packages live under `<storeDir>/links` (pruned by the engine itself) and only\n * `lock.yaml` and the hoisted `node_modules` remain here. A `lockfileOnly` install leaves the\n * directory missing entirely. Both cases mean \"nothing for us to prune\".\n */\nasync function readPackageDirsFromVirtualStore(virtualStoreDir: string): Promise<string[]> {\n let allDirs: string[];\n try {\n allDirs = await fs.readdir(virtualStoreDir);\n } catch (err: any) {\n if (err.code === 'ENOENT') return [];\n throw err;\n }\n return allDirs.filter((dir) => dir !== 'lock.yaml' && dir !== 'node_modules');\n}\n"],"mappings":";;;;;;AAAA,SAAAA,SAAA;EAAA,MAAAC,IAAA,GAAAC,sBAAA,CAAAC,OAAA;EAAAH,QAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,MAAA;EAAA,MAAAH,IAAA,GAAAC,sBAAA,CAAAC,OAAA;EAAAC,KAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAI,QAAA;EAAA,MAAAJ,IAAA,GAAAE,OAAA;EAAAE,OAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,SAAAK,kBAAA;EAAA,MAAAL,IAAA,GAAAE,OAAA;EAAAG,iBAAA,YAAAA,CAAA;IAAA,OAAAL,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAM,gCAAA;EAAA,MAAAN,IAAA,GAAAE,OAAA;EAAAI,+BAAA,YAAAA,CAAA;IAAA,OAAAN,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAAkF,SAAAC,uBAAAM,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAGlF,IAAIG,iBAAwD;AAE5D,SAASC,cAAcA,CAAA,EAA8B;EACnDD,iBAAiB,KAAK,CAAC,YAAY;IACjC,MAAM;MAAEE;IAAQ,CAAC,GAAG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H;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAenB,+BAA+BA,CAACJ,eAAuB,EAAqB;EACzF,IAAI2B,OAAiB;EACrB,IAAI;IACFA,OAAO,GAAG,MAAMF,kBAAE,CAACG,OAAO,CAAC5B,eAAe,CAAC;EAC7C,CAAC,CAAC,OAAO6B,GAAQ,EAAE;IACjB,IAAIA,GAAG,CAACC,IAAI,KAAK,QAAQ,EAAE,OAAO,EAAE;IACpC,MAAMD,GAAG;EACX;EACA,OAAOF,OAAO,CAACL,MAAM,CAAEC,GAAG,IAAKA,GAAG,KAAK,WAAW,IAAIA,GAAG,KAAK,cAAc,CAAC;AAC/E","ignoreList":[]}
1
+ {"version":3,"names":["_fsExtra","data","_interopRequireDefault","require","_path","_lodash","nodeApi","_interopRequireWildcard","_dependenciesPnpm","_preserveLoadedVirtualStoreDirs","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","pnpmPruneModules","rootDir","virtualStoreDir","path","join","pkgDirs","readPackageDirsFromVirtualStore","length","lockfile","readLockfile","dir","kind","snapshots","dirsShouldBePresent","keys","map","depPath","depPathToDirName","extraneous","difference","loadedByThisProcess","loadedVirtualStoreDirNames","Promise","all","filter","fs","remove","allDirs","readdir","err","code"],"sources":["pnpm-prune-modules.ts"],"sourcesContent":["import fs from 'fs-extra';\nimport path from 'path';\nimport { difference } from 'lodash';\nimport * as nodeApi from '@pnpm/napi';\nimport { depPathToDirName } from '@teambit/dependencies.pnpm.dep-path';\nimport { loadedVirtualStoreDirNames } from './preserve-loaded-virtual-store-dirs';\n\n/**\n * Reads the private lockfile at node_modules/.pnpm/lock.yaml\n * and removes any directories from node_modules/.pnpm that are not listed in the lockfile.\n */\nexport async function pnpmPruneModules(rootDir: string): Promise<void> {\n const virtualStoreDir = path.join(rootDir, 'node_modules/.pnpm');\n const pkgDirs = await readPackageDirsFromVirtualStore(virtualStoreDir);\n if (pkgDirs.length === 0) return;\n const lockfile = await nodeApi.readLockfile({ dir: rootDir, kind: 'current' });\n // No current lockfile means nothing is known about what was materialized,\n // not that nothing belongs here — pruning against an empty set would empty\n // the virtual store and leave the workspace needing a reinstall.\n if (lockfile == null) return;\n // The virtual store's directory names come from the peer-suffixed dep\n // paths, which is what `snapshots` is keyed by; `packages` is keyed\n // without the suffix and would not match.\n const snapshots = (lockfile.snapshots ?? {}) as Record<string, unknown>;\n const dirsShouldBePresent = Object.keys(snapshots).map((depPath) => depPathToDirName(depPath));\n const extraneous = difference(pkgDirs, dirsShouldBePresent);\n // the usual case, and the one worth keeping cheap: scanning the loaded modules below is\n // proportional to how much this process has loaded, and with nothing to remove it decides nothing\n if (extraneous.length === 0) return;\n // never remove a directory the running process has loaded modules from. an install that re-keys\n // a loaded package to a new peer hash restores the old directory so deferred requires keep\n // working (see preserve-loaded-virtual-store-dirs.ts); that directory is intentionally absent\n // from the lockfile, and deleting it here would re-break exactly what the restore fixed. a later\n // command's prune, whose process has nothing loaded from it, cleans it up.\n const loadedByThisProcess = loadedVirtualStoreDirNames(virtualStoreDir);\n await Promise.all(\n extraneous\n .filter((dir) => !loadedByThisProcess.has(dir))\n .map((dir) => fs.remove(path.join(virtualStoreDir, dir)))\n );\n}\n\n/**\n * The project-local virtual store may hold no package directories at all: with the global virtual\n * store enabled the packages live under `<storeDir>/links` (pruned by the engine itself) and only\n * `lock.yaml` and the hoisted `node_modules` remain here. A `lockfileOnly` install leaves the\n * directory missing entirely. Both cases mean \"nothing for us to prune\".\n */\nasync function readPackageDirsFromVirtualStore(virtualStoreDir: string): Promise<string[]> {\n let allDirs: string[];\n try {\n allDirs = await fs.readdir(virtualStoreDir);\n } catch (err: any) {\n if (err.code === 'ENOENT') return [];\n throw err;\n }\n return allDirs.filter((dir) => dir !== 'lock.yaml' && dir !== 'node_modules');\n}\n"],"mappings":";;;;;;AAAA,SAAAA,SAAA;EAAA,MAAAC,IAAA,GAAAC,sBAAA,CAAAC,OAAA;EAAA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EAC9F,MAAME,UAAU,GAAG,IAAAC,oBAAU,EAACd,OAAO,EAAEQ,mBAAmB,CAAC;EAC3D;EACA;EACA,IAAIK,UAAU,CAACX,MAAM,KAAK,CAAC,EAAE;EAC7B;EACA;EACA;EACA;EACA;EACA,MAAMa,mBAAmB,GAAG,IAAAC,4DAA0B,EAACnB,eAAe,CAAC;EACvE,MAAMoB,OAAO,CAACC,GAAG,CACfL,UAAU,CACPM,MAAM,CAAEd,GAAG,IAAK,CAACU,mBAAmB,CAAC5B,GAAG,CAACkB,GAAG,CAAC,CAAC,CAC9CK,GAAG,CAAEL,GAAG,IAAKe,kBAAE,CAACC,MAAM,CAACvB,eAAI,CAACC,IAAI,CAACF,eAAe,EAAEQ,GAAG,CAAC,CAAC,CAC5D,CAAC;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAeJ,+BAA+BA,CAACJ,eAAuB,EAAqB;EACzF,IAAIyB,OAAiB;EACrB,IAAI;IACFA,OAAO,GAAG,MAAMF,kBAAE,CAACG,OAAO,CAAC1B,eAAe,CAAC;EAC7C,CAAC,CAAC,OAAO2B,GAAQ,EAAE;IACjB,IAAIA,GAAG,CAACC,IAAI,KAAK,QAAQ,EAAE,OAAO,EAAE;IACpC,MAAMD,GAAG;EACX;EACA,OAAOF,OAAO,CAACH,MAAM,CAAEd,GAAG,IAAKA,GAAG,KAAK,WAAW,IAAIA,GAAG,KAAK,cAAc,CAAC;AAC/E","ignoreList":[]}
@@ -4,7 +4,6 @@ import { Registries } from '@teambit/pkg.entities.registry';
4
4
  import type { Logger } from '@teambit/logger';
5
5
  import type { PeerDependencyIssuesByProjects, ResolvedConfig } from '@pnpm/napi';
6
6
  import { type ProjectManifest, type DepPath } from '@pnpm/types';
7
- import type { Modules } from '@pnpm/installing.modules-yaml';
8
7
  import type { RebuildFn } from './lynx';
9
8
  import { type DependenciesGraph } from '@teambit/objects';
10
9
  export type { RebuildFn };
@@ -18,12 +17,19 @@ type ReadConfigResult = Promise<{
18
17
  config: ResolvedConfig;
19
18
  warnings: string[];
20
19
  }>;
20
+ /**
21
+ * The `.modules.yaml` fields Bit reads. The engine returns the whole
22
+ * manifest; only these are consumed here.
23
+ */
24
+ interface ModulesManifest {
25
+ injectedDeps?: Record<string, string[]>;
26
+ }
21
27
  export declare class PnpmPackageManager implements PackageManager {
22
28
  private depResolver;
23
29
  private logger;
24
30
  private cloud;
25
31
  readonly name = "pnpm";
26
- readonly modulesManifestCache: Map<string, Modules>;
32
+ readonly modulesManifestCache: Map<string, ModulesManifest>;
27
33
  private username;
28
34
  private _readConfig;
29
35
  readConfig: (dir?: string) => ReadConfigResult;
@@ -43,7 +49,7 @@ export declare class PnpmPackageManager implements PackageManager {
43
49
  getNetworkConfig?(): Promise<PackageManagerNetworkConfig>;
44
50
  getRegistries(): Promise<Registries>;
45
51
  getInjectedDirs(rootDir: string, componentDir: string, packageName: string): Promise<string[]>;
46
- _readModulesManifest(lockfileDir: string): Promise<Modules | undefined>;
52
+ _readModulesManifest(lockfileDir: string): Promise<ModulesManifest | undefined>;
47
53
  getWorkspaceDepsOfBitRoots(manifests: ProjectManifest[]): Record<string, string>;
48
54
  /**
49
55
  * pnpm's own shared `<storeDir>/links`.
@@ -25,13 +25,6 @@ function _harmonyModules() {
25
25
  };
26
26
  return data;
27
27
  }
28
- function _fs() {
29
- const data = _interopRequireDefault(require("fs"));
30
- _fs = function () {
31
- return data;
32
- };
33
- return data;
34
- }
35
28
  function _lodash() {
36
29
  const data = require("lodash");
37
30
  _lodash = function () {
@@ -39,27 +32,6 @@ function _lodash() {
39
32
  };
40
33
  return data;
41
34
  }
42
- function _lockfile() {
43
- const data = require("@pnpm/lockfile.filtering");
44
- _lockfile = function () {
45
- return data;
46
- };
47
- return data;
48
- }
49
- function _depsInspection() {
50
- const data = require("@pnpm/deps.inspection.tree-builder");
51
- _depsInspection = function () {
52
- return data;
53
- };
54
- return data;
55
- }
56
- function _depsInspection2() {
57
- const data = require("@pnpm/deps.inspection.list");
58
- _depsInspection2 = function () {
59
- return data;
60
- };
61
- return data;
62
- }
63
35
  function _legacy() {
64
36
  const data = require("@teambit/legacy.constants");
65
37
  _legacy = function () {
@@ -109,28 +81,25 @@ function _preserveLoadedVirtualStoreDirs() {
109
81
  };
110
82
  return data;
111
83
  }
112
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
113
84
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
114
85
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
115
86
  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; }
116
87
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
117
88
  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); }
118
- let pnpmEsmPromise;
119
- function loadPnpmEsm() {
120
- pnpmEsmPromise ??= (async () => {
121
- const {
122
- loadEsm
123
- } = require('./load-pnpm-esm.cjs');
124
- const {
125
- lockfileFs,
126
- modulesYaml
127
- } = await loadEsm();
128
- return {
129
- lockfileFs,
130
- modulesYaml
131
- };
132
- })();
133
- return pnpmEsmPromise;
89
+ /**
90
+ * The `.modules.yaml` fields Bit reads. The engine returns the whole
91
+ * manifest; only these are consumed here.
92
+ */
93
+
94
+ /** One importer entry of a lockfile, in the file's own shape. */
95
+
96
+ /**
97
+ * Required lazily so the native engine binary is not mapped into every
98
+ * `bit` process at startup (same convention as the `./lynx` require sites).
99
+ */
100
+ function loadNodeApi() {
101
+ // eslint-disable-next-line global-require, import/no-dynamic-require
102
+ return require('@pnpm/napi');
134
103
  }
135
104
  class PnpmPackageManager {
136
105
  constructor(depResolver, logger, cloud) {
@@ -174,29 +143,26 @@ class PnpmPackageManager {
174
143
  const graphLockfile = await (0, _lockfileDepsGraphConverter().convertGraphToLockfile)(dependenciesGraph, _objectSpread(_objectSpread({}, opts), {}, {
175
144
  resolve
176
145
  }));
177
- const {
178
- lockfileFs: {
179
- readWantedLockfile,
180
- writeLockfileFile,
181
- convertToLockfileFile: convertLockfileObjectToLockfileFile
182
- }
183
- } = await loadPnpmEsm();
146
+ const nodeApi = loadNodeApi();
184
147
  // Merge the graph-derived subset into any existing wanted lockfile rather than
185
148
  // overwriting. Only the importers, packages, and snapshots referenced by the
186
149
  // imported components' subgraph are re-stated here; every other workspace dep's
187
150
  // locked version must be preserved so pnpm doesn't re-resolve it to a newer
188
151
  // registry version.
189
- const existingLockfile = await readWantedLockfile(opts.rootDir, {
190
- ignoreIncompatible: true
152
+ const existingLockfile = await nodeApi.readLockfile({
153
+ dir: opts.rootDir
191
154
  });
192
- const mergedLockfile = existingLockfile ? mergeGraphLockfileIntoExisting(convertLockfileObjectToLockfileFile(existingLockfile), graphLockfile) : graphLockfile;
155
+ const mergedLockfile = existingLockfile ? mergeGraphLockfileIntoExisting(existingLockfile, graphLockfile) : graphLockfile;
193
156
  Object.assign(mergedLockfile, {
194
157
  bit: _objectSpread(_objectSpread({}, mergedLockfile.bit), {}, {
195
158
  restoredFromModel: true
196
159
  })
197
160
  });
161
+ await nodeApi.writeLockfile({
162
+ dir: opts.rootDir,
163
+ lockfile: mergedLockfile
164
+ });
198
165
  const lockfilePath = (0, _path().join)(opts.rootDir, 'pnpm-lock.yaml');
199
- await writeLockfileFile(lockfilePath, mergedLockfile);
200
166
  this.logger.debug(`generated a lockfile from dependencies graph at ${lockfilePath}`);
201
167
  if (process.env.DEPS_GRAPH_LOG) {
202
168
  // eslint-disable-next-line no-console
@@ -301,9 +267,7 @@ class PnpmPackageManager {
301
267
  hidePackageManagerOutput: installOptions.hidePackageManagerOutput,
302
268
  reportOptions: {
303
269
  appendOnly: installOptions.optimizeReportForNonTerminal,
304
- process: process.env.BIT_CLI_SERVER_NO_TTY ? _objectSpread(_objectSpread({}, process), {}, {
305
- stdout: new (_legacy2().ServerSendOutStream)()
306
- }) : undefined,
270
+ outputStream: process.env.BIT_CLI_SERVER_NO_TTY ? new (_legacy2().ServerSendOutStream)() : undefined,
307
271
  throttleProgress: installOptions.throttleProgress,
308
272
  hideProgressPrefix: installOptions.hideProgressPrefix,
309
273
  hideLifecycleOutput: installOptions.hideLifecycleOutput,
@@ -463,12 +427,8 @@ class PnpmPackageManager {
463
427
  if (this.modulesManifestCache.has(lockfileDir)) {
464
428
  return this.modulesManifestCache.get(lockfileDir);
465
429
  }
466
- const {
467
- modulesYaml: {
468
- readModulesManifest
469
- }
470
- } = await loadPnpmEsm();
471
- const modulesManifest = await readModulesManifest((0, _path().join)(lockfileDir, 'node_modules'));
430
+ const nodeApi = loadNodeApi();
431
+ const modulesManifest = await nodeApi.readModulesManifest((0, _path().join)(lockfileDir, 'node_modules'));
472
432
  if (modulesManifest) {
473
433
  this.modulesManifestCache.set(lockfileDir, modulesManifest);
474
434
  }
@@ -501,52 +461,21 @@ class PnpmPackageManager {
501
461
  return (0, _pnpmPruneModules().pnpmPruneModules)(rootDir);
502
462
  }
503
463
  async findUsages(depName, opts) {
504
- const {
505
- lockfileFs: {
506
- readWantedLockfile
507
- }
508
- } = await loadPnpmEsm();
509
- const lockfile = await readWantedLockfile(opts.lockfileDir, {
510
- ignoreIncompatible: false
464
+ const nodeApi = loadNodeApi();
465
+ const trees = await nodeApi.getDependents({
466
+ dir: opts.lockfileDir,
467
+ packages: [depName],
468
+ // The generated importers under `.bit_roots` wire the workspace
469
+ // together; they are not somewhere a user's dependency comes from.
470
+ excludeProjectPatterns: [`*${_legacy().BIT_ROOTS_DIR}/*`],
471
+ // The engine walks the lockfile, which knows package names. Ask it
472
+ // for the field that carries the component id so the tree can be
473
+ // rendered in Bit's terms instead.
474
+ manifestFields: ['componentId']
511
475
  });
512
- if (!lockfile) return '';
513
- const importerIds = Object.keys(lockfile.importers ?? {}).filter(id => !id.includes(`${_legacy().BIT_ROOTS_DIR}/`));
514
- const projectPaths = importerIds.map(id => (0, _path().join)(opts.lockfileDir, id));
515
- const importerInfoMap = new Map();
516
- for (const importerId of importerIds) {
517
- const pkgJson = tryReadPackageJson((0, _path().join)(opts.lockfileDir, importerId));
518
- importerInfoMap.set(importerId, {
519
- name: pkgJson?.name ?? importerId,
520
- version: pkgJson?.version ?? ''
521
- });
522
- }
523
- const trees = await (0, _depsInspection().buildDependentsTree)([depName], projectPaths, {
524
- include: {
525
- dependencies: true,
526
- devDependencies: true,
527
- optionalDependencies: true
528
- },
529
- lockfileDir: opts.lockfileDir,
530
- registries: {
531
- default: 'https://registry.npmjs.org'
532
- },
533
- importerInfoMap,
534
- lockfile,
535
- nameFormatter({
536
- manifest
537
- }) {
538
- if ('componentId' in manifest) {
539
- const {
540
- scope,
541
- name
542
- } = manifest.componentId;
543
- return `${scope}/${name}`;
544
- }
545
- return manifest.name;
546
- }
547
- });
548
- return (0, _depsInspection2().renderDependentsTree)(trees, {
549
- depth: opts.depth ?? Infinity,
476
+ applyComponentIdNames(trees);
477
+ return nodeApi.renderDependents(trees, {
478
+ depth: opts.depth,
550
479
  long: false
551
480
  });
552
481
  }
@@ -556,18 +485,14 @@ class PnpmPackageManager {
556
485
  */
557
486
  async calcDependenciesGraph(opts) {
558
487
  await (0, _lockfileDepsGraphConverter().init)();
559
- const {
560
- lockfileFs: {
561
- readWantedLockfile,
562
- convertToLockfileFile: convertLockfileObjectToLockfileFile
563
- }
564
- } = await loadPnpmEsm();
565
- const originalLockfile = await readWantedLockfile(opts.rootDir, {
566
- ignoreIncompatible: false
488
+ const nodeApi = loadNodeApi();
489
+ const originalLockfile = await nodeApi.readLockfile({
490
+ dir: opts.rootDir
567
491
  });
568
- if (!originalLockfile) {
492
+ if (!originalLockfile?.importers) {
569
493
  return;
570
494
  }
495
+ const originalImporters = originalLockfile.importers;
571
496
  for (const {
572
497
  componentRootDir,
573
498
  componentRelativeDir,
@@ -576,15 +501,15 @@ class PnpmPackageManager {
576
501
  } of opts.components) {
577
502
  const componentImporterId = componentRelativeDir || '.';
578
503
  let compRootDir;
579
- if (componentRootDir && !originalLockfile.importers[componentRootDir] && componentRootDir.includes('@')) {
504
+ if (componentRootDir && !originalImporters[componentRootDir] && componentRootDir.includes('@')) {
580
505
  compRootDir = componentRootDir.split('@')[0];
581
506
  } else {
582
507
  compRootDir = componentRootDir;
583
508
  }
584
- if (!originalLockfile.importers[componentImporterId]) {
509
+ if (!originalImporters[componentImporterId]) {
585
510
  continue;
586
511
  }
587
- const hasComponentRootImporter = compRootDir != null && Boolean(originalLockfile.importers[compRootDir]);
512
+ const hasComponentRootImporter = compRootDir != null && Boolean(originalImporters[compRootDir]);
588
513
  const filterByImporterIds = [componentImporterId];
589
514
  if (hasComponentRootImporter && compRootDir !== componentImporterId) {
590
515
  filterByImporterIds.push(compRootDir);
@@ -592,12 +517,12 @@ class PnpmPackageManager {
592
517
  // Only clone the importers that will be mutated, reuse the rest of the lockfile as-is
593
518
  const clonedImporters = {};
594
519
  for (const importerId of filterByImporterIds) {
595
- if (originalLockfile.importers[importerId]) {
596
- clonedImporters[importerId] = structuredClone(originalLockfile.importers[importerId]);
520
+ if (originalImporters[importerId]) {
521
+ clonedImporters[importerId] = structuredClone(originalImporters[importerId]);
597
522
  }
598
523
  }
599
524
  const lockfile = _objectSpread(_objectSpread({}, originalLockfile), {}, {
600
- importers: _objectSpread(_objectSpread({}, originalLockfile.importers), clonedImporters)
525
+ importers: _objectSpread(_objectSpread({}, originalImporters), clonedImporters)
601
526
  });
602
527
  for (const importerId of filterByImporterIds) {
603
528
  const importer = lockfile.importers[importerId];
@@ -612,23 +537,15 @@ class PnpmPackageManager {
612
537
  // component's graph.
613
538
  if (importerId === componentImporterId) {
614
539
  const ref = importer.dependencies?.[workspacePkgName] ?? importer.devDependencies?.[workspacePkgName] ?? importer.optionalDependencies?.[workspacePkgName];
615
- if (typeof ref === 'string' && ref.startsWith('file:')) continue;
540
+ if (ref?.version?.startsWith('file:')) continue;
616
541
  }
617
- for (const depType of ['dependencies', 'devDependencies', 'optionalDependencies', 'specifiers', 'dependenciesMeta']) {
542
+ for (const depType of ['dependencies', 'devDependencies', 'optionalDependencies', 'dependenciesMeta']) {
618
543
  delete importer[depType]?.[workspacePkgName];
619
544
  }
620
545
  }
621
546
  }
622
547
  // Filters the lockfile so that it only includes packages related to the given component.
623
- const partialLockfile = convertLockfileObjectToLockfileFile((0, _lockfile().filterLockfileByImporters)(lockfile, filterByImporterIds, {
624
- include: {
625
- dependencies: true,
626
- devDependencies: true,
627
- optionalDependencies: true
628
- },
629
- failOnMissingDependencies: false,
630
- skipped: new Set()
631
- }));
548
+ const partialLockfile = nodeApi.filterLockfileByImporters(lockfile, filterByImporterIds);
632
549
  const graph = (0, _lockfileDepsGraphConverter().convertLockfileToGraph)(partialLockfile, _objectSpread(_objectSpread({}, opts), {}, {
633
550
  componentRootDir: hasComponentRootImporter ? compRootDir : undefined,
634
551
  componentRelativeDir: componentImporterId,
@@ -649,12 +566,23 @@ function resolveHoistPattern(hoistPatternsFromBitConfig, hoistPatternFromPnpmCon
649
566
  function isDefaultHoistPattern(hoistPattern) {
650
567
  return hoistPattern.length === 1 && hoistPattern[0] === '*';
651
568
  }
652
- function tryReadPackageJson(pkgDir) {
653
- try {
654
- return JSON.parse(_fs().default.readFileSync((0, _path().join)(pkgDir, 'package.json'), 'utf8'));
655
- } catch {
656
- return undefined;
657
- }
569
+
570
+ /**
571
+ * Rename every node the engine resolved to a Bit component after its
572
+ * component id, in place. The engine has no notion of one — it reports the
573
+ * package name from the lockfile — so it is asked for the `componentId`
574
+ * field of each node's manifest and Bit turns that into the display name,
575
+ * which the renderer then prefers over the package name.
576
+ */
577
+ function applyComponentIdNames(trees) {
578
+ const rename = node => {
579
+ const componentId = node.manifest?.componentId;
580
+ if (componentId?.scope && componentId.name) {
581
+ node.displayName = `${componentId.scope}/${componentId.name}`;
582
+ }
583
+ node.dependents?.forEach(rename);
584
+ };
585
+ trees.forEach(rename);
658
586
  }
659
587
 
660
588
  // Merge a graph-derived lockfile into an existing wanted lockfile. The graph lockfile is