nx 24.1.0-beta.0 → 24.1.0-beta.1

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 (84) hide show
  1. package/dist/bin/init-local.js +2 -4
  2. package/dist/bin/nx-cloud.js +2 -1
  3. package/dist/bin/nx.js +12 -14
  4. package/dist/bin/run-executor.js +5 -0
  5. package/dist/src/adapter/compat.d.ts +1 -1
  6. package/dist/src/adapter/compat.js +1 -0
  7. package/dist/src/command-line/completion/scripts/bash.sh +9 -2
  8. package/dist/src/command-line/completion/scripts/fish.fish +10 -2
  9. package/dist/src/command-line/completion/scripts/zsh.zsh +8 -2
  10. package/dist/src/command-line/completion/scripts.js +18 -8
  11. package/dist/src/command-line/conformance/command-object.d.ts +3 -0
  12. package/dist/src/command-line/conformance/command-object.js +66 -0
  13. package/dist/src/command-line/generate/generate.js +2 -4
  14. package/dist/src/command-line/generate/generator-utils.d.ts +1 -0
  15. package/dist/src/command-line/generate/generator-utils.js +9 -0
  16. package/dist/src/command-line/import/import.js +26 -2
  17. package/dist/src/command-line/import/utils/ai-output.d.ts +9 -1
  18. package/dist/src/command-line/import/utils/ai-output.js +20 -1
  19. package/dist/src/command-line/nx-commands.d.ts +1 -1
  20. package/dist/src/command-line/nx-commands.js +82 -132
  21. package/dist/src/command-line/release/command-object.d.ts +1 -0
  22. package/dist/src/command-line/release/command-object.js +4 -0
  23. package/dist/src/command-line/release/release.js +6 -4
  24. package/dist/src/command-line/release/utils/resolve-nx-json-error-message.js +2 -24
  25. package/dist/src/command-line/report/report.js +1 -1
  26. package/dist/src/config/nx-json.d.ts +117 -0
  27. package/dist/src/config/workspace-json-project-json.d.ts +6 -7
  28. package/dist/src/daemon/server/project-graph-incremental-recomputation.js +13 -20
  29. package/dist/src/devkit-exports.d.ts +1 -1
  30. package/dist/src/devkit-internals.d.ts +11 -4
  31. package/dist/src/devkit-internals.js +26 -4
  32. package/dist/src/executors/run-commands/run-commands.impl.d.ts +1 -1
  33. package/dist/src/executors/run-commands/run-commands.impl.js +35 -13
  34. package/dist/src/migrations/update-24-1-0/replace-powerpack-conformance.d.ts +4 -0
  35. package/dist/src/migrations/update-24-1-0/replace-powerpack-conformance.js +117 -0
  36. package/dist/src/migrations/update-24-1-0/replace-powerpack-conformance.md +38 -0
  37. package/dist/src/native/index.d.ts +6 -4
  38. package/dist/src/native/index.js +5 -0
  39. package/dist/src/native/native-bindings.js +1 -0
  40. package/dist/src/native/nx.wasm32-wasi.debug.wasm +0 -0
  41. package/dist/src/native/nx.wasm32-wasi.wasm +0 -0
  42. package/dist/src/native/transform-objects.d.ts +2 -0
  43. package/dist/src/native/transform-objects.js +15 -0
  44. package/dist/src/plugins/js/lock-file/bun-parser.d.ts +1 -2
  45. package/dist/src/plugins/js/lock-file/bun-parser.js +5 -3
  46. package/dist/src/plugins/js/lock-file/lock-file-names.d.ts +6 -0
  47. package/dist/src/plugins/js/lock-file/lock-file-names.js +16 -0
  48. package/dist/src/plugins/js/lock-file/lock-file.d.ts +1 -2
  49. package/dist/src/plugins/js/lock-file/lock-file.js +24 -31
  50. package/dist/src/plugins/js/project-graph/affected/npm-packages.js +50 -2
  51. package/dist/src/plugins/js/project-graph/build-dependencies/target-project-locator.d.ts +5 -0
  52. package/dist/src/plugins/js/project-graph/build-dependencies/target-project-locator.js +75 -13
  53. package/dist/src/plugins/js/utils/register.js +13 -6
  54. package/dist/src/project-graph/build-project-graph.js +5 -2
  55. package/dist/src/project-graph/nx-deps-cache.d.ts +3 -2
  56. package/dist/src/project-graph/nx-deps-cache.js +8 -2
  57. package/dist/src/project-graph/utils/project-graph-paths.d.ts +8 -0
  58. package/dist/src/project-graph/utils/project-graph-paths.js +170 -0
  59. package/dist/src/tasks-runner/batch/run-batch.js +3 -13
  60. package/dist/src/tasks-runner/cache.js +19 -18
  61. package/dist/src/tasks-runner/run-command.js +6 -3
  62. package/dist/src/tasks-runner/task-orchestrator.d.ts +1 -0
  63. package/dist/src/tasks-runner/task-orchestrator.js +13 -2
  64. package/dist/src/utils/child-process.js +2 -1
  65. package/dist/src/utils/find-workspace-root.js +2 -4
  66. package/dist/src/utils/git-utils.d.ts +5 -0
  67. package/dist/src/utils/git-utils.js +23 -1
  68. package/dist/src/utils/handle-import.js +6 -0
  69. package/dist/src/utils/installation-directory.d.ts +16 -0
  70. package/dist/src/utils/installation-directory.js +96 -2
  71. package/dist/src/utils/json.d.ts +7 -0
  72. package/dist/src/utils/json.js +27 -0
  73. package/dist/src/utils/nx-key.js +11 -8
  74. package/dist/src/utils/output.d.ts +5 -0
  75. package/dist/src/utils/output.js +11 -4
  76. package/dist/src/utils/owned-private-dir.d.ts +10 -0
  77. package/dist/src/utils/owned-private-dir.js +28 -0
  78. package/dist/src/utils/require-nx-key.js +6 -4
  79. package/dist/src/utils/workspace-root.d.ts +12 -0
  80. package/dist/src/utils/workspace-root.js +56 -7
  81. package/migrations.json +6 -0
  82. package/package.json +13 -11
  83. package/schemas/nx-schema.json +75 -9
  84. package/schemas/project-schema.json +5 -0
@@ -4,6 +4,7 @@ exports.initLocal = initLocal;
4
4
  exports.rewriteTargetsAndProjects = rewriteTargetsAndProjects;
5
5
  const perf_hooks_1 = require("perf_hooks");
6
6
  const nx_commands_1 = require("../src/command-line/nx-commands");
7
+ const installation_directory_1 = require("../src/utils/installation-directory");
7
8
  const strip_indents_1 = require("../src/utils/strip-indents");
8
9
  const client_1 = require("../src/daemon/client/client");
9
10
  const prompt_helpers_1 = require("../src/utils/prompt-helpers");
@@ -178,10 +179,7 @@ To update the cache configuration, you can directly update the relevant options
178
179
  }
179
180
  else {
180
181
  try {
181
- // nx-ignore-next-line
182
- const cli = require.resolve('@angular/cli/lib/init.js', {
183
- paths: [workspace.dir],
184
- });
182
+ const cli = (0, installation_directory_1.resolveInstalledPackage)('@angular/cli/lib/init.js', [workspace.dir], workspace.dir);
185
183
  require(cli);
186
184
  }
187
185
  catch (e) {
@@ -5,6 +5,7 @@ exports.invokeCommandWithNxCloudClient = invokeCommandWithNxCloudClient;
5
5
  const get_cloud_options_1 = require("../src/nx-cloud/utilities/get-cloud-options");
6
6
  const update_manager_1 = require("../src/nx-cloud/update-manager");
7
7
  const output_1 = require("../src/utils/output");
8
+ const installation_directory_1 = require("../src/utils/installation-directory");
8
9
  const client_1 = require("../src/nx-cloud/utilities/client");
9
10
  const command = process.argv[2];
10
11
  const options = (0, get_cloud_options_1.getCloudOptions)();
@@ -39,7 +40,7 @@ async function invokeCommandWithNxCloudClient(options) {
39
40
  try {
40
41
  // TODO: Remove this when all enterprise customers have updated.
41
42
  // Try requiring the bin from the `nx-cloud` package.
42
- return require('nx-cloud/bin/nx-cloud');
43
+ return require((0, installation_directory_1.resolveInstalledPackage)('nx-cloud/bin/nx-cloud', [__dirname]));
43
44
  }
44
45
  catch { }
45
46
  body.push('If you are an Nx Enterprise customer, please reach out to your assigned Developer Productivity Engineer.', 'If you are NOT an Nx Enterprise customer but are seeing this message, please reach out to cloud-support@nrwl.io.');
package/dist/bin/nx.js CHANGED
@@ -93,14 +93,8 @@ async function main() {
93
93
  if (!Symbol.observable)
94
94
  Symbol.observable = Symbol('observable polyfill');
95
95
  // Make sure that a local copy of Nx exists in workspace
96
- let localNx;
97
- try {
98
- localNx = workspace && resolveNx(workspace);
99
- }
100
- catch {
101
- localNx = null;
102
- }
103
- const isLocalInstall = localNx === resolveNx(null) || localNx === __filename;
96
+ const localNx = workspace && tryResolveNx(workspace);
97
+ const isLocalInstall = !!localNx && (localNx === tryResolveNx(null) || localNx === __filename);
104
98
  const { LOCAL_NX_VERSION, GLOBAL_NX_VERSION } = determineNxVersions(localNx, workspace, isLocalInstall);
105
99
  if (process.argv[2] === '--version') {
106
100
  handleNxVersionCommand(LOCAL_NX_VERSION, GLOBAL_NX_VERSION);
@@ -185,20 +179,24 @@ function resolveNx(workspace) {
185
179
  // root relative to location of the nx bin
186
180
  const globalsRoot = (0, path_1.join)(__dirname, '../../../../');
187
181
  const root = workspace ? workspace.dir : globalsRoot;
188
- // Use createRequire to resolve from outside the nx package,
189
- // avoiding self-referencing caused by the exports field
190
182
  // prefer Nx installed in .nx/installation
191
183
  try {
192
184
  const installPath = (0, installation_directory_1.getNxInstallationPath)(root);
193
185
  if ((0, fs_1.existsSync)(installPath)) {
194
- const installRequire = (0, module_1.createRequire)((0, path_1.join)(installPath, 'package.json'));
195
- return installRequire.resolve('nx/bin/nx.js');
186
+ return (0, installation_directory_1.resolveNxBinFrom)(installPath, root);
196
187
  }
197
188
  }
198
189
  catch { }
199
190
  // check for root install
200
- const rootRequire = (0, module_1.createRequire)((0, path_1.join)(root, 'package.json'));
201
- return rootRequire.resolve('nx/bin/nx.js');
191
+ return (0, installation_directory_1.resolveNxBinFrom)(root);
192
+ }
193
+ function tryResolveNx(workspace) {
194
+ try {
195
+ return resolveNx(workspace);
196
+ }
197
+ catch {
198
+ return null;
199
+ }
202
200
  }
203
201
  function isNxCloudCommand(command) {
204
202
  const nxCloudCommands = [
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const fs_1 = require("fs");
4
4
  const run_1 = require("../src/command-line/run/run");
5
+ const output_1 = require("../src/utils/output");
5
6
  if (process.env.NX_TERMINAL_OUTPUT_PATH) {
6
7
  setUpOutputWatching(process.env.NX_TERMINAL_CAPTURE_STDERR === 'true', process.env.NX_STREAM_OUTPUT === 'true');
7
8
  }
@@ -57,10 +58,14 @@ function setUpOutputWatching(captureStderr, streamOutput) {
57
58
  process.on('message', async (message) => {
58
59
  try {
59
60
  const statusCode = await (0, run_1.run)(process.cwd(), process.env.NX_WORKSPACE_ROOT, message.targetDescription, message.overrides, message.isVerbose, message.taskGraph);
61
+ // `process.exit` does not wait for pipe writes, so a task that ends with
62
+ // a large write would otherwise lose the end of its output.
63
+ await output_1.output.drain();
60
64
  process.exit(statusCode);
61
65
  }
62
66
  catch (e) {
63
67
  console.error(e);
68
+ await output_1.output.drain();
64
69
  process.exit(1);
65
70
  }
66
71
  });
@@ -1,2 +1,2 @@
1
1
  export declare const allowedProjectExtensions: readonly ['tags', 'implicitDependencies', 'configFilePath', '$schema', 'generators', 'namedInputs', 'name', 'files', 'root', 'sourceRoot', 'projectType', 'release', 'includedScripts', 'metadata', 'owners', 'nxCloudImplicitDependencies'];
2
- export declare const allowedWorkspaceExtensions: readonly ['$schema', 'implicitDependencies', 'affected', 'defaultBase', 'tasksRunnerOptions', 'workspaceLayout', 'plugins', 'targetDefaults', 'files', 'generators', 'namedInputs', 'extends', 'cli', 'pluginsConfig', 'defaultProject', 'installation', 'release', 'nxCloudAccessToken', 'nxCloudId', 'nxCloudUrl', 'nxCloudEncryptionKey', 'parallel', 'cacheDirectory', 'useDaemonProcess', 'useInferencePlugins', 'neverConnectToCloud', 'analytics', 'sync', 'migrate', 'useLegacyCache', 'maxCacheSize', 'tui', 'owners'];
2
+ export declare const allowedWorkspaceExtensions: readonly ['$schema', 'implicitDependencies', 'affected', 'defaultBase', 'tasksRunnerOptions', 'workspaceLayout', 'plugins', 'targetDefaults', 'files', 'generators', 'namedInputs', 'extends', 'cli', 'pluginsConfig', 'defaultProject', 'installation', 'release', 'nxCloudAccessToken', 'nxCloudId', 'nxCloudUrl', 'nxCloudEncryptionKey', 'parallel', 'cacheDirectory', 'useDaemonProcess', 'useInferencePlugins', 'neverConnectToCloud', 'analytics', 'sync', 'migrate', 'conformance', 'useLegacyCache', 'maxCacheSize', 'tui', 'owners'];
@@ -67,6 +67,7 @@ exports.allowedWorkspaceExtensions = [
67
67
  'analytics',
68
68
  'sync',
69
69
  'migrate',
70
+ 'conformance',
70
71
  'useLegacyCache',
71
72
  'maxCacheSize',
72
73
  'tui',
@@ -5,6 +5,13 @@
5
5
  # Installation: nx completion bash >> ~/.bashrc
6
6
  # or: nx completion bash >> ~/.bash_profile
7
7
  #
8
+ # In a world-writable directory (/tmp) only trust entries owned by you or root.
9
+ _nx_trusted_entry()
10
+ {
11
+ [ -z "$(find -H "$1" -prune -perm -0002 2>/dev/null)" ] ||
12
+ [ -n "$(find "$1/$2" -prune \( -user "$EUID" -o -user 0 \) 2>/dev/null)" ]
13
+ }
14
+
8
15
  _nx_completions()
9
16
  {
10
17
  local cur_word args type_list nx_cmd dir
@@ -16,11 +23,11 @@ _nx_completions()
16
23
  nx_cmd="nx"
17
24
  dir="$PWD"
18
25
  while [ "$dir" != "/" ]; do
19
- if [ -x "$dir/node_modules/.bin/nx" ]; then
26
+ if [ -x "$dir/node_modules/.bin/nx" ] && _nx_trusted_entry "$dir" node_modules; then
20
27
  nx_cmd="$dir/node_modules/.bin/nx"
21
28
  break
22
29
  fi
23
- if [ -x "$dir/.nx/installation/node_modules/.bin/nx" ]; then
30
+ if [ -x "$dir/.nx/installation/node_modules/.bin/nx" ] && _nx_trusted_entry "$dir" .nx; then
24
31
  nx_cmd="$dir/.nx/installation/node_modules/.bin/nx"
25
32
  break
26
33
  fi
@@ -8,6 +8,14 @@
8
8
  #
9
9
  complete -e -c nx
10
10
 
11
+ # In a world-writable directory (/tmp) only trust entries owned by you or root.
12
+ function __nx_trusted_entry
13
+ set -l shared (find -H $argv[1] -prune -perm -0002 2>/dev/null)
14
+ test -z "$shared"; and return 0
15
+ set -l owned (find $argv[1]/$argv[2] -prune \( -user (id -u) -o -user 0 \) 2>/dev/null)
16
+ test -n "$owned"
17
+ end
18
+
11
19
  function __nx_completions
12
20
  set -l tokens (commandline -cop)
13
21
  set -l current (commandline -ct)
@@ -15,11 +23,11 @@ function __nx_completions
15
23
  set -l nx_cmd nx
16
24
  set -l dir $PWD
17
25
  while test "$dir" != "/"
18
- if test -x "$dir/node_modules/.bin/nx"
26
+ if test -x "$dir/node_modules/.bin/nx"; and __nx_trusted_entry "$dir" node_modules
19
27
  set nx_cmd "$dir/node_modules/.bin/nx"
20
28
  break
21
29
  end
22
- if test -x "$dir/.nx/installation/node_modules/.bin/nx"
30
+ if test -x "$dir/.nx/installation/node_modules/.bin/nx"; and __nx_trusted_entry "$dir" .nx
23
31
  set nx_cmd "$dir/.nx/installation/node_modules/.bin/nx"
24
32
  break
25
33
  end
@@ -6,6 +6,12 @@
6
6
  # or: nx completion zsh > /usr/local/share/zsh/site-functions/_nx
7
7
  #
8
8
  if type compdef &>/dev/null; then
9
+ # In a world-writable directory (/tmp) only trust entries owned by you or root.
10
+ _nx_trusted_entry () {
11
+ [[ -z "$(find -H "$1" -prune -perm -0002 2>/dev/null)" ]] ||
12
+ [[ -n "$(find "$1/$2" -prune \( -user "$EUID" -o -user 0 \) 2>/dev/null)" ]]
13
+ }
14
+
9
15
  _nx_completions () {
10
16
  local reply nx_cmd dir
11
17
  local si=$IFS
@@ -14,11 +20,11 @@ if type compdef &>/dev/null; then
14
20
  nx_cmd="nx"
15
21
  dir="$PWD"
16
22
  while [[ "$dir" != "/" ]]; do
17
- if [[ -x "$dir/node_modules/.bin/nx" ]]; then
23
+ if [[ -x "$dir/node_modules/.bin/nx" ]] && _nx_trusted_entry "$dir" node_modules; then
18
24
  nx_cmd="$dir/node_modules/.bin/nx"
19
25
  break
20
26
  fi
21
- if [[ -x "$dir/.nx/installation/node_modules/.bin/nx" ]]; then
27
+ if [[ -x "$dir/.nx/installation/node_modules/.bin/nx" ]] && _nx_trusted_entry "$dir" .nx; then
22
28
  nx_cmd="$dir/.nx/installation/node_modules/.bin/nx"
23
29
  break
24
30
  fi
@@ -9,6 +9,8 @@ const child_process_1 = require("child_process");
9
9
  const fs_1 = require("fs");
10
10
  const os_1 = require("os");
11
11
  const path_1 = require("path");
12
+ const BEGIN_MARKER = '###-begin-nx-completions-###';
13
+ const END_MARKER = '###-end-nx-completions-###';
12
14
  exports.SHELLS = ['bash', 'zsh', 'fish', 'powershell'];
13
15
  /** Print the raw wrapper script to stdout — for scripting / custom rc paths. */
14
16
  function printCompletionScript(shell) {
@@ -54,21 +56,29 @@ function writeScriptToRcFile(shell) {
54
56
  function writeOneRcFile(shell, path, script) {
55
57
  (0, fs_1.mkdirSync)((0, path_1.dirname)(path), { recursive: true });
56
58
  // Fish keeps each completion in its own file (a full overwrite is correct).
57
- // bash/zsh/powershell append to a shared rc file: skip if an nx-completion
58
- // block is already present so re-runs are no-ops, and never modify
59
- // existing content — the user may have customized around the block.
59
+ // bash/zsh/powershell share an rc file: replace only the text between the
60
+ // markers so content the user wrote around the block is kept.
60
61
  if (shell === 'fish') {
61
62
  (0, fs_1.writeFileSync)(path, script);
62
63
  }
63
64
  else {
64
65
  const existing = (0, fs_1.existsSync)(path) ? (0, fs_1.readFileSync)(path, 'utf8') : '';
65
- if (existing.includes('###-begin-nx-completions-###')) {
66
- console.warn(`nx: ${shell} completion already present in ${path} — skipping.\n` +
67
- ` Remove the existing block manually if you need to reinstall.`);
66
+ const start = existing.indexOf(BEGIN_MARKER);
67
+ const end = start === -1 ? -1 : existing.indexOf(END_MARKER, start);
68
+ if (end !== -1) {
69
+ (0, fs_1.writeFileSync)(path, existing.slice(0, start) +
70
+ script.trimEnd() +
71
+ existing.slice(end + END_MARKER.length));
72
+ }
73
+ else if (start !== -1) {
74
+ console.warn(`nx: ${shell} completion in ${path} has no end marker — skipping.\n` +
75
+ ` Remove the existing block manually to reinstall.`);
68
76
  return;
69
77
  }
70
- const sep = existing && !existing.endsWith('\n') ? '\n' : '';
71
- (0, fs_1.writeFileSync)(path, existing + sep + script);
78
+ else {
79
+ const sep = existing && !existing.endsWith('\n') ? '\n' : '';
80
+ (0, fs_1.writeFileSync)(path, existing + sep + script);
81
+ }
72
82
  }
73
83
  console.warn(`nx: ${shell} completion installed at ${path}.\n` +
74
84
  ` Open a new shell (or re-source the rc file) to activate.`);
@@ -0,0 +1,3 @@
1
+ import type { CommandModule } from 'yargs';
2
+ export type ConformanceCommand = 'conformance' | 'conformance:check';
3
+ export declare function resolveConformanceCommandObject(command: ConformanceCommand): CommandModule;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveConformanceCommandObject = resolveConformanceCommandObject;
4
+ const installation_directory_1 = require("../../utils/installation-directory");
5
+ const output_1 = require("../../utils/output");
6
+ const shared_options_1 = require("../yargs-utils/shared-options");
7
+ function resolveConformanceCommandObject(command) {
8
+ let commandObject;
9
+ try {
10
+ const conformance = require((0, installation_directory_1.resolveInstalledPackage)('@nx/conformance', [__dirname]));
11
+ commandObject =
12
+ command === 'conformance'
13
+ ? conformance.yargsConformanceCommand
14
+ : conformance.yargsConformanceCheckCommand;
15
+ }
16
+ catch (e) {
17
+ return isConformanceNotInstalled(e)
18
+ ? createMissingConformanceCommand(command)
19
+ : createUnloadableConformanceCommand(command, e);
20
+ }
21
+ return {
22
+ ...commandObject,
23
+ builder: (yargs) => commandObject.builder((0, shared_options_1.withVerbose)(yargs)),
24
+ };
25
+ }
26
+ // Only a missing @nx/conformance itself means the plugin is not installed.
27
+ // Any other load error is a broken install and is reported as such.
28
+ function isConformanceNotInstalled(e) {
29
+ return (e?.code === 'MODULE_NOT_FOUND' &&
30
+ e.message.includes(`'@nx/conformance'`));
31
+ }
32
+ function createMissingConformanceCommand(command) {
33
+ return {
34
+ command,
35
+ // Hidden from --help until the plugin is installed
36
+ describe: false,
37
+ handler: () => {
38
+ output_1.output.error({
39
+ title: `nx ${command} requires the @nx/conformance plugin`,
40
+ bodyLines: [
41
+ 'Install it by running `nx add @nx/conformance`.',
42
+ '',
43
+ 'To learn more, visit https://nx.dev/docs/reference/conformance/overview',
44
+ ],
45
+ });
46
+ process.exit(1);
47
+ },
48
+ };
49
+ }
50
+ function createUnloadableConformanceCommand(command, error) {
51
+ return {
52
+ command,
53
+ describe: false,
54
+ handler: () => {
55
+ output_1.output.error({
56
+ title: `nx ${command} could not load the @nx/conformance plugin`,
57
+ bodyLines: [
58
+ error instanceof Error ? error.message : String(error),
59
+ '',
60
+ 'Reinstall your dependencies, and make sure @nx/conformance matches your nx version.',
61
+ ],
62
+ });
63
+ process.exit(1);
64
+ },
65
+ };
66
+ }
@@ -240,7 +240,7 @@ async function generate(args) {
240
240
  if ((0, generator_utils_1.getGeneratorInformation)(opts.collectionName, normalizedGeneratorName, workspace_root_1.workspaceRoot, projectsConfigurations.projects).isNxGenerator) {
241
241
  const host = new tree_1.FsTree(workspace_root_1.workspaceRoot, args.verbose, `generating (${opts.collectionName}:${normalizedGeneratorName})`);
242
242
  const implementation = implementationFactory();
243
- const task = await implementation(host, combinedOpts);
243
+ const result = await implementation(host, combinedOpts);
244
244
  host.lock();
245
245
  const changes = host.listChanges();
246
246
  if (!opts.quiet) {
@@ -248,9 +248,7 @@ async function generate(args) {
248
248
  }
249
249
  if (!opts.dryRun) {
250
250
  (0, tree_1.flushChanges)(workspace_root_1.workspaceRoot, changes);
251
- if (task) {
252
- await task();
253
- }
251
+ await (0, generator_utils_1.runGeneratorCallback)(result);
254
252
  }
255
253
  else {
256
254
  logger_1.logger.warn(`\nNOTE: The "dryRun" flag means no changes were made.`);
@@ -16,3 +16,4 @@ export declare function readGeneratorsJson(collectionName: string, generator: st
16
16
  normalizedGeneratorName: string;
17
17
  resolvedCollectionName: string;
18
18
  };
19
+ export declare function runGeneratorCallback(result: unknown): Promise<void>;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getGeneratorInformation = getGeneratorInformation;
4
4
  exports.readGeneratorsJson = readGeneratorsJson;
5
+ exports.runGeneratorCallback = runGeneratorCallback;
5
6
  const path_1 = require("path");
6
7
  const schema_utils_1 = require("../../config/schema-utils");
7
8
  const fileutils_1 = require("../../utils/fileutils");
@@ -89,3 +90,11 @@ function findFullGeneratorName(name, generators) {
89
90
  }
90
91
  }
91
92
  }
93
+ async function runGeneratorCallback(result) {
94
+ const callback = result && typeof result === 'object'
95
+ ? result.callback
96
+ : result;
97
+ if (typeof callback === 'function') {
98
+ await callback();
99
+ }
100
+ }
@@ -29,6 +29,24 @@ const check_compatible_with_plugins_1 = require("../init/implementation/check-co
29
29
  const native_1 = require("../../native");
30
30
  const ai_output_1 = require("./utils/ai-output");
31
31
  const importRemoteName = '__tmp_nx_import__';
32
+ function createDestinationGitClient() {
33
+ const cwd = process.cwd();
34
+ if ((0, git_utils_1.getGitRepositoryStatus)(cwd) === 'not-git') {
35
+ throw new ai_output_1.NxImportError(`${cwd} is not a git repository. Nx imports code by merging its git history, so run "git init", commit your files and try again.`, 'NOT_A_GIT_REPOSITORY');
36
+ }
37
+ return new git_utils_1.GitRepository(cwd);
38
+ }
39
+ function getSourceNotAGitRepositoryMessage(sourceDirectory) {
40
+ const message = `${sourceDirectory} is not a git repository. Nx imports code along with its git history, so the source must be a git repository.`;
41
+ // git reports the repository by its real path, so the directory is resolved
42
+ // too; otherwise a symlinked source yields a path that is not inside it.
43
+ const realSourceDirectory = (0, node_fs_1.realpathSync)(sourceDirectory);
44
+ const pathInEnclosingRepo = (0, git_utils_1.getGitRootRelativePath)(realSourceDirectory);
45
+ if (pathInEnclosingRepo) {
46
+ return `${message}\nIt is a directory inside the git repository at ${(0, git_utils_1.getGitRootPath)(realSourceDirectory)}. Import that repository instead and select the directory ${pathInEnclosingRepo} with the --source option.`;
47
+ }
48
+ return `${message}\nRun "git init" in ${sourceDirectory}, commit the files and try again.`;
49
+ }
32
50
  async function importHandler(options) {
33
51
  process.env.NX_RUNNING_NX_IMPORT = 'true';
34
52
  let { sourceRepository, ref, source, destination, verbose } = options;
@@ -51,7 +69,7 @@ async function importHandler(options) {
51
69
  // Check if this is a plugin-only call (second step of two-step flow)
52
70
  if (destination && options.plugins) {
53
71
  const absDestAi = (0, path_1.join)(process.cwd(), destination);
54
- const destGitClient = new git_utils_1.GitRepository(process.cwd());
72
+ const destGitClient = createDestinationGitClient();
55
73
  const destFiles = await destGitClient.getGitFiles(absDestAi);
56
74
  if (destFiles.length > 0) {
57
75
  // Destination not empty + --plugins provided + AI mode = plugin-only mode
@@ -59,7 +77,7 @@ async function importHandler(options) {
59
77
  }
60
78
  }
61
79
  }
62
- const destinationGitClient = new git_utils_1.GitRepository(process.cwd());
80
+ const destinationGitClient = createDestinationGitClient();
63
81
  if (await destinationGitClient.hasUncommittedChanges()) {
64
82
  throw new Error(`You have uncommitted changes in the destination repository. Commit or revert the changes and try again.`);
65
83
  }
@@ -82,10 +100,12 @@ async function importHandler(options) {
82
100
  validate: (value) => (value ? undefined : 'A repository is required'),
83
101
  });
84
102
  }
103
+ let sourceIsLocalDirectory = false;
85
104
  try {
86
105
  const maybeLocalDirectory = await (0, promises_1.stat)(sourceRepository);
87
106
  if (maybeLocalDirectory.isDirectory()) {
88
107
  sourceRepository = (0, path_1.resolve)(sourceRepository);
108
+ sourceIsLocalDirectory = true;
89
109
  }
90
110
  }
91
111
  catch (e) {
@@ -112,6 +132,10 @@ async function importHandler(options) {
112
132
  if (!aiMode) {
113
133
  spinner.fail(`Failed to clone ${displayRepository} into ${sourceTempRepoPath}`);
114
134
  }
135
+ if (sourceIsLocalDirectory &&
136
+ !(await (0, git_utils_1.isCloneableGitRepository)(sourceRepository))) {
137
+ throw new ai_output_1.NxImportError(getSourceNotAGitRepositoryMessage(sourceRepository), 'NOT_A_GIT_REPOSITORY');
138
+ }
115
139
  throw new Error(`Failed to clone ${displayRepository} into ${sourceTempRepoPath}. Please double check the remote and try again.\n${(0, redact_url_credentials_1.redactUrlCredentials)(e.message)}`);
116
140
  }
117
141
  if (!aiMode) {
@@ -6,7 +6,15 @@
6
6
  import { writeAiOutput, logProgress, writeErrorLog, type DetectedPlugin, type UserNextSteps } from '../../ai/ai-output';
7
7
  export { writeAiOutput, logProgress, writeErrorLog };
8
8
  export type ImportProgressStage = 'starting' | 'cloning' | 'filtering' | 'merging' | 'detecting-plugins' | 'installing' | 'installing-plugins' | 'complete' | 'error' | 'needs_input';
9
- export type NxImportErrorCode = 'UNCOMMITTED_CHANGES' | 'CLONE_FAILED' | 'SOURCE_NOT_FOUND' | 'DESTINATION_NOT_EMPTY' | 'INVALID_DESTINATION' | 'FILTER_FAILED' | 'MERGE_FAILED' | 'PACKAGE_INSTALL_ERROR' | 'PLUGIN_INIT_ERROR' | 'UNKNOWN';
9
+ export type NxImportErrorCode = 'UNCOMMITTED_CHANGES' | 'NOT_A_GIT_REPOSITORY' | 'CLONE_FAILED' | 'SOURCE_NOT_FOUND' | 'DESTINATION_NOT_EMPTY' | 'INVALID_DESTINATION' | 'FILTER_FAILED' | 'MERGE_FAILED' | 'PACKAGE_INSTALL_ERROR' | 'PLUGIN_INIT_ERROR' | 'UNKNOWN';
10
+ /**
11
+ * An import failure that states its own error code, for messages that embed
12
+ * user paths and so cannot be classified by their text.
13
+ */
14
+ export declare class NxImportError extends Error {
15
+ readonly errorCode: NxImportErrorCode;
16
+ constructor(message: string, errorCode: NxImportErrorCode);
17
+ }
10
18
  interface ImportOptionInfo {
11
19
  description: string;
12
20
  flag: string;
@@ -5,7 +5,7 @@
5
5
  * Extends the shared base with import-specific types and builders.
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.writeErrorLog = exports.logProgress = exports.writeAiOutput = void 0;
8
+ exports.NxImportError = exports.writeErrorLog = exports.logProgress = exports.writeAiOutput = void 0;
9
9
  exports.buildImportNeedsOptionsResult = buildImportNeedsOptionsResult;
10
10
  exports.buildImportNeedsPluginSelectionResult = buildImportNeedsPluginSelectionResult;
11
11
  exports.buildImportSuccessResult = buildImportSuccessResult;
@@ -16,6 +16,18 @@ const ai_output_1 = require("../../ai/ai-output");
16
16
  Object.defineProperty(exports, "writeAiOutput", { enumerable: true, get: function () { return ai_output_1.writeAiOutput; } });
17
17
  Object.defineProperty(exports, "logProgress", { enumerable: true, get: function () { return ai_output_1.logProgress; } });
18
18
  Object.defineProperty(exports, "writeErrorLog", { enumerable: true, get: function () { return ai_output_1.writeErrorLog; } });
19
+ /**
20
+ * An import failure that states its own error code, for messages that embed
21
+ * user paths and so cannot be classified by their text.
22
+ */
23
+ class NxImportError extends Error {
24
+ constructor(message, errorCode) {
25
+ super(message);
26
+ this.errorCode = errorCode;
27
+ this.name = 'NxImportError';
28
+ }
29
+ }
30
+ exports.NxImportError = NxImportError;
19
31
  const AVAILABLE_OPTIONS = {
20
32
  sourceRepository: {
21
33
  description: 'URL or path of the repository to import.',
@@ -129,6 +141,11 @@ function getImportErrorHints(errorCode) {
129
141
  'Commit or stash your changes before running nx import',
130
142
  'Run "git status" to see uncommitted changes',
131
143
  ];
144
+ case 'NOT_A_GIT_REPOSITORY':
145
+ return [
146
+ 'nx import needs both the source and this workspace to be git repositories',
147
+ 'Run "git init" in the directory that is not a repository and commit its files',
148
+ ];
132
149
  case 'CLONE_FAILED':
133
150
  return [
134
151
  'Check the repository URL is correct and accessible',
@@ -183,6 +200,8 @@ function getImportErrorHints(errorCode) {
183
200
  }
184
201
  }
185
202
  function determineImportErrorCode(error) {
203
+ if (error instanceof NxImportError)
204
+ return error.errorCode;
186
205
  const message = error instanceof Error ? error.message : String(error);
187
206
  const lower = message.toLowerCase();
188
207
  if (lower.includes('uncommitted'))
@@ -7,4 +7,4 @@ export declare const parserConfiguration: Partial<yargs.ParserConfigurationOptio
7
7
  * from the `.argv` call, so the object and it's relative scripts can
8
8
  * be executed correctly.
9
9
  */
10
- export declare const commandsObject: yargs.Argv<unknown>;
10
+ export declare const commandsObject: yargs.Argv<{}>;