nx 24.0.4 → 24.0.6

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 (78) hide show
  1. package/dist/bin/nx.js +2 -8
  2. package/dist/bin/workspace-env.d.ts +7 -0
  3. package/dist/bin/workspace-env.js +20 -0
  4. package/dist/src/command-line/affected/affected.js +1 -0
  5. package/dist/src/command-line/migrate/migrate.js +23 -7
  6. package/dist/src/command-line/migrate/prompt-files.d.ts +4 -2
  7. package/dist/src/command-line/migrate/prompt-files.js +26 -5
  8. package/dist/src/command-line/nx-cloud/start-nx-agents/command-object.js +1 -1
  9. package/dist/src/command-line/release/changelog.js +15 -12
  10. package/dist/src/command-line/reset/reset.js +13 -1
  11. package/dist/src/daemon/client/client.js +8 -7
  12. package/dist/src/daemon/client/daemon-environment.d.ts +43 -11
  13. package/dist/src/daemon/client/daemon-environment.js +139 -8
  14. package/dist/src/daemon/server/handle-client-env.d.ts +11 -1
  15. package/dist/src/daemon/server/handle-client-env.js +96 -5
  16. package/dist/src/daemon/server/handle-configure-ai-agents.js +2 -1
  17. package/dist/src/daemon/server/latest-nx.js +2 -1
  18. package/dist/src/daemon/server/server.js +1 -1
  19. package/dist/src/daemon/socket-utils.d.ts +9 -1
  20. package/dist/src/daemon/socket-utils.js +25 -0
  21. package/dist/src/executors/run-commands/running-tasks.d.ts +1 -0
  22. package/dist/src/executors/run-commands/running-tasks.js +69 -17
  23. package/dist/src/executors/run-script/run-script.impl.js +11 -3
  24. package/dist/src/native/index.d.ts +1 -1
  25. package/dist/src/native/index.js +31 -3
  26. package/dist/src/native/native-file-cache-location.js +10 -4
  27. package/dist/src/native/nx.wasm32-wasi.debug.wasm +0 -0
  28. package/dist/src/native/nx.wasm32-wasi.wasm +0 -0
  29. package/dist/src/native/transform-objects.js +5 -1
  30. package/dist/src/nx-cloud/update-manager.d.ts +6 -1
  31. package/dist/src/nx-cloud/update-manager.js +39 -12
  32. package/dist/src/plugins/js/lock-file/pnpm-parser.js +22 -34
  33. package/dist/src/plugins/js/lock-file/project-graph-pruning.d.ts +7 -0
  34. package/dist/src/plugins/js/lock-file/project-graph-pruning.js +31 -5
  35. package/dist/src/plugins/js/lock-file/utils/pnpm-normalizer.d.ts +1 -1
  36. package/dist/src/plugins/js/lock-file/utils/pnpm-normalizer.js +6 -5
  37. package/dist/src/plugins/js/package-json/create-package-json.d.ts +1 -1
  38. package/dist/src/plugins/js/package-json/create-package-json.js +53 -16
  39. package/dist/src/plugins/js/project-graph/build-dependencies/target-project-locator.js +7 -1
  40. package/dist/src/project-graph/affected/affected-tasks.js +29 -1
  41. package/dist/src/project-graph/plugins/get-plugins.d.ts +2 -0
  42. package/dist/src/project-graph/plugins/get-plugins.js +17 -2
  43. package/dist/src/project-graph/plugins/isolation/isolated-plugin.js +4 -2
  44. package/dist/src/tasks-runner/fork.js +4 -2
  45. package/dist/src/tasks-runner/run-command.d.ts +4 -1
  46. package/dist/src/tasks-runner/run-command.js +6 -4
  47. package/dist/src/tasks-runner/running-tasks/batch-process.d.ts +3 -2
  48. package/dist/src/tasks-runner/running-tasks/batch-process.js +7 -3
  49. package/dist/src/tasks-runner/task-orchestrator.d.ts +1 -0
  50. package/dist/src/tasks-runner/task-orchestrator.js +12 -3
  51. package/dist/src/tasks-runner/tasks-runner.d.ts +5 -0
  52. package/dist/src/ultracache/overrides.d.ts +1 -1
  53. package/dist/src/ultracache/overrides.js +1 -1
  54. package/dist/src/ultracache/report.d.ts +1 -1
  55. package/dist/src/ultracache/report.js +4 -1
  56. package/dist/src/utils/cache-directory.d.ts +3 -0
  57. package/dist/src/utils/cache-directory.js +105 -25
  58. package/dist/src/utils/child-process.d.ts +8 -1
  59. package/dist/src/utils/child-process.js +24 -0
  60. package/dist/src/utils/compile-cache.d.ts +6 -8
  61. package/dist/src/utils/compile-cache.js +23 -16
  62. package/dist/src/utils/min-release-age/packument.d.ts +2 -1
  63. package/dist/src/utils/min-release-age/packument.js +5 -3
  64. package/dist/src/utils/nx-tmp-dir.d.ts +14 -2
  65. package/dist/src/utils/nx-tmp-dir.js +26 -2
  66. package/dist/src/utils/owned-private-dir.d.ts +22 -0
  67. package/dist/src/utils/owned-private-dir.js +148 -0
  68. package/dist/src/utils/package-json.d.ts +8 -1
  69. package/dist/src/utils/package-json.js +77 -34
  70. package/dist/src/utils/package-manager.d.ts +25 -0
  71. package/dist/src/utils/package-manager.js +244 -9
  72. package/dist/src/utils/path.d.ts +4 -0
  73. package/dist/src/utils/path.js +8 -0
  74. package/dist/src/utils/redact-url-credentials.js +3 -2
  75. package/dist/src/utils/wait-for-socket-connection.d.ts +2 -0
  76. package/dist/src/utils/wait-for-socket-connection.js +3 -3
  77. package/package.json +11 -11
  78. package/schemas/migrations-schema.json +1 -1
package/dist/bin/nx.js CHANGED
@@ -17,6 +17,7 @@ const output_1 = require("../src/utils/output");
17
17
  const installation_directory_1 = require("../src/utils/installation-directory");
18
18
  const semver_1 = require("semver");
19
19
  const strip_indents_1 = require("../src/utils/strip-indents");
20
+ const workspace_env_1 = require("./workspace-env");
20
21
  const child_process_1 = require("child_process");
21
22
  const module_1 = require("module");
22
23
  const path_1 = require("path");
@@ -63,14 +64,7 @@ async function main() {
63
64
  // --version doesn't need any env / daemon / analytics state — skip dotenv
64
65
  // loading (and the heavy modules it would pull in).
65
66
  if (workspace && process.argv[2] !== '--version') {
66
- const { workspaceDataDirectoryForWorkspace } = await import('../src/utils/cache-directory.js');
67
- process.report.reportOnFatalError = true;
68
- process.report.directory = workspaceDataDirectoryForWorkspace(workspace.dir);
69
- const { loadRootEnvFiles } = await import('../src/utils/dotenv.js');
70
- perf_hooks_1.performance.mark('loading dotenv files:start');
71
- loadRootEnvFiles(workspace.dir);
72
- perf_hooks_1.performance.mark('loading dotenv files:end');
73
- perf_hooks_1.performance.measure('loading dotenv files', 'loading dotenv files:start', 'loading dotenv files:end');
67
+ await (0, workspace_env_1.loadWorkspaceEnv)(workspace.dir);
74
68
  }
75
69
  // new is a special case because there is no local workspace to load
76
70
  if (process.argv[2] === 'new' ||
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Loads the workspace's root `.env` files, then sends Node's fatal error
3
+ * reports to its workspace data directory. The `.env` files load first because
4
+ * importing `cache-directory` resolves and checks the configured directories,
5
+ * which read `NX_*` variables those files can set.
6
+ */
7
+ export declare function loadWorkspaceEnv(workspaceDir: string): Promise<void>;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.loadWorkspaceEnv = loadWorkspaceEnv;
4
+ const perf_hooks_1 = require("perf_hooks");
5
+ /**
6
+ * Loads the workspace's root `.env` files, then sends Node's fatal error
7
+ * reports to its workspace data directory. The `.env` files load first because
8
+ * importing `cache-directory` resolves and checks the configured directories,
9
+ * which read `NX_*` variables those files can set.
10
+ */
11
+ async function loadWorkspaceEnv(workspaceDir) {
12
+ const { loadRootEnvFiles } = await import('../src/utils/dotenv.js');
13
+ perf_hooks_1.performance.mark('loading dotenv files:start');
14
+ loadRootEnvFiles(workspaceDir);
15
+ perf_hooks_1.performance.mark('loading dotenv files:end');
16
+ perf_hooks_1.performance.measure('loading dotenv files', 'loading dotenv files:start', 'loading dotenv files:end');
17
+ const { workspaceDataDirectoryForWorkspace } = await import('../src/utils/cache-directory.js');
18
+ process.report.reportOnFatalError = true;
19
+ process.report.directory = workspaceDataDirectoryForWorkspace(workspaceDir);
20
+ }
@@ -77,6 +77,7 @@ async function affected(command, args, extraTargetDependencies = {}, extraOption
77
77
  projects = await getAffectedGraphNodes(nxArgs, projectGraph);
78
78
  if (command === 'affected' && !nxArgs.graph) {
79
79
  taskSelection = (0, run_command_1.selectTasksForProjects)(projectGraph, projectsWithTarget(projects, nxArgs), nxArgs, overrides, extraTargetDependencies, extraOptions.excludeTaskDependencies);
80
+ taskSelection.ultracacheSkippedTaskIds = [];
80
81
  }
81
82
  }
82
83
  try {
@@ -147,6 +147,9 @@ class Migrator {
147
147
  if (!migrationConfig.version) {
148
148
  throw new Error(`Fetched migration metadata for ${packageName} is invalid: the target version is missing.`);
149
149
  }
150
+ if (!(0, semver_1.valid)(migrationConfig.version)) {
151
+ throw new Error(`Fetched migration metadata for ${packageName} is invalid: the target version "${migrationConfig.version}" is not a valid version.`);
152
+ }
150
153
  return migrationConfig;
151
154
  }
152
155
  async migrate(targetPackage, targetVersion) {
@@ -1218,9 +1221,10 @@ function createFetcher(pmc) {
1218
1221
  });
1219
1222
  })
1220
1223
  .catch((e) => {
1221
- // A cooldown violation would fail an install identically (only slower),
1222
- // so surface it instead of retrying through the package manager.
1223
- if (e instanceof errors_1.MinReleaseAgeViolationError) {
1224
+ // A cooldown violation or a malformed release would reach an install
1225
+ // unchanged, so surface it instead of retrying through the package manager.
1226
+ if (e instanceof errors_1.MinReleaseAgeViolationError ||
1227
+ e instanceof package_manager_1.InvalidResolvedVersionError) {
1224
1228
  throw e;
1225
1229
  }
1226
1230
  logger_1.logger.verbose(`Failed to get migrations from registry for ${packageName}@${packageVersion}: ${e.message}. Falling back to install.`);
@@ -1392,19 +1396,28 @@ async function getPackageMigrationsUsingInstall(packageName, packageVersion, pmc
1392
1396
  return installConcurrencyLimit ? installConcurrencyLimit(run) : run();
1393
1397
  }
1394
1398
  async function getPackageMigrationsUsingInstallImpl(packageName, packageVersion, pmc) {
1399
+ (0, package_manager_1.assertValidPackageName)(packageName);
1395
1400
  const { dir, cleanup } = (0, package_manager_1.createTempNpmDirectory)();
1396
1401
  let result;
1397
1402
  const installVersion = (0, provenance_1.getNxPackageGroup)().includes(packageName)
1398
1403
  ? await (0, provenance_1.resolveVersionWithProvenance)(packageName, packageVersion)
1399
1404
  : packageVersion;
1400
1405
  try {
1401
- const addCommand = `${pmc.add} ${packageName}@${installVersion}`;
1406
+ const addCommand = [
1407
+ pmc.add,
1408
+ (0, shell_quoting_1.quoteShellArg)(`${packageName}@${installVersion}`),
1409
+ pmc.ignoreScriptsFlag,
1410
+ ]
1411
+ .filter(Boolean)
1412
+ .join(' ');
1402
1413
  try {
1403
1414
  await execAsync(addCommand, {
1404
1415
  cwd: dir,
1405
1416
  env: {
1406
1417
  ...process.env,
1407
1418
  npm_config_legacy_peer_deps: 'true',
1419
+ // Yarn Berry has no flag to skip lifecycle scripts.
1420
+ YARN_ENABLE_SCRIPTS: 'false',
1408
1421
  },
1409
1422
  });
1410
1423
  }
@@ -1483,7 +1496,8 @@ async function updatePackageJson(root, updatedPackages) {
1483
1496
  return;
1484
1497
  }
1485
1498
  const dependencyType = updatedPackages[p].addToPackageJson;
1486
- if (typeof dependencyType === 'string') {
1499
+ if (dependencyType === 'dependencies' ||
1500
+ dependencyType === 'devDependencies') {
1487
1501
  json[dependencyType] ??= {};
1488
1502
  if (json[dependencyType][p] !== updatedPackages[p].version) {
1489
1503
  json[dependencyType][p] = updatedPackages[p].version;
@@ -2898,11 +2912,12 @@ async function nxCliPath(nxWorkspaceRoot) {
2898
2912
  const isVerbose = process.env.NX_VERBOSE_LOGGING === 'true';
2899
2913
  const root = nxWorkspaceRoot ?? workspace_root_1.workspaceRoot;
2900
2914
  const version = await (0, provenance_1.resolveVersionWithProvenance)('nx', process.env.NX_MIGRATE_CLI_VERSION || 'latest', root);
2915
+ // Outside the try, so a missing private install root is reported rather than
2916
+ // hidden behind the fallback to the workspace's nx.
2917
+ const tmpDir = (0, package_manager_1.createTempInstallDirectory)();
2901
2918
  try {
2902
2919
  const packageManager = (0, package_manager_1.detectPackageManager)();
2903
2920
  const pmc = (0, package_manager_1.getPackageManagerCommand)(packageManager);
2904
- const { dirSync } = require('tmp');
2905
- const tmpDir = dirSync().name;
2906
2921
  (0, fileutils_1.writeJsonFile)((0, path_1.join)(tmpDir, 'package.json'), {
2907
2922
  dependencies: {
2908
2923
  nx: version,
@@ -2936,6 +2951,7 @@ async function nxCliPath(nxWorkspaceRoot) {
2936
2951
  cwd: tmpDir,
2937
2952
  stdio,
2938
2953
  windowsHide: true,
2954
+ env: { ...process.env, YARN_ENABLE_SCRIPTS: 'false' },
2939
2955
  });
2940
2956
  // Set NODE_PATH so that these modules can be used for module resolution
2941
2957
  addToNodePath((0, path_1.join)(tmpDir, 'node_modules'));
@@ -17,8 +17,10 @@ export declare class PromptResolutionError extends Error {
17
17
  * Resolves a migration prompt file path to an absolute path. Prompt paths are
18
18
  * plain markdown files referenced relative to the directory containing the
19
19
  * `migrations.json` - unlike schemas, they are not resolved through package
20
- * exports or `require.resolve`. The path must stay within the migrations
21
- * directory and point at an existing file.
20
+ * exports or `require.resolve`. The path must point at an existing markdown
21
+ * (`.md`) file, free of characters reserved on Windows, that stays within the
22
+ * migrations directory after resolving links, outside any nested
23
+ * `node_modules`.
22
24
  */
23
25
  export declare function resolvePrompt(promptPath: string, migrationsDir: string): string;
24
26
  export declare function extractPromptFilesFromTarball(packageName: string, packageVersion: string, migrations: MigrationsJson, migrationsFilePath: string, fullTarballPath: string, destDir: string): Promise<Record<string, string> | undefined>;
@@ -33,6 +33,9 @@ async function resolvePromptFiles(packageName, packageVersion, migrations, migra
33
33
  continue;
34
34
  }
35
35
  assertPromptPathWithinMigrationsDir(migrationsDir, entry.prompt, packageName, packageVersion);
36
+ if (!isPortableMarkdownPath(entry.prompt)) {
37
+ throw new Error(`Invalid prompt path "${entry.prompt}" in package "${packageName}@${packageVersion}": prompt files must be markdown (.md) files whose path has no characters reserved on Windows (<>:"|?*).`);
38
+ }
36
39
  try {
37
40
  resolvedPromptFiles[entry.prompt] = await resolveContent(entry.prompt);
38
41
  }
@@ -49,6 +52,14 @@ function assertPromptPathWithinMigrationsDir(migrationsDir, promptRelPath, packa
49
52
  throw new Error(`Invalid prompt path "${promptRelPath}" in package "${packageName}@${packageVersion}": prompt paths must be relative and resolve within the package's migrations directory.`);
50
53
  }
51
54
  }
55
+ // Prompt files are copied into the workspace under their own name, so any
56
+ // other extension could land as workspace configuration (e.g. project.json).
57
+ // Windows reads `:` as an NTFS stream separator, so `project.json:x.md` would
58
+ // write project.json.
59
+ function isPortableMarkdownPath(promptPath) {
60
+ return (!/[<>:"|?*\x00-\x1f]/.test(promptPath) &&
61
+ path_1.posix.extname(promptPath).toLowerCase() === '.md');
62
+ }
52
63
  /**
53
64
  * Thrown when the markdown prompt file referenced by a migration cannot be
54
65
  * resolved.
@@ -66,17 +77,27 @@ exports.PromptResolutionError = PromptResolutionError;
66
77
  * Resolves a migration prompt file path to an absolute path. Prompt paths are
67
78
  * plain markdown files referenced relative to the directory containing the
68
79
  * `migrations.json` - unlike schemas, they are not resolved through package
69
- * exports or `require.resolve`. The path must stay within the migrations
70
- * directory and point at an existing file.
80
+ * exports or `require.resolve`. The path must point at an existing markdown
81
+ * (`.md`) file, free of characters reserved on Windows, that stays within the
82
+ * migrations directory after resolving links, outside any nested
83
+ * `node_modules`.
71
84
  */
72
85
  function resolvePrompt(promptPath, migrationsDir) {
73
- if (!(0, path_2.isContainedRelativePath)(promptPath)) {
86
+ if (!(0, path_2.isContainedRelativePath)(promptPath) ||
87
+ !isPortableMarkdownPath(promptPath)) {
74
88
  throw new PromptResolutionError(promptPath, migrationsDir);
75
89
  }
76
90
  const resolvedPath = (0, path_1.join)(migrationsDir, promptPath);
77
91
  if (!(0, fs_1.existsSync)(resolvedPath)) {
78
92
  throw new PromptResolutionError(promptPath, migrationsDir);
79
93
  }
94
+ const realRelativePath = (0, path_1.relative)((0, fs_1.realpathSync)(migrationsDir), (0, fs_1.realpathSync)(resolvedPath));
95
+ if (!(0, path_2.isContainedRelativePath)(realRelativePath) ||
96
+ realRelativePath
97
+ .split(path_1.sep)
98
+ .some((segment) => segment.toLowerCase() === 'node_modules')) {
99
+ throw new PromptResolutionError(promptPath, migrationsDir);
100
+ }
80
101
  return resolvedPath;
81
102
  }
82
103
  function extractPromptFilesFromTarball(packageName, packageVersion, migrations, migrationsFilePath, fullTarballPath, destDir) {
@@ -90,7 +111,7 @@ function extractPromptFilesFromTarball(packageName, packageVersion, migrations,
90
111
  }
91
112
  function readPromptFilesFromInstall(packageName, packageVersion, migrations, migrationsFilePath) {
92
113
  const migrationsDir = (0, path_1.dirname)(migrationsFilePath);
93
- return resolvePromptFiles(packageName, packageVersion, migrations, migrationsDir, (promptRelPath) => (0, fs_1.readFileSync)((0, path_1.join)(migrationsDir, promptRelPath), 'utf-8'));
114
+ return resolvePromptFiles(packageName, packageVersion, migrations, migrationsDir, (promptRelPath) => (0, fs_1.readFileSync)(resolvePrompt(promptRelPath, migrationsDir), 'utf-8'));
94
115
  }
95
116
  function writePromptMigrationFiles(root, migrations, promptContents, targetVersion) {
96
117
  const sourceToChosen = new Map();
@@ -107,7 +128,7 @@ function writePromptMigrationFiles(root, migrations, promptContents, targetVersi
107
128
  migration.prompt = cached;
108
129
  continue;
109
130
  }
110
- const baseName = path_1.posix.basename(migration.prompt);
131
+ const baseName = path_1.posix.basename(path_1.posix.normalize((0, path_2.normalizePath)(migration.prompt)));
111
132
  const ext = path_1.posix.extname(baseName);
112
133
  const stem = ext ? baseName.slice(0, -ext.length) : baseName;
113
134
  const destDir = (0, path_2.joinPathFragments)(exports.AI_MIGRATIONS_DIR, migration.package, targetVersion);
@@ -5,7 +5,7 @@ const handle_import_1 = require("../../../utils/handle-import");
5
5
  const shared_options_1 = require("../../yargs-utils/shared-options");
6
6
  exports.yargsStartNxAgentsCommand = {
7
7
  command: 'start-nx-agents [options]',
8
- describe: 'Provisions Nx Agents for distributed task execution, reading configuration from `.nx/ci-config.yaml`. This command is an alias for [`nx-cloud start-nx-agents`](/docs/reference/nx-cloud-cli#nx-cloud-start-workers).',
8
+ describe: 'Starts workers for distributed task execution, reading configuration from `.nx/pipelines/ci.yaml`. This command is an alias for [`nx-cloud start-workers`](/docs/reference/nx-cloud-cli#nx-cloud-start-workers).',
9
9
  builder: (yargs) => (0, shared_options_1.withVerbose)(yargs)
10
10
  .help(false)
11
11
  .showHelpOnFail(false)
@@ -205,22 +205,21 @@ function createAPI(overrideReleaseConfig, ignoreNxJsonConfig) {
205
205
  : [];
206
206
  (0, shared_1.handleDuplicateGitTags)(gitTagValues);
207
207
  const postGitTasks = [];
208
- const workspaceChangelogChanges = await resolveWorkspaceChangelogChanges({
209
- releaseGraph,
210
- nxReleaseConfig,
211
- args,
212
- workspacePreid,
213
- projectsPreid,
214
- useAutomaticFromRef,
215
- toSHA,
216
- fromSHA,
217
- });
218
208
  const workspaceChangelog = await generateChangelogForWorkspace({
219
209
  tree,
220
210
  args,
221
211
  nxReleaseConfig,
222
212
  workspaceChangelogVersion,
223
- changes: workspaceChangelogChanges,
213
+ resolveChanges: () => resolveWorkspaceChangelogChanges({
214
+ releaseGraph,
215
+ nxReleaseConfig,
216
+ args,
217
+ workspacePreid,
218
+ projectsPreid,
219
+ useAutomaticFromRef,
220
+ toSHA,
221
+ fromSHA,
222
+ }),
224
223
  });
225
224
  // Add the post git task (e.g. create a remote release) for the workspace changelog, if applicable
226
225
  if (workspaceChangelog && workspaceChangelog.postGitTask) {
@@ -594,7 +593,7 @@ async function applyChangesAndExit(args, nxReleaseConfig, tree, toSHA, postGitTa
594
593
  }
595
594
  return;
596
595
  }
597
- async function generateChangelogForWorkspace({ tree, args, nxReleaseConfig, workspaceChangelogVersion, changes, }) {
596
+ async function generateChangelogForWorkspace({ tree, args, nxReleaseConfig, workspaceChangelogVersion, resolveChanges, }) {
598
597
  const config = nxReleaseConfig.changelog.workspaceChangelog;
599
598
  // The entire feature is disabled at the workspace level, exit early
600
599
  if (config === false) {
@@ -629,6 +628,10 @@ async function generateChangelogForWorkspace({ tree, args, nxReleaseConfig, work
629
628
  });
630
629
  return;
631
630
  }
631
+ // Only resolved once we know the workspace changelog will be generated: resolving changes
632
+ // from commits requires a previous workspace-level tag, which a workspace that tags per
633
+ // release group or per project does not have
634
+ const changes = await resolveChanges();
632
635
  // Only trigger interactive mode for the workspace changelog if the user explicitly requested it via "all" or "workspace"
633
636
  const interactive = args.interactive === 'all' || args.interactive === 'workspace';
634
637
  const dryRun = !!args.dryRun;
@@ -15,6 +15,7 @@ const nx_cloud_utils_1 = require("../../utils/nx-cloud-utils");
15
15
  const configuration_1 = require("../../config/configuration");
16
16
  const db_connection_1 = require("../../utils/db-connection");
17
17
  const update_manager_1 = require("../../nx-cloud/update-manager");
18
+ const package_manager_1 = require("../../utils/package-manager");
18
19
  // Wait at max 5 seconds before giving up on a failing operation.
19
20
  const INCREMENTAL_BACKOFF_MAX_DURATION = 5000;
20
21
  // If an operation fails, wait 100ms before first retry.
@@ -64,6 +65,14 @@ async function resetHandler(args) {
64
65
  },
65
66
  });
66
67
  }
68
+ if (all) {
69
+ await runResetStep(errors, {
70
+ start: 'Removing stale temporary package installs',
71
+ success: 'Removed stale temporary package installs',
72
+ failure: 'Failed to remove stale temporary package installs.',
73
+ run: async () => (0, package_manager_1.removeStaleTempInstallDirectories)(),
74
+ });
75
+ }
67
76
  if ((cloudEnabled && all) || args.onlyCloud) {
68
77
  await runResetStep(errors, {
69
78
  start: 'Cleaning up the Nx Cloud client',
@@ -124,7 +133,10 @@ async function resetCloudClient() {
124
133
  }
125
134
  function removeInstalledNxCloudClient() {
126
135
  return incrementalBackoff(INCREMENTAL_BACKOFF_FIRST_DELAY, INCREMENTAL_BACKOFF_MAX_DURATION, () => {
127
- (0, node_fs_1.rmSync)((0, update_manager_1.getBundleInstallDefaultLocation)(), { recursive: true, force: true });
136
+ const location = (0, update_manager_1.getBundleInstallDefaultLocation)();
137
+ if (location) {
138
+ (0, node_fs_1.rmSync)(location, { recursive: true, force: true });
139
+ }
128
140
  });
129
141
  }
130
142
  function cleanupCacheEntries() {
@@ -5,7 +5,6 @@ exports.isDaemonEnabled = isDaemonEnabled;
5
5
  exports.daemonPermissionException = daemonPermissionException;
6
6
  exports.daemonProcessException = daemonProcessException;
7
7
  const child_process_1 = require("child_process");
8
- const net_1 = require("net");
9
8
  const node_fs_1 = require("node:fs");
10
9
  const path_1 = require("path");
11
10
  const perf_hooks_1 = require("perf_hooks");
@@ -46,6 +45,7 @@ const streaming_messages_1 = require("../message-types/streaming-messages");
46
45
  const task_history_1 = require("../message-types/task-history");
47
46
  const update_workspace_context_1 = require("../message-types/update-workspace-context");
48
47
  const tmp_dir_1 = require("../tmp-dir");
48
+ const socket_utils_1 = require("../socket-utils");
49
49
  const sandbox_socket_hint_1 = require("../sandbox-socket-hint");
50
50
  const socket_refused_exit_code_1 = require("../../utils/socket-refused-exit-code");
51
51
  const daemon_socket_messenger_1 = require("./daemon-socket-messenger");
@@ -278,7 +278,7 @@ class DaemonClient {
278
278
  }
279
279
  await this.startDaemonIfNecessary();
280
280
  const socketPath = this.getSocketPath();
281
- this.fileWatcherMessenger = new daemon_socket_messenger_1.DaemonSocketMessenger((0, net_1.connect)(socketPath)).listen((message) => {
281
+ this.fileWatcherMessenger = new daemon_socket_messenger_1.DaemonSocketMessenger((0, socket_utils_1.connectToDaemonSocket)(socketPath)).listen((message) => {
282
282
  try {
283
283
  const parsedMessage = (0, consume_messages_from_socket_1.parseMessage)(message);
284
284
  if (this.handleFileWatcherRegistration(parsedMessage))
@@ -443,7 +443,7 @@ class DaemonClient {
443
443
  try {
444
444
  // Try to reconnect
445
445
  const socketPath = this.getSocketPath();
446
- this.fileWatcherMessenger = new daemon_socket_messenger_1.DaemonSocketMessenger((0, net_1.connect)(socketPath)).listen((message) => {
446
+ this.fileWatcherMessenger = new daemon_socket_messenger_1.DaemonSocketMessenger((0, socket_utils_1.connectToDaemonSocket)(socketPath)).listen((message) => {
447
447
  try {
448
448
  const parsedMessage = (0, consume_messages_from_socket_1.parseMessage)(message);
449
449
  if (this.handleFileWatcherRegistration(parsedMessage))
@@ -521,7 +521,7 @@ class DaemonClient {
521
521
  }
522
522
  await this.startDaemonIfNecessary();
523
523
  const socketPath = this.getSocketPath();
524
- this.projectGraphListenerMessenger = new daemon_socket_messenger_1.DaemonSocketMessenger((0, net_1.connect)(socketPath)).listen((message) => {
524
+ this.projectGraphListenerMessenger = new daemon_socket_messenger_1.DaemonSocketMessenger((0, socket_utils_1.connectToDaemonSocket)(socketPath)).listen((message) => {
525
525
  try {
526
526
  const parsedMessage = (0, consume_messages_from_socket_1.parseMessage)(message);
527
527
  // A delivered message means the stream is healthy again.
@@ -622,7 +622,7 @@ class DaemonClient {
622
622
  try {
623
623
  const socketPath = this.getSocketPath();
624
624
  // Try to reconnect
625
- this.projectGraphListenerMessenger = new daemon_socket_messenger_1.DaemonSocketMessenger((0, net_1.connect)(socketPath)).listen((message) => {
625
+ this.projectGraphListenerMessenger = new daemon_socket_messenger_1.DaemonSocketMessenger((0, socket_utils_1.connectToDaemonSocket)(socketPath)).listen((message) => {
626
626
  try {
627
627
  const parsedMessage = (0, consume_messages_from_socket_1.parseMessage)(message);
628
628
  // A delivered message means the stream is healthy again.
@@ -865,7 +865,7 @@ class DaemonClient {
865
865
  resolve({ available: false });
866
866
  return;
867
867
  }
868
- const socket = (0, net_1.connect)(socketPath, () => {
868
+ const socket = (0, socket_utils_1.connectToDaemonSocket)(socketPath, () => {
869
869
  socket.destroy();
870
870
  resolve({ available: true });
871
871
  });
@@ -967,7 +967,7 @@ class DaemonClient {
967
967
  }
968
968
  setUpConnection() {
969
969
  const socketPath = this.getSocketPath();
970
- const socket = (0, net_1.connect)(socketPath);
970
+ const socket = (0, socket_utils_1.connectToDaemonSocket)(socketPath);
971
971
  // Unref the socket so it doesn't keep the process alive. The
972
972
  // sendMessageToDaemon method uses a keep-alive setTimeout to
973
973
  // explicitly hold the event loop open while awaiting a response.
@@ -1112,6 +1112,7 @@ class DaemonClient {
1112
1112
  }, {
1113
1113
  maxAttempts: WAIT_FOR_SERVER_CONFIG.maxAttempts,
1114
1114
  delayMs: WAIT_FOR_SERVER_CONFIG.delayMs,
1115
+ connect: socket_utils_1.connectToDaemonSocket,
1115
1116
  onConnectError: (error, socketPath) => {
1116
1117
  refusal = { error, socketPath };
1117
1118
  // A refusal is not expected to become an acceptance, so polling the
@@ -29,14 +29,13 @@ export declare function getDaemonClientEnvGeneration(): number;
29
29
  * the pin, a root without markers under an ancestor that has them
30
30
  * resolves to the ancestor and the daemon publishes its socket under the
31
31
  * wrong workspace.
32
- * - NX_MAX_MESSAGE_SIZE: excluded from reflection (see above), so the value
33
- * here holds for the daemon's whole lifetime. Changing it therefore needs a
34
- * daemon restart (`nx reset`).
32
+ * - NX_MAX_MESSAGE_SIZE and NX_ALLOW_INSECURE_DIRECTORIES: excluded from
33
+ * reflection (see above), so the value here holds for the daemon's whole
34
+ * lifetime. Changing either therefore needs a daemon restart (`nx reset`).
35
+ * - TMPDIR: without it, os.tmpdir() in the daemon and every process it
36
+ * starts falls back to the shared /tmp instead of the user's own.
35
37
  */
36
- export declare function getDaemonSpawnEnv(): NodeJS.ProcessEnv & {
37
- NX_PROJECT_GLOB_CACHE: string;
38
- NX_CACHE_PROJECTS_CONFIG: string;
39
- };
38
+ export declare function getDaemonSpawnEnv(): NodeJS.ProcessEnv;
40
39
  /**
41
40
  * A copy of the env the last `applyDaemonEnvFromClient` call applied, with a
42
41
  * sequence that advances on every call, or `undefined` before the first. For a
@@ -64,11 +63,44 @@ export declare function getAppliedDaemonClientEnv(): {
64
63
  export declare function applyDaemonEnvFromClient(newEnv: NodeJS.ProcessEnv): string[];
65
64
  /**
66
65
  * Yarn Berry creates a fresh BERRY_BIN_FOLDER for every invocation and puts it
67
- * first on PATH. The wrappers inside are runtime state the daemon and workers
68
- * must receive, but the folder's random name is not project-graph identity:
69
- * two invocations whose environments differ only by it would compute the same
70
- * graph. Strips the folder from PATH and pins the var to a sentinel so such
66
+ * first on PATH. Plugin workers, and the daemon's own PATH when it runs plugins
67
+ * itself, get its wrappers only while a connected client carries it. Its random name is not
68
+ * project-graph identity: two invocations whose environments differ only by it
69
+ * would compute the same graph. Strips the folder from PATH and pins the var to a sentinel so such
71
70
  * environments compare equal. Returns a copy; never mutates runtime env.
72
71
  */
73
72
  export declare function normalizeDaemonEnvironmentForGraph(env: NodeJS.ProcessEnv, platform?: NodeJS.Platform): NodeJS.ProcessEnv;
74
73
  export declare function getChangedEnvKeys(before: NodeJS.ProcessEnv, after: NodeJS.ProcessEnv): string[];
74
+ export declare function hasBerryBinFolders(env: NodeJS.ProcessEnv): boolean;
75
+ /**
76
+ * Yarn Berry deletes its per-invocation bin folders when the command exits, so
77
+ * a process that can outlive the command must not resolve binaries through
78
+ * them. BERRY_BIN_FOLDER is kept: Yarn only ever writes it, and graph identity
79
+ * is computed from it.
80
+ */
81
+ export declare function withoutBerryBinFoldersOnPath(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
82
+ export declare function withoutBerryBinFolders(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
83
+ /**
84
+ * For work a live client is waiting on: its Yarn command, and so its bin
85
+ * folders, are still alive, but only folders that are ours and closed to other
86
+ * users are kept.
87
+ */
88
+ export declare function withTrustedBerryBinFolders(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
89
+ /**
90
+ * Like withTrustedBerryBinFolders, but also drops every bin folder outside
91
+ * `liveFolders`.
92
+ */
93
+ export declare function withLiveBerryBinFolders(env: NodeJS.ProcessEnv, liveFolders: ReadonlySet<string>): NodeJS.ProcessEnv;
94
+ /**
95
+ * The PATH and BERRY_BIN_FOLDER of the env the daemon applied last, keeping
96
+ * only the bin folders a connected client still carries. The daemon's own PATH
97
+ * lacks the client's bin folders, so workers spawned for that client's request,
98
+ * and a daemon that starts running plugins itself, take them here.
99
+ */
100
+ export declare function setLiveClientBerryEnv(env: NodeJS.ProcessEnv | undefined): void;
101
+ export declare function getLiveClientBerryEnv(): NodeJS.ProcessEnv;
102
+ /**
103
+ * Replaces the bin folders on this process's PATH with those on `env`'s PATH,
104
+ * for a daemon that runs plugins itself rather than in workers.
105
+ */
106
+ export declare function adoptBerryBinFoldersOnPath(env: NodeJS.ProcessEnv): void;