feat(devkit): bump compatibility to Nx 19 - 21.x (#28243)

BREAKING CHANGE

<!-- Please make sure you have read the submission guidelines before
posting an PR -->
<!--
https://github.com/nrwl/nx/blob/master/CONTRIBUTING.md#-submitting-a-pr
-->

<!-- Please make sure that your commit message follows our format -->
<!-- Example: `fix(nx): must begin with lowercase` -->

<!-- If this is a particularly complex change or feature addition, you
can request a dedicated Nx release for this pull request branch. Mention
someone from the Nx team or the `@nrwl/nx-pipelines-reviewers` and they
will confirm if the PR warrants its own release for testing purposes,
and generate it for you if appropriate. -->

## Current Behavior
<!-- This is the behavior we have today -->

* `@nx/devkit` supports Nx 17 - 20.
* Node 18 - 22 is supported 
* `ExecutorContext.projectGraph`, `ExecutorContext.nxJsonConfiguration`,
and `ExecutorContext.projectsConfigurations` is marked as optional
because `ExecutorContext` in some versions of Nx did not have them.
* `ExecutorContext.workspace` is marked as optional because
`ExecutorContext` in some versions of Nx did not have the above
properties which contain the same information.
* `ProjectGraphNode` is deprecated.
* `NxPluginV1.processProjectGraph` was deprecated long ago and there has
been a warning since.
* `appRootPath` has been deprecated for a long time.
* `parseTargetString` had a variant that did not take either the project
graph or the executor context.
* `readNxJson` has a variant which does not take a tree. This was not
clearly deprecated.
* There are handlers to require from `@nx/` instead of `@nrwl`
* Nx tries to get a root install from `@nrwl/cli`


## Expected Behavior
<!-- This is the behavior we should expect with the changes in this PR
-->

* `@nx/devkit` supports Nx 19 - 21.
* Node 20 - 22 is supported 
* `ExecutorContext.projectGraph`, `ExecutorContext.nxJsonConfiguration`,
and `ExecutorContext.projectsConfigurations` is marked as required
because `ExecutorContext` in Nx 19+ is guaranteed to have them.
* `ExecutorContext.workspace` is removed because the same information is
available in the above properties
* `ProjectGraphNode` is removed.
* `NxPluginV1` is no more. All plugins should be `NxPluginV2`.
* `workspaceRoot` is the replacement for `appRootPath`. `appRootPath` is
removed.
* `parseTargetString` no longer has a variant that did not take either
the project graph or the executor context.
* `readNxJson` still has a variant which does not take a tree but it's
clearly deprecated to be removed in Nx 21.
* `@nrwl` packages are no more so we don't have to redirect requires
anymore.
* `@nrwl/cli` is no more so Nx shouldn't try to get a root install there
* 

## Related Issue(s)
<!-- Please link the issue being fixed so it gets closed when this is
merged. -->

Fixes #
This commit is contained in:
Jason Jean 2024-10-03 17:35:47 -04:00 committed by GitHub
parent d131b0b677
commit 23bebd91e7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
79 changed files with 606 additions and 1381 deletions

View File

@ -5,12 +5,12 @@
A pair of file patterns and [CreateNodesFunction](../../devkit/documents/CreateNodesFunction) A pair of file patterns and [CreateNodesFunction](../../devkit/documents/CreateNodesFunction)
Nx 19.2+: Both original `CreateNodes` and `CreateNodesV2` are supported. Nx will only invoke `CreateNodesV2` if it is present. Nx 19.2+: Both original `CreateNodes` and `CreateNodesV2` are supported. Nx will only invoke `CreateNodesV2` if it is present.
Nx 20.X : The `CreateNodesV2` will be the only supported API. This typing will still exist, but be identical to `CreateNodesV2`. Nx 21.X : The `CreateNodesV2` will be the only supported API. This typing will still exist, but be identical to `CreateNodesV2`.
Nx **will not** invoke the original `plugin.createNodes` callback. This should give plugin authors a window to transition. Nx **will not** invoke the original `plugin.createNodes` callback. This should give plugin authors a window to transition.
Plugin authors should update their plugin's `createNodes` function to align with `CreateNodesV2` / the updated `CreateNodes`. Plugin authors should update their plugin's `createNodes` function to align with `CreateNodesV2` / the updated `CreateNodes`.
The plugin should contain something like: `export createNodes = createNodesV2;` during this period. This will allow the plugin The plugin should contain something like: `export createNodes = createNodesV2;` during this period. This will allow the plugin
to maintain compatibility with Nx 19.2 and up. to maintain compatibility with Nx 19.2 and up.
Nx 21.X : The `CreateNodesV2` typing will be removed, as it has replaced `CreateNodes`. Nx 22.X : The `CreateNodesV2` typing will be removed, as it has replaced `CreateNodes`.
**`Deprecated`** **`Deprecated`**

View File

@ -3,7 +3,7 @@
Ƭ **CreateNodesV2**\<`T`\>: readonly [projectFilePattern: string, createNodesFunction: CreateNodesFunctionV2\<T\>] Ƭ **CreateNodesV2**\<`T`\>: readonly [projectFilePattern: string, createNodesFunction: CreateNodesFunctionV2\<T\>]
A pair of file patterns and [CreateNodesFunctionV2](../../devkit/documents/CreateNodesFunctionV2) A pair of file patterns and [CreateNodesFunctionV2](../../devkit/documents/CreateNodesFunctionV2)
In Nx 20 [CreateNodes](../../devkit/documents/CreateNodes) will be replaced with this type. In Nx 21, this type will be removed. In Nx 21 [CreateNodes](../../devkit/documents/CreateNodes) will be replaced with this type. In Nx 22, this type will be removed.
#### Type parameters #### Type parameters

View File

@ -17,7 +17,6 @@ Context that is passed into an executor
- [target](../../devkit/documents/ExecutorContext#target): TargetConfiguration<any> - [target](../../devkit/documents/ExecutorContext#target): TargetConfiguration<any>
- [targetName](../../devkit/documents/ExecutorContext#targetname): string - [targetName](../../devkit/documents/ExecutorContext#targetname): string
- [taskGraph](../../devkit/documents/ExecutorContext#taskgraph): TaskGraph - [taskGraph](../../devkit/documents/ExecutorContext#taskgraph): TaskGraph
- [workspace](../../devkit/documents/ExecutorContext#workspace): ProjectsConfigurations & NxJsonConfiguration<string[] | "\*">
## Properties ## Properties
@ -47,23 +46,19 @@ Enable verbose logging
### nxJsonConfiguration ### nxJsonConfiguration
`Optional` **nxJsonConfiguration**: [`NxJsonConfiguration`](../../devkit/documents/NxJsonConfiguration)\<`string`[] \| `"*"`\> **nxJsonConfiguration**: [`NxJsonConfiguration`](../../devkit/documents/NxJsonConfiguration)\<`string`[] \| `"*"`\>
The contents of nx.json. The contents of nx.json.
@todo(vsavkin): mark this as required for v17
--- ---
### projectGraph ### projectGraph
`Optional` **projectGraph**: [`ProjectGraph`](../../devkit/documents/ProjectGraph) **projectGraph**: [`ProjectGraph`](../../devkit/documents/ProjectGraph)
A snapshot of the project graph as A snapshot of the project graph as
it existed when the Nx command was kicked off it existed when the Nx command was kicked off
@todo(vsavkin) mark this required for v17
--- ---
### projectName ### projectName
@ -76,12 +71,10 @@ The name of the project being executed on
### projectsConfigurations ### projectsConfigurations
`Optional` **projectsConfigurations**: [`ProjectsConfigurations`](../../devkit/documents/ProjectsConfigurations) **projectsConfigurations**: [`ProjectsConfigurations`](../../devkit/documents/ProjectsConfigurations)
Projects config Projects config
@todo(vsavkin): mark this as required for v17
--- ---
### root ### root
@ -114,13 +107,3 @@ The name of the target being executed
A snapshot of the task graph as A snapshot of the task graph as
it existed when the Nx command was kicked off it existed when the Nx command was kicked off
---
### workspace
`Optional` **workspace**: [`ProjectsConfigurations`](../../devkit/documents/ProjectsConfigurations) & [`NxJsonConfiguration`](../../devkit/documents/NxJsonConfiguration)\<`string`[] \| `"*"`\>
Deprecated. Use projectsConfigurations or nxJsonConfiguration
The full workspace configuration
@todo(vsavkin): remove after v17

View File

@ -1,5 +1,5 @@
# Type alias: NxPlugin # Type alias: NxPlugin
Ƭ **NxPlugin**: [`NxPluginV1`](../../devkit/documents/NxPluginV1) \| [`NxPluginV2`](../../devkit/documents/NxPluginV2) Ƭ **NxPlugin**: [`NxPluginV2`](../../devkit/documents/NxPluginV2)
A plugin for Nx A plugin for Nx

View File

@ -1,16 +0,0 @@
# Type alias: NxPluginV1
Ƭ **NxPluginV1**: `Object`
**`Deprecated`**
Use [NxPluginV2](../../devkit/documents/NxPluginV2) instead. This will be removed in Nx 20
#### Type declaration
| Name | Type | Description |
| :------------------------ | :------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | `string` | - |
| `processProjectGraph?` | `ProjectGraphProcessor` | **`Deprecated`** Use [CreateNodes](../../devkit/documents/CreateNodes) and [CreateDependencies](../../devkit/documents/CreateDependencies) instead. This will be removed in Nx 20 |
| `projectFilePatterns?` | `string`[] | A glob pattern to search for non-standard project files. @example: ["*.csproj", "pom.xml"] **`Deprecated`** Use [CreateNodes](../../devkit/documents/CreateNodes) instead. This will be removed in Nx 20 |
| `registerProjectTargets?` | [`ProjectTargetConfigurator`](../../devkit/documents/ProjectTargetConfigurator) | **`Deprecated`** Add targets to the projects inside of [CreateNodes](../../devkit/documents/CreateNodes) instead. This will be removed in Nx 20 |

View File

@ -16,6 +16,6 @@ A plugin for Nx which creates nodes and dependencies for the [ProjectGraph](../.
| :-------------------- | :------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | :-------------------- | :------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `createDependencies?` | [`CreateDependencies`](../../devkit/documents/CreateDependencies)\<`TOptions`\> | Provides a function to analyze files to create dependencies for the [ProjectGraph](../../devkit/documents/ProjectGraph) | | `createDependencies?` | [`CreateDependencies`](../../devkit/documents/CreateDependencies)\<`TOptions`\> | Provides a function to analyze files to create dependencies for the [ProjectGraph](../../devkit/documents/ProjectGraph) |
| `createMetadata?` | [`CreateMetadata`](../../devkit/documents/CreateMetadata)\<`TOptions`\> | Provides a function to create metadata for the [ProjectGraph](../../devkit/documents/ProjectGraph) | | `createMetadata?` | [`CreateMetadata`](../../devkit/documents/CreateMetadata)\<`TOptions`\> | Provides a function to create metadata for the [ProjectGraph](../../devkit/documents/ProjectGraph) |
| `createNodes?` | [`CreateNodes`](../../devkit/documents/CreateNodes)\<`TOptions`\> | Provides a file pattern and function that retrieves configuration info from those files. e.g. { '**/\*.csproj': buildProjectsFromCsProjFile } **`Deprecated`\*\* Use createNodesV2 instead. In Nx 20 support for calling createNodes with a single file for the first argument will be removed. | | `createNodes?` | [`CreateNodes`](../../devkit/documents/CreateNodes)\<`TOptions`\> | Provides a file pattern and function that retrieves configuration info from those files. e.g. { '**/\*.csproj': buildProjectsFromCsProjFile } **`Deprecated`\*\* Use createNodesV2 instead. In Nx 21 support for calling createNodes with a single file for the first argument will be removed. |
| `createNodesV2?` | [`CreateNodesV2`](../../devkit/documents/CreateNodesV2)\<`TOptions`\> | Provides a file pattern and function that retrieves configuration info from those files. e.g. { '\*_/_.csproj': buildProjectsFromCsProjFiles } In Nx 20 createNodes will be replaced with this property. In Nx 21, this property will be removed. | | `createNodesV2?` | [`CreateNodesV2`](../../devkit/documents/CreateNodesV2)\<`TOptions`\> | Provides a file pattern and function that retrieves configuration info from those files. e.g. { '\*_/_.csproj': buildProjectsFromCsProjFiles } In Nx 21 createNodes will be replaced with this property. In Nx 22, this property will be removed. |
| `name` | `string` | - | | `name` | `string` | - |

View File

@ -1,288 +0,0 @@
# Class: ProjectGraphBuilder
A class which builds up a project graph
**`Deprecated`**
The ProjectGraphProcessor has been deprecated. Use a [CreateNodes](../../devkit/documents/CreateNodes) and/or a [CreateDependencies](../../devkit/documents/CreateDependencies) instead. This will be removed in Nx 20.
## Table of contents
### Constructors
- [constructor](../../devkit/documents/ProjectGraphBuilder#constructor)
### Properties
- [graph](../../devkit/documents/ProjectGraphBuilder#graph): ProjectGraph
- [removedEdges](../../devkit/documents/ProjectGraphBuilder#removededges): Object
### Methods
- [addDependency](../../devkit/documents/ProjectGraphBuilder#adddependency)
- [addDynamicDependency](../../devkit/documents/ProjectGraphBuilder#adddynamicdependency)
- [addExplicitDependency](../../devkit/documents/ProjectGraphBuilder#addexplicitdependency)
- [addExternalNode](../../devkit/documents/ProjectGraphBuilder#addexternalnode)
- [addImplicitDependency](../../devkit/documents/ProjectGraphBuilder#addimplicitdependency)
- [addNode](../../devkit/documents/ProjectGraphBuilder#addnode)
- [addStaticDependency](../../devkit/documents/ProjectGraphBuilder#addstaticdependency)
- [getUpdatedProjectGraph](../../devkit/documents/ProjectGraphBuilder#getupdatedprojectgraph)
- [mergeProjectGraph](../../devkit/documents/ProjectGraphBuilder#mergeprojectgraph)
- [removeDependency](../../devkit/documents/ProjectGraphBuilder#removedependency)
- [removeNode](../../devkit/documents/ProjectGraphBuilder#removenode)
- [setVersion](../../devkit/documents/ProjectGraphBuilder#setversion)
## Constructors
### constructor
**new ProjectGraphBuilder**(`graph?`, `projectFileMap?`, `nonProjectFiles?`): [`ProjectGraphBuilder`](../../devkit/documents/ProjectGraphBuilder)
#### Parameters
| Name | Type |
| :----------------- | :-------------------------------------------------------- |
| `graph?` | [`ProjectGraph`](../../devkit/documents/ProjectGraph) |
| `projectFileMap?` | [`ProjectFileMap`](../../devkit/documents/ProjectFileMap) |
| `nonProjectFiles?` | [`FileData`](../../devkit/documents/FileData)[] |
#### Returns
[`ProjectGraphBuilder`](../../devkit/documents/ProjectGraphBuilder)
## Properties
### graph
`Readonly` **graph**: [`ProjectGraph`](../../devkit/documents/ProjectGraph)
---
### removedEdges
`Readonly` **removedEdges**: `Object` = `{}`
#### Index signature
▪ [source: `string`]: `Set`\<`string`\>
## Methods
### addDependency
**addDependency**(`source`, `target`, `type`, `sourceFile?`): `void`
#### Parameters
| Name | Type |
| :------------ | :-------------------------------------------------------- |
| `source` | `string` |
| `target` | `string` |
| `type` | [`DependencyType`](../../devkit/documents/DependencyType) |
| `sourceFile?` | `string` |
#### Returns
`void`
---
### addDynamicDependency
**addDynamicDependency**(`sourceProjectName`, `targetProjectName`, `sourceProjectFile`): `void`
Adds dynamic dependency from source project to target project
#### Parameters
| Name | Type |
| :------------------ | :------- |
| `sourceProjectName` | `string` |
| `targetProjectName` | `string` |
| `sourceProjectFile` | `string` |
#### Returns
`void`
---
### addExplicitDependency
**addExplicitDependency**(`sourceProjectName`, `sourceProjectFile`, `targetProjectName`): `void`
Add an explicit dependency from a file in source project to target project
#### Parameters
| Name | Type |
| :------------------ | :------- |
| `sourceProjectName` | `string` |
| `sourceProjectFile` | `string` |
| `targetProjectName` | `string` |
#### Returns
`void`
**`Deprecated`**
this method will be removed in v17. Use [addStaticDependency](../../devkit/documents/ProjectGraphBuilder#addstaticdependency) or [addDynamicDependency](../../devkit/documents/ProjectGraphBuilder#adddynamicdependency) instead
---
### addExternalNode
**addExternalNode**(`node`): `void`
Adds a external node to the project graph
#### Parameters
| Name | Type |
| :----- | :---------------------------------------------------------------------------- |
| `node` | [`ProjectGraphExternalNode`](../../devkit/documents/ProjectGraphExternalNode) |
#### Returns
`void`
---
### addImplicitDependency
**addImplicitDependency**(`sourceProjectName`, `targetProjectName`): `void`
Adds implicit dependency from source project to target project
#### Parameters
| Name | Type |
| :------------------ | :------- |
| `sourceProjectName` | `string` |
| `targetProjectName` | `string` |
#### Returns
`void`
---
### addNode
**addNode**(`node`): `void`
Adds a project node to the project graph
#### Parameters
| Name | Type |
| :----- | :-------------------------------------------------------------------------- |
| `node` | [`ProjectGraphProjectNode`](../../devkit/documents/ProjectGraphProjectNode) |
#### Returns
`void`
---
### addStaticDependency
**addStaticDependency**(`sourceProjectName`, `targetProjectName`, `sourceProjectFile?`): `void`
Adds static dependency from source project to target project
#### Parameters
| Name | Type |
| :------------------- | :------- |
| `sourceProjectName` | `string` |
| `targetProjectName` | `string` |
| `sourceProjectFile?` | `string` |
#### Returns
`void`
---
### getUpdatedProjectGraph
**getUpdatedProjectGraph**(): [`ProjectGraph`](../../devkit/documents/ProjectGraph)
#### Returns
[`ProjectGraph`](../../devkit/documents/ProjectGraph)
---
### mergeProjectGraph
**mergeProjectGraph**(`p`): `void`
Merges the nodes and dependencies of p into the built project graph.
#### Parameters
| Name | Type |
| :--- | :---------------------------------------------------- |
| `p` | [`ProjectGraph`](../../devkit/documents/ProjectGraph) |
#### Returns
`void`
---
### removeDependency
**removeDependency**(`sourceProjectName`, `targetProjectName`): `void`
Removes a dependency from source project to target project
#### Parameters
| Name | Type |
| :------------------ | :------- |
| `sourceProjectName` | `string` |
| `targetProjectName` | `string` |
#### Returns
`void`
---
### removeNode
**removeNode**(`name`): `void`
Removes a node and all of its dependency edges from the graph
#### Parameters
| Name | Type |
| :----- | :------- |
| `name` | `string` |
#### Returns
`void`
---
### setVersion
**setVersion**(`version`): `void`
Set version of the project graph
#### Parameters
| Name | Type |
| :-------- | :------- |
| `version` | `string` |
#### Returns
`void`

View File

@ -1,7 +0,0 @@
# Type alias: ProjectGraphNode
Ƭ **ProjectGraphNode**: [`ProjectGraphProjectNode`](../../devkit/documents/ProjectGraphProjectNode) \| [`ProjectGraphExternalNode`](../../devkit/documents/ProjectGraphExternalNode)
**`Deprecated`**
this type will be removed in v16. Use [ProjectGraphProjectNode](../../devkit/documents/ProjectGraphProjectNode) or [ProjectGraphExternalNode](../../devkit/documents/ProjectGraphExternalNode) instead

View File

@ -1,57 +0,0 @@
# Interface: ProjectGraphProcessorContext
Additional information to be used to process a project graph
**`Deprecated`**
The ProjectGraphProcessor is deprecated. This will be removed in Nx 20.
## Table of contents
### Properties
- [fileMap](../../devkit/documents/ProjectGraphProcessorContext#filemap): ProjectFileMap
- [filesToProcess](../../devkit/documents/ProjectGraphProcessorContext#filestoprocess): ProjectFileMap
- [nxJsonConfiguration](../../devkit/documents/ProjectGraphProcessorContext#nxjsonconfiguration): NxJsonConfiguration<string[] | "\*">
- [projectsConfigurations](../../devkit/documents/ProjectGraphProcessorContext#projectsconfigurations): ProjectsConfigurations
- [workspace](../../devkit/documents/ProjectGraphProcessorContext#workspace): Workspace
## Properties
### fileMap
**fileMap**: [`ProjectFileMap`](../../devkit/documents/ProjectFileMap)
All files in the workspace
---
### filesToProcess
**filesToProcess**: [`ProjectFileMap`](../../devkit/documents/ProjectFileMap)
Files changes since last invocation
---
### nxJsonConfiguration
**nxJsonConfiguration**: [`NxJsonConfiguration`](../../devkit/documents/NxJsonConfiguration)\<`string`[] \| `"*"`\>
---
### projectsConfigurations
**projectsConfigurations**: [`ProjectsConfigurations`](../../devkit/documents/ProjectsConfigurations)
---
### workspace
**workspace**: [`Workspace`](../../devkit/documents/Workspace)
Workspace information such as projects and configuration
**`Deprecated`**
use [projectsConfigurations](../../devkit/documents/ProjectGraphProcessorContext#projectsconfigurations) or [nxJsonConfiguration](../../devkit/documents/ProjectGraphProcessorContext#nxjsonconfiguration) instead

View File

@ -1,21 +0,0 @@
# Type alias: ProjectTargetConfigurator
Ƭ **ProjectTargetConfigurator**: (`file`: `string`) => `Record`\<`string`, [`TargetConfiguration`](../../devkit/documents/TargetConfiguration)\>
**`Deprecated`**
Add targets to the projects in a [CreateNodes](../../devkit/documents/CreateNodes) function instead. This will be removed in Nx 20
#### Type declaration
▸ (`file`): `Record`\<`string`, [`TargetConfiguration`](../../devkit/documents/TargetConfiguration)\>
##### Parameters
| Name | Type |
| :----- | :------- |
| `file` | `string` |
##### Returns
`Record`\<`string`, [`TargetConfiguration`](../../devkit/documents/TargetConfiguration)\>

View File

@ -20,7 +20,6 @@ It only uses language primitives and immutable objects
### Classes ### Classes
- [AggregateCreateNodesError](../../devkit/documents/AggregateCreateNodesError) - [AggregateCreateNodesError](../../devkit/documents/AggregateCreateNodesError)
- [ProjectGraphBuilder](../../devkit/documents/ProjectGraphBuilder)
### Interfaces ### Interfaces
@ -49,7 +48,6 @@ It only uses language primitives and immutable objects
- [ProjectGraph](../../devkit/documents/ProjectGraph) - [ProjectGraph](../../devkit/documents/ProjectGraph)
- [ProjectGraphDependency](../../devkit/documents/ProjectGraphDependency) - [ProjectGraphDependency](../../devkit/documents/ProjectGraphDependency)
- [ProjectGraphExternalNode](../../devkit/documents/ProjectGraphExternalNode) - [ProjectGraphExternalNode](../../devkit/documents/ProjectGraphExternalNode)
- [ProjectGraphProcessorContext](../../devkit/documents/ProjectGraphProcessorContext)
- [ProjectGraphProjectNode](../../devkit/documents/ProjectGraphProjectNode) - [ProjectGraphProjectNode](../../devkit/documents/ProjectGraphProjectNode)
- [ProjectsConfigurations](../../devkit/documents/ProjectsConfigurations) - [ProjectsConfigurations](../../devkit/documents/ProjectsConfigurations)
- [RemoteCache](../../devkit/documents/RemoteCache) - [RemoteCache](../../devkit/documents/RemoteCache)
@ -85,12 +83,9 @@ It only uses language primitives and immutable objects
- [ImplicitDependency](../../devkit/documents/ImplicitDependency) - [ImplicitDependency](../../devkit/documents/ImplicitDependency)
- [ImplicitDependencyEntry](../../devkit/documents/ImplicitDependencyEntry) - [ImplicitDependencyEntry](../../devkit/documents/ImplicitDependencyEntry)
- [NxPlugin](../../devkit/documents/NxPlugin) - [NxPlugin](../../devkit/documents/NxPlugin)
- [NxPluginV1](../../devkit/documents/NxPluginV1)
- [NxPluginV2](../../devkit/documents/NxPluginV2) - [NxPluginV2](../../devkit/documents/NxPluginV2)
- [PackageManager](../../devkit/documents/PackageManager) - [PackageManager](../../devkit/documents/PackageManager)
- [PluginConfiguration](../../devkit/documents/PluginConfiguration) - [PluginConfiguration](../../devkit/documents/PluginConfiguration)
- [ProjectGraphNode](../../devkit/documents/ProjectGraphNode)
- [ProjectTargetConfigurator](../../devkit/documents/ProjectTargetConfigurator)
- [ProjectType](../../devkit/documents/ProjectType) - [ProjectType](../../devkit/documents/ProjectType)
- [ProjectsMetadata](../../devkit/documents/ProjectsMetadata) - [ProjectsMetadata](../../devkit/documents/ProjectsMetadata)
- [PromiseExecutor](../../devkit/documents/PromiseExecutor) - [PromiseExecutor](../../devkit/documents/PromiseExecutor)
@ -105,7 +100,6 @@ It only uses language primitives and immutable objects
### Variables ### Variables
- [NX_VERSION](../../devkit/documents/NX_VERSION): string - [NX_VERSION](../../devkit/documents/NX_VERSION): string
- [appRootPath](../../devkit/documents/appRootPath): string
- [cacheDir](../../devkit/documents/cacheDir): string - [cacheDir](../../devkit/documents/cacheDir): string
- [logger](../../devkit/documents/logger): Object - [logger](../../devkit/documents/logger): Object
- [output](../../devkit/documents/output): CLIOutput - [output](../../devkit/documents/output): CLIOutput

View File

@ -1,9 +0,0 @@
# Variable: appRootPath
`Const` **appRootPath**: `string` = `workspaceRoot`
The root of the workspace.
**`Deprecated`**
use workspaceRoot instead

View File

@ -1,19 +1,5 @@
# Function: parseTargetString # Function: parseTargetString
**parseTargetString**(`targetString`): [`Target`](../../devkit/documents/Target)
@deprecated(v17) A project graph should be passed to parseTargetString for best accuracy.
#### Parameters
| Name | Type |
| :------------- | :------- |
| `targetString` | `string` |
#### Returns
[`Target`](../../devkit/documents/Target)
**parseTargetString**(`targetString`, `projectGraph`): [`Target`](../../devkit/documents/Target) **parseTargetString**(`targetString`, `projectGraph`): [`Target`](../../devkit/documents/Target)
Parses a target string into {project, target, configuration} Parses a target string into {project, target, configuration}

View File

@ -8,7 +8,7 @@
**`Deprecated`** **`Deprecated`**
You must pass a [Tree](../../devkit/documents/Tree) You must pass a [Tree](../../devkit/documents/Tree). This will be removed in Nx 21.
**readNxJson**(`tree`): [`NxJsonConfiguration`](../../devkit/documents/NxJsonConfiguration) \| `null` **readNxJson**(`tree`): [`NxJsonConfiguration`](../../devkit/documents/NxJsonConfiguration) \| `null`

View File

@ -20,7 +20,6 @@ It only uses language primitives and immutable objects
### Classes ### Classes
- [AggregateCreateNodesError](../../devkit/documents/AggregateCreateNodesError) - [AggregateCreateNodesError](../../devkit/documents/AggregateCreateNodesError)
- [ProjectGraphBuilder](../../devkit/documents/ProjectGraphBuilder)
### Interfaces ### Interfaces
@ -49,7 +48,6 @@ It only uses language primitives and immutable objects
- [ProjectGraph](../../devkit/documents/ProjectGraph) - [ProjectGraph](../../devkit/documents/ProjectGraph)
- [ProjectGraphDependency](../../devkit/documents/ProjectGraphDependency) - [ProjectGraphDependency](../../devkit/documents/ProjectGraphDependency)
- [ProjectGraphExternalNode](../../devkit/documents/ProjectGraphExternalNode) - [ProjectGraphExternalNode](../../devkit/documents/ProjectGraphExternalNode)
- [ProjectGraphProcessorContext](../../devkit/documents/ProjectGraphProcessorContext)
- [ProjectGraphProjectNode](../../devkit/documents/ProjectGraphProjectNode) - [ProjectGraphProjectNode](../../devkit/documents/ProjectGraphProjectNode)
- [ProjectsConfigurations](../../devkit/documents/ProjectsConfigurations) - [ProjectsConfigurations](../../devkit/documents/ProjectsConfigurations)
- [RemoteCache](../../devkit/documents/RemoteCache) - [RemoteCache](../../devkit/documents/RemoteCache)
@ -85,12 +83,9 @@ It only uses language primitives and immutable objects
- [ImplicitDependency](../../devkit/documents/ImplicitDependency) - [ImplicitDependency](../../devkit/documents/ImplicitDependency)
- [ImplicitDependencyEntry](../../devkit/documents/ImplicitDependencyEntry) - [ImplicitDependencyEntry](../../devkit/documents/ImplicitDependencyEntry)
- [NxPlugin](../../devkit/documents/NxPlugin) - [NxPlugin](../../devkit/documents/NxPlugin)
- [NxPluginV1](../../devkit/documents/NxPluginV1)
- [NxPluginV2](../../devkit/documents/NxPluginV2) - [NxPluginV2](../../devkit/documents/NxPluginV2)
- [PackageManager](../../devkit/documents/PackageManager) - [PackageManager](../../devkit/documents/PackageManager)
- [PluginConfiguration](../../devkit/documents/PluginConfiguration) - [PluginConfiguration](../../devkit/documents/PluginConfiguration)
- [ProjectGraphNode](../../devkit/documents/ProjectGraphNode)
- [ProjectTargetConfigurator](../../devkit/documents/ProjectTargetConfigurator)
- [ProjectType](../../devkit/documents/ProjectType) - [ProjectType](../../devkit/documents/ProjectType)
- [ProjectsMetadata](../../devkit/documents/ProjectsMetadata) - [ProjectsMetadata](../../devkit/documents/ProjectsMetadata)
- [PromiseExecutor](../../devkit/documents/PromiseExecutor) - [PromiseExecutor](../../devkit/documents/PromiseExecutor)
@ -105,7 +100,6 @@ It only uses language primitives and immutable objects
### Variables ### Variables
- [NX_VERSION](../../devkit/documents/NX_VERSION): string - [NX_VERSION](../../devkit/documents/NX_VERSION): string
- [appRootPath](../../devkit/documents/appRootPath): string
- [cacheDir](../../devkit/documents/cacheDir): string - [cacheDir](../../devkit/documents/cacheDir): string
- [logger](../../devkit/documents/logger): Object - [logger](../../devkit/documents/logger): Object
- [output](../../devkit/documents/output): CLIOutput - [output](../../devkit/documents/output): CLIOutput

View File

@ -8,8 +8,9 @@ and the version of NodeJS that we tested it against.
| Nx Version | Node Version | Typescript Version | | Nx Version | Node Version | Typescript Version |
| --------------- | ---------------- | ------------------ | | --------------- | ---------------- | ------------------ |
| 19.x (latest) | 22.x, 20.x, 18.x | ~5.4.2 | | 20.x (latest) | 22.x, 20.x | ~5.4.2 |
| 18.x (previous) | 20.x, 18.x | ~5.4.2 | | 19.x (previous) | 22.x, 20.x, 18.x | ~5.4.2 |
| 18.x | 20.x, 18.x | ~5.4.2 |
| 17.x | 20.x, 18.x | ~5.1.0 | | 17.x | 20.x, 18.x | ~5.1.0 |
| 16.x | 20.x, 18.x, 16.x | ~5.1.0 | | 16.x | 20.x, 18.x, 16.x | ~5.1.0 |
| 15.x | 18.x, 16.x, 14.x | ~5.0.0 | | 15.x | 18.x, 16.x, 14.x | ~5.0.0 |

View File

@ -8,8 +8,9 @@ and the version of NodeJS that we tested it against.
| Nx Version | Node Version | Typescript Version | | Nx Version | Node Version | Typescript Version |
| --------------- | ---------------- | ------------------ | | --------------- | ---------------- | ------------------ |
| 19.x (latest) | 22.x, 20.x, 18.x | ~5.4.2 | | 20.x (latest) | 22.x, 20.x | ~5.4.2 |
| 18.x (previous) | 20.x, 18.x | ~5.4.2 | | 19.x (previous) | 22.x, 20.x, 18.x | ~5.4.2 |
| 18.x | 20.x, 18.x | ~5.4.2 |
| 17.x | 20.x, 18.x | ~5.1.0 | | 17.x | 20.x, 18.x | ~5.1.0 |
| 16.x | 20.x, 18.x, 16.x | ~5.1.0 | | 16.x | 20.x, 18.x, 16.x | ~5.1.0 |
| 15.x | 18.x, 16.x, 14.x | ~5.0.0 | | 15.x | 18.x, 16.x, 14.x | ~5.0.0 |

View File

@ -55,32 +55,43 @@ describe('Extra Nx Misc Tests', () => {
const nxJson = readJson('nx.json'); const nxJson = readJson('nx.json');
nxJson.plugins = ['./tools/plugin']; nxJson.plugins = ['./tools/plugin'];
updateFile('nx.json', JSON.stringify(nxJson)); updateFile('nx.json', JSON.stringify(nxJson));
updateFile('test/project.txt', 'plugin-node');
updateFile('test2/project.txt', 'plugin-node2');
updateFile('test2/dependencies.txt', 'plugin-node');
updateFile( updateFile(
'tools/plugin.js', 'tools/plugin.js',
` `
const { readFileSync } = require('fs');
const { dirname } = require('path');
module.exports = { module.exports = {
processProjectGraph: (graph) => { createNodesV2: ['**/project.txt', (configFiles) => {
const Builder = require('@nx/devkit').ProjectGraphBuilder; const results = [];
const builder = new Builder(graph); for (const configFile of configFiles) {
builder.addNode({ const name = readFileSync(configFile, 'utf8');
name: 'plugin-node', results.push([configFile, {
type: 'lib', projects: {
data: { [dirname(configFile)]: {
root: 'test' name: name,
} }
});
builder.addNode({
name: 'plugin-node2',
type: 'lib',
data: {
root: 'test2'
} }
}); }]);
builder.addImplicitDependency( }
'plugin-node',
'plugin-node2' return results;
); }],
return builder.getUpdatedProjectGraph(); createDependencies: () => {
return [
{
source: 'plugin-node',
/**
* The name of a {@link ProjectGraphProjectNode} that the source project depends on
*/
target: 'plugin-node2',
type: 'implicit'
}
];
} }
}; };
` `

View File

@ -393,36 +393,6 @@ describe('Nx Running Tests', () => {
); );
}, 10000); }, 10000);
it('should run targets inferred from plugin-specified project files', () => {
// Setup an app to extend
const myapp = uniq('app');
runCLI(`generate @nx/web:app ${myapp} --directory=apps/${myapp}`);
// Register an Nx plugin
const plugin = `module.exports = {
projectFilePatterns: ['inferred-project.nxproject'],
registerProjectTargets: () => ({
"echo": {
"executor": "nx:run-commands",
"options": {
"command": "echo inferred-target"
}
}
})
}`;
updateFile('tools/local-plugin/plugin.js', plugin);
updateFile('nx.json', (c) => {
const nxJson = JSON.parse(c);
nxJson.plugins = ['./tools/local-plugin/plugin.js'];
return JSON.stringify(nxJson, null, 2);
});
// Create a custom project file for the app
updateFile(`apps/${myapp}/inferred-project.nxproject`, 'contents');
expect(runCLI(`echo ${myapp}`)).toContain('inferred-target');
});
it('should build a specific project with the daemon disabled', () => { it('should build a specific project with the daemon disabled', () => {
const myapp = uniq('app'); const myapp = uniq('app');
runCLI(`generate @nx/web:app ${myapp} --directory=apps/${myapp}`); runCLI(`generate @nx/web:app ${myapp} --directory=apps/${myapp}`);

View File

@ -271,47 +271,7 @@ describe('Nx Plugin', () => {
runCLI(`generate @nx/plugin:plugin ${plugin} --linter=eslint`); runCLI(`generate @nx/plugin:plugin ${plugin} --linter=eslint`);
}); });
it('should be able to infer projects and targets (v1)', async () => { it('should be able to infer projects and targets', async () => {
// Setup project inference + target inference
updateFile(
`${plugin}/src/index.ts`,
`import {basename} from 'path'
export function registerProjectTargets(f) {
if (basename(f) === 'my-project-file') {
return {
build: {
executor: "nx:run-commands",
options: {
command: "echo 'custom registered target'"
}
}
}
}
}
export const projectFilePatterns = ['my-project-file'];
`
);
// Register plugin in nx.json (required for inference)
updateFile(`nx.json`, (nxJson) => {
const nx = JSON.parse(nxJson);
nx.plugins = [`@${workspaceName}/${plugin}`];
return JSON.stringify(nx, null, 2);
});
// Create project that should be inferred by Nx
const inferredProject = uniq('inferred');
createFile(`${inferredProject}/my-project-file`);
// Attempt to use inferred project w/ Nx
expect(runCLI(`build ${inferredProject}`)).toContain(
'custom registered target'
);
});
it('should be able to infer projects and targets (v2)', async () => {
// Setup project inference + target inference // Setup project inference + target inference
updateFile(`${plugin}/src/index.ts`, NX_PLUGIN_V2_CONTENTS); updateFile(`${plugin}/src/index.ts`, NX_PLUGIN_V2_CONTENTS);

View File

@ -135,7 +135,7 @@
"@types/jest": "29.5.12", "@types/jest": "29.5.12",
"@types/js-yaml": "^4.0.5", "@types/js-yaml": "^4.0.5",
"@types/marked": "^2.0.0", "@types/marked": "^2.0.0",
"@types/node": "18.19.8", "@types/node": "20.16.10",
"@types/npm-package-arg": "6.1.1", "@types/npm-package-arg": "6.1.1",
"@types/react": "18.3.1", "@types/react": "18.3.1",
"@types/react-dom": "18.3.0", "@types/react-dom": "18.3.0",

View File

@ -5,6 +5,8 @@ import {
normalizePath, normalizePath,
parseTargetString, parseTargetString,
readCachedProjectGraph, readCachedProjectGraph,
readProjectsConfigurationFromProjectGraph,
workspaceRoot,
} from '@nx/devkit'; } from '@nx/devkit';
import { getRootTsConfigPath } from '@nx/js'; import { getRootTsConfigPath } from '@nx/js';
import type { DependentBuildableProjectNode } from '@nx/js/src/utils/buildable-libs-utils'; import type { DependentBuildableProjectNode } from '@nx/js/src/utils/buildable-libs-utils';
@ -34,6 +36,7 @@ import type {
Schema, Schema,
SchemaWithBrowserTarget, SchemaWithBrowserTarget,
} from './schema'; } from './schema';
import { readNxJson } from 'nx/src/config/configuration';
type BuildTargetOptions = { type BuildTargetOptions = {
tsConfig: string; tsConfig: string;
@ -55,11 +58,16 @@ export function executeDevServerBuilder(
const options = normalizeOptions(rawOptions); const options = normalizeOptions(rawOptions);
const projectGraph = readCachedProjectGraph();
const parsedBuildTarget = parseTargetString(options.buildTarget, { const parsedBuildTarget = parseTargetString(options.buildTarget, {
cwd: context.currentDirectory, cwd: context.currentDirectory,
projectGraph: readCachedProjectGraph(), projectGraph,
projectName: context.target.project, projectName: context.target.project,
projectsConfigurations:
readProjectsConfigurationFromProjectGraph(projectGraph),
root: context.workspaceRoot, root: context.workspaceRoot,
nxJsonConfiguration: readNxJson(workspaceRoot),
isVerbose: false, isVerbose: false,
}); });
const browserTargetProjectConfiguration = readCachedProjectConfiguration( const browserTargetProjectConfiguration = readCachedProjectConfiguration(

View File

@ -96,7 +96,7 @@ export async function configurationGeneratorInternal(
await addFiles(tree, opts, projectGraph, hasPlugin); await addFiles(tree, opts, projectGraph, hasPlugin);
if (!hasPlugin) { if (!hasPlugin) {
addTarget(tree, opts); addTarget(tree, opts, projectGraph);
} }
const linterTask = await addLinterToCyProject(tree, { const linterTask = await addLinterToCyProject(tree, {
@ -290,7 +290,11 @@ async function addFiles(
} }
} }
function addTarget(tree: Tree, opts: NormalizedSchema) { function addTarget(
tree: Tree,
opts: NormalizedSchema,
projectGraph: ProjectGraph
) {
const projectConfig = readProjectConfiguration(tree, opts.project); const projectConfig = readProjectConfiguration(tree, opts.project);
const cyVersion = installedCypressVersion(); const cyVersion = installedCypressVersion();
projectConfig.targets ??= {}; projectConfig.targets ??= {};
@ -307,7 +311,7 @@ function addTarget(tree: Tree, opts: NormalizedSchema) {
}, },
}; };
if (opts.devServerTarget) { if (opts.devServerTarget) {
const parsedTarget = parseTargetString(opts.devServerTarget); const parsedTarget = parseTargetString(opts.devServerTarget, projectGraph);
projectConfig.targets.e2e.options = { projectConfig.targets.e2e.options = {
...projectConfig.targets.e2e.options, ...projectConfig.targets.e2e.options,

View File

@ -38,7 +38,7 @@
"enquirer": "~2.3.6" "enquirer": "~2.3.6"
}, },
"peerDependencies": { "peerDependencies": {
"nx": ">= 17 <= 20" "nx": ">= 19 <= 21"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"

View File

@ -1,7 +1,11 @@
import { parseTargetString, targetToTargetString } from './parse-target-string'; import { parseTargetString, targetToTargetString } from './parse-target-string';
import * as splitTarget from 'nx/src/utils/split-target'; import * as splitTarget from 'nx/src/utils/split-target';
import { ExecutorContext } from 'nx/src/devkit-exports'; import {
ExecutorContext,
ProjectGraph,
readProjectsConfigurationFromProjectGraph,
} from 'nx/src/devkit-exports';
const cases = [ const cases = [
{ input: 'one:two', expected: { project: 'one', target: 'two' } }, { input: 'one:two', expected: { project: 'one', target: 'two' } },
@ -16,12 +20,7 @@ const cases = [
]; ];
describe('parseTargetString', () => { describe('parseTargetString', () => {
const mockContext: ExecutorContext = { const graph: ProjectGraph = {
projectName: 'my-project',
cwd: '/virtual',
root: '/virtual',
isVerbose: false,
projectGraph: {
nodes: { nodes: {
'my-project': { 'my-project': {
type: 'lib', type: 'lib',
@ -37,7 +36,15 @@ describe('parseTargetString', () => {
dependencies: {}, dependencies: {},
externalNodes: {}, externalNodes: {},
version: '', version: '',
}, };
const mockContext: ExecutorContext = {
projectName: 'my-project',
cwd: '/virtual',
root: '/virtual',
isVerbose: false,
projectGraph: graph,
projectsConfigurations: readProjectsConfigurationFromProjectGraph(graph),
nxJsonConfiguration: {},
}; };
it.each(cases)('$input -> $expected', ({ input, expected }) => { it.each(cases)('$input -> $expected', ({ input, expected }) => {

View File

@ -6,10 +6,6 @@ import {
} from 'nx/src/devkit-exports'; } from 'nx/src/devkit-exports';
import { splitByColons, splitTarget } from 'nx/src/devkit-internals'; import { splitByColons, splitTarget } from 'nx/src/devkit-internals';
/**
* @deprecated(v17) A project graph should be passed to parseTargetString for best accuracy.
*/
export function parseTargetString(targetString: string): Target;
/** /**
* Parses a target string into {project, target, configuration} * Parses a target string into {project, target, configuration}
* *

View File

@ -17,9 +17,7 @@ export function readTargetOptions<T = any>(
{ project, target, configuration }: Target, { project, target, configuration }: Target,
context: ExecutorContext context: ExecutorContext
): T { ): T {
const projectConfiguration = ( const projectConfiguration = context.projectsConfigurations.projects[project];
context.workspace || context.projectsConfigurations
).projects[project];
if (!projectConfiguration) { if (!projectConfiguration) {
throw new Error(`Unable to find project ${project}`); throw new Error(`Unable to find project ${project}`);
@ -36,7 +34,7 @@ export function readTargetOptions<T = any>(
nodeModule, nodeModule,
executorName, executorName,
context.root, context.root,
context.projectsConfigurations?.projects ?? context.workspace.projects context.projectsConfigurations?.projects
); );
const defaultProject = calculateDefaultProjectName( const defaultProject = calculateDefaultProjectName(

View File

@ -21,6 +21,7 @@ describe('normalizeOptions', () => {
cwd: '/', cwd: '/',
isVerbose: false, isVerbose: false,
projectName: 'myapp', projectName: 'myapp',
nxJsonConfiguration: {},
projectsConfigurations: { projectsConfigurations: {
version: 2, version: 2,
projects: { projects: {

View File

@ -95,6 +95,22 @@ describe('Linter Builder', () => {
projectName, projectName,
root: tempFs.tempDir, root: tempFs.tempDir,
cwd: tempFs.tempDir, cwd: tempFs.tempDir,
projectGraph: {
nodes: {
[projectName]: {
type: 'app',
name: projectName,
data: {
root: `apps/${projectName}`,
sourceRoot: `apps/${projectName}/src`,
targets: {},
},
},
},
dependencies: {
[projectName]: [],
},
},
projectsConfigurations: { projectsConfigurations: {
version: 2, version: 2,
projects: { projects: {

View File

@ -37,6 +37,25 @@ describe('Jest Executor', () => {
mockContext = { mockContext = {
root: '/root', root: '/root',
projectName: 'proj', projectName: 'proj',
projectGraph: {
nodes: {
proj: {
type: 'lib',
name: 'proj',
data: {
root: 'proj',
targets: {
test: {
executor: '@nx/jest:jest',
},
},
},
},
},
dependencies: {
proj: [],
},
},
projectsConfigurations: { projectsConfigurations: {
version: 2, version: 2,
projects: { projects: {

View File

@ -11,6 +11,10 @@ describe('tscExecutor', () => {
context = { context = {
root: '/root', root: '/root',
cwd: '/root', cwd: '/root',
projectGraph: {
nodes: {},
dependencies: {},
},
projectsConfigurations: { projectsConfigurations: {
version: 2, version: 2,
projects: {}, projects: {},

View File

@ -6,7 +6,12 @@ import {
UpdatePackageJsonOption, UpdatePackageJsonOption,
} from './update-package-json'; } from './update-package-json';
import { vol } from 'memfs'; import { vol } from 'memfs';
import { DependencyType, ExecutorContext, ProjectGraph } from '@nx/devkit'; import {
DependencyType,
ExecutorContext,
ProjectGraph,
readProjectsConfigurationFromProjectGraph,
} from '@nx/devkit';
import { DependentBuildableProjectNode } from '../buildable-libs-utils'; import { DependentBuildableProjectNode } from '../buildable-libs-utils';
jest.mock('nx/src/utils/workspace-root', () => ({ jest.mock('nx/src/utils/workspace-root', () => ({
@ -471,6 +476,9 @@ describe('updatePackageJson', () => {
cwd: '', cwd: '',
targetName: 'build', targetName: 'build',
projectGraph, projectGraph,
projectsConfigurations:
readProjectsConfigurationFromProjectGraph(projectGraph),
nxJsonConfiguration: {},
}; };
it('should generate new package if missing', () => { it('should generate new package if missing', () => {

View File

@ -10,6 +10,7 @@ import {
ExecutorContext, ExecutorContext,
parseTargetString, parseTargetString,
readCachedProjectGraph, readCachedProjectGraph,
readProjectsConfigurationFromProjectGraph,
readTargetOptions, readTargetOptions,
stripIndents, stripIndents,
workspaceRoot, workspaceRoot,
@ -24,6 +25,7 @@ import {
import { join } from 'path'; import { join } from 'path';
import { NextBuildBuilderOptions } from '../src/utils/types'; import { NextBuildBuilderOptions } from '../src/utils/types';
import { CypressExecutorOptions } from '@nx/cypress/src/executors/cypress/cypress.impl'; import { CypressExecutorOptions } from '@nx/cypress/src/executors/cypress/cypress.impl';
import { readNxJson } from 'nx/src/config/configuration';
export function nxComponentTestingPreset( export function nxComponentTestingPreset(
pathToConfig: string, pathToConfig: string,
@ -71,6 +73,8 @@ export function nxComponentTestingPreset(
const parsedBuildTarget = parseTargetString(buildTarget, { const parsedBuildTarget = parseTargetString(buildTarget, {
cwd: process.cwd(), cwd: process.cwd(),
root: workspaceRoot, root: workspaceRoot,
projectsConfigurations: readProjectsConfigurationFromProjectGraph(graph),
nxJsonConfiguration: readNxJson(workspaceRoot),
isVerbose: false, isVerbose: false,
projectName: ctProjectName, projectName: ctProjectName,
projectGraph: graph, projectGraph: graph,

View File

@ -23,7 +23,8 @@ export default async function* serveExecutor(
parseTargetString(options.buildTarget, context), parseTargetString(options.buildTarget, context),
context context
); );
const projectRoot = context.workspace.projects[context.projectName].root; const projectRoot =
context.projectsConfigurations.projects[context.projectName].root;
// This is required for the default custom server to work. See the @nx/next:app generator. // This is required for the default custom server to work. See the @nx/next:app generator.
const nextDir = const nextDir =
!options.dev && resolve(context.root, buildOptions.outputPath); !options.dev && resolve(context.root, buildOptions.outputPath);

View File

@ -4,8 +4,6 @@ import { commandsObject } from '../src/command-line/nx-commands';
import { WorkspaceTypeAndRoot } from '../src/utils/find-workspace-root'; import { WorkspaceTypeAndRoot } from '../src/utils/find-workspace-root';
import { stripIndents } from '../src/utils/strip-indents'; import { stripIndents } from '../src/utils/strip-indents';
import * as Mod from 'module';
/** /**
* Nx is being run inside a workspace. * Nx is being run inside a workspace.
* *
@ -18,8 +16,6 @@ export function initLocal(workspace: WorkspaceTypeAndRoot) {
try { try {
performance.mark('init-local'); performance.mark('init-local');
monkeyPatchRequire();
if (workspace.type !== 'nx' && shouldDelegateToAngularCLI()) { if (workspace.type !== 'nx' && shouldDelegateToAngularCLI()) {
console.warn( console.warn(
stripIndents`Using Nx to run Angular CLI commands is deprecated and will be removed in a future version. stripIndents`Using Nx to run Angular CLI commands is deprecated and will be removed in a future version.
@ -162,42 +158,3 @@ To update the cache configuration, you can directly update the relevant options
} }
} }
} }
// TODO(v17): Remove this once the @nrwl/* packages are not
function monkeyPatchRequire() {
const originalRequire = Mod.prototype.require;
(Mod.prototype.require as any) = function (...args) {
const modulePath = args[0];
if (!modulePath.startsWith('@nrwl/')) {
return originalRequire.apply(this, args);
} else {
try {
// Try the original require
return originalRequire.apply(this, args);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
try {
// Retry the require with the @nx package
return originalRequire.apply(
this,
args.map((value, i) => {
if (i !== 0) {
return value;
} else {
return value.replace('@nrwl/', '@nx/');
}
})
);
} catch {
// Throw the original error
throw e;
}
}
}
// do some side-effect of your own
};
}

View File

@ -167,18 +167,9 @@ function resolveNx(workspace: WorkspaceTypeAndRoot | null) {
} catch {} } catch {}
// check for root install // check for root install
try {
return require.resolve('nx/bin/nx.js', { return require.resolve('nx/bin/nx.js', {
paths: [workspace ? workspace.dir : globalsRoot], paths: [workspace ? workspace.dir : globalsRoot],
}); });
} catch {
// TODO(v17): Remove this
// fallback for old CLI install setup
// nx-ignore-next-line
return require.resolve('@nrwl/cli/bin/nx.js', {
paths: [workspace ? workspace.dir : globalsRoot],
});
}
} }
function handleMissingLocalInstallation() { function handleMissingLocalInstallation() {

View File

@ -52,6 +52,11 @@
"description": "Set project name in nx.json explicitly", "description": "Set project name in nx.json explicitly",
"implementation": "./src/migrations/update-19-2-4/set-project-name", "implementation": "./src/migrations/update-19-2-4/set-project-name",
"x-repair-skip": true "x-repair-skip": true
},
"move-use-daemon-process": {
"version": "20.0.0-beta.7",
"description": "Migration for v20.0.0-beta.7",
"implementation": "./src/migrations/update-20-0-0/move-use-daemon-process"
} }
} }
} }

View File

@ -18,11 +18,9 @@ import { projectHasTarget } from '../../utils/project-graph-utils';
import { filterAffected } from '../../project-graph/affected/affected-project-graph'; import { filterAffected } from '../../project-graph/affected/affected-project-graph';
import { TargetDependencyConfig } from '../../config/workspace-json-project-json'; import { TargetDependencyConfig } from '../../config/workspace-json-project-json';
import { readNxJson } from '../../config/configuration'; import { readNxJson } from '../../config/configuration';
import { workspaceConfigurationCheck } from '../../utils/workspace-configuration-check';
import { findMatchingProjects } from '../../utils/find-matching-projects'; import { findMatchingProjects } from '../../utils/find-matching-projects';
import { generateGraph } from '../graph/graph'; import { generateGraph } from '../graph/graph';
import { allFileData } from '../../utils/all-file-data'; import { allFileData } from '../../utils/all-file-data';
import { NX_PREFIX, logger } from '../../utils/logger';
export async function affected( export async function affected(
command: 'graph' | 'print-affected' | 'affected', command: 'graph' | 'print-affected' | 'affected',
@ -41,7 +39,6 @@ export async function affected(
): Promise<void> { ): Promise<void> {
performance.mark('code-loading:end'); performance.mark('code-loading:end');
performance.measure('code-loading', 'init-local', 'code-loading:end'); performance.measure('code-loading', 'init-local', 'code-loading:end');
workspaceConfigurationCheck();
const nxJson = readNxJson(); const nxJson = readNxJson();
const { nxArgs, overrides } = splitArgsIntoNxArgsAndOverrides( const { nxArgs, overrides } = splitArgsIntoNxArgsAndOverrides(

View File

@ -3,7 +3,7 @@
* https://github.com/unjs/changelogen * https://github.com/unjs/changelogen
*/ */
import { interpolate } from '../../../tasks-runner/utils'; import { interpolate } from '../../../tasks-runner/utils';
import { workspaceRoot } from '../../../utils/app-root'; import { workspaceRoot } from '../../../utils/workspace-root';
import { execCommand } from './exec-command'; import { execCommand } from './exec-command';
export interface GitCommitAuthor { export interface GitCommitAuthor {

View File

@ -2,8 +2,8 @@ import { runCommand } from '../../tasks-runner/run-command';
import { import {
NxArgs, NxArgs,
readGraphFileFromGraphArg, readGraphFileFromGraphArg,
splitArgsIntoNxArgsAndOverrides,
} from '../../utils/command-line-utils'; } from '../../utils/command-line-utils';
import { splitArgsIntoNxArgsAndOverrides } from '../../utils/command-line-utils';
import { projectHasTarget } from '../../utils/project-graph-utils'; import { projectHasTarget } from '../../utils/project-graph-utils';
import { connectToNxCloudIfExplicitlyAsked } from '../connect/connect-to-nx-cloud'; import { connectToNxCloudIfExplicitlyAsked } from '../connect/connect-to-nx-cloud';
import { performance } from 'perf_hooks'; import { performance } from 'perf_hooks';
@ -16,7 +16,6 @@ import { TargetDependencyConfig } from '../../config/workspace-json-project-json
import { readNxJson } from '../../config/configuration'; import { readNxJson } from '../../config/configuration';
import { output } from '../../utils/output'; import { output } from '../../utils/output';
import { findMatchingProjects } from '../../utils/find-matching-projects'; import { findMatchingProjects } from '../../utils/find-matching-projects';
import { workspaceConfigurationCheck } from '../../utils/workspace-configuration-check';
import { generateGraph } from '../graph/graph'; import { generateGraph } from '../graph/graph';
export async function runMany( export async function runMany(
@ -35,7 +34,6 @@ export async function runMany(
) { ) {
performance.mark('code-loading:end'); performance.mark('code-loading:end');
performance.measure('code-loading', 'init-local', 'code-loading:end'); performance.measure('code-loading', 'init-local', 'code-loading:end');
workspaceConfigurationCheck();
const nxJson = readNxJson(); const nxJson = readNxJson();
const { nxArgs, overrides } = splitArgsIntoNxArgsAndOverrides( const { nxArgs, overrides } = splitArgsIntoNxArgsAndOverrides(
args, args,

View File

@ -17,7 +17,6 @@ import { output } from '../../utils/output';
import { TargetDependencyConfig } from '../../config/workspace-json-project-json'; import { TargetDependencyConfig } from '../../config/workspace-json-project-json';
import { readNxJson } from '../../config/configuration'; import { readNxJson } from '../../config/configuration';
import { calculateDefaultProjectName } from '../../config/calculate-default-project-name'; import { calculateDefaultProjectName } from '../../config/calculate-default-project-name';
import { workspaceConfigurationCheck } from '../../utils/workspace-configuration-check';
import { generateGraph } from '../graph/graph'; import { generateGraph } from '../graph/graph';
export async function runOne( export async function runOne(
@ -37,7 +36,6 @@ export async function runOne(
): Promise<void> { ): Promise<void> {
performance.mark('code-loading:end'); performance.mark('code-loading:end');
performance.measure('code-loading', 'init-local', 'code-loading:end'); performance.measure('code-loading', 'init-local', 'code-loading:end');
workspaceConfigurationCheck();
const nxJson = readNxJson(); const nxJson = readNxJson();
const projectGraph = await createProjectGraphAsync(); const projectGraph = await createProjectGraphAsync();

View File

@ -190,7 +190,6 @@ async function runExecutorInternal<T extends { success: boolean }>(
target: targetConfig, target: targetConfig,
projectsConfigurations, projectsConfigurations,
nxJsonConfiguration, nxJsonConfiguration,
workspace: { ...projectsConfigurations, ...nxJsonConfiguration },
projectName: project, projectName: project,
targetName: target, targetName: target,
configurationName: configuration, configurationName: configuration,

View File

@ -209,17 +209,13 @@ export interface ExecutorContext {
/** /**
* Projects config * Projects config
*
* @todo(vsavkin): mark this as required for v17
*/ */
projectsConfigurations?: ProjectsConfigurations; projectsConfigurations: ProjectsConfigurations;
/** /**
* The contents of nx.json. * The contents of nx.json.
*
* @todo(vsavkin): mark this as required for v17
*/ */
nxJsonConfiguration?: NxJsonConfiguration; nxJsonConfiguration: NxJsonConfiguration;
/** /**
* The current working directory * The current working directory
@ -234,21 +230,12 @@ export interface ExecutorContext {
/** /**
* A snapshot of the project graph as * A snapshot of the project graph as
* it existed when the Nx command was kicked off * it existed when the Nx command was kicked off
*
* @todo(vsavkin) mark this required for v17
*/ */
projectGraph?: ProjectGraph; projectGraph: ProjectGraph;
/** /**
* A snapshot of the task graph as * A snapshot of the task graph as
* it existed when the Nx command was kicked off * it existed when the Nx command was kicked off
*/ */
taskGraph?: TaskGraph; taskGraph?: TaskGraph;
/**
* Deprecated. Use projectsConfigurations or nxJsonConfiguration
* The full workspace configuration
* @todo(vsavkin): remove after v17
*/
workspace?: ProjectsConfigurations & NxJsonConfiguration;
} }

View File

@ -89,11 +89,6 @@ export enum DependencyType {
implicit = 'implicit', implicit = 'implicit',
} }
/** @deprecated this type will be removed in v16. Use {@link ProjectGraphProjectNode} or {@link ProjectGraphExternalNode} instead */
export type ProjectGraphNode =
| ProjectGraphProjectNode
| ProjectGraphExternalNode;
/** /**
* A node describing a project in a workspace * A node describing a project in a workspace
*/ */

View File

@ -123,10 +123,7 @@ export class DaemonClient {
enabled() { enabled() {
if (this._enabled === undefined) { if (this._enabled === undefined) {
// TODO(v19): Add migration to move it out of existing configs and remove the ?? here. const useDaemonProcessOption = this.nxJson?.useDaemonProcess;
const useDaemonProcessOption =
this.nxJson?.useDaemonProcess ??
this.nxJson?.tasksRunnerOptions?.['default']?.options?.useDaemonProcess;
const env = process.env.NX_DAEMON; const env = process.env.NX_DAEMON;
// env takes precedence // env takes precedence

View File

@ -63,11 +63,6 @@ export { AggregateCreateNodesError } from './project-graph/error-types';
export { createNodesFromFiles } from './project-graph/plugins'; export { createNodesFromFiles } from './project-graph/plugins';
export type {
NxPluginV1,
ProjectTargetConfigurator,
} from './utils/nx-plugin.deprecated';
/** /**
* @category Workspace * @category Workspace
*/ */
@ -153,10 +148,8 @@ export type {
FileData, FileData,
ProjectGraph, ProjectGraph,
ProjectGraphDependency, ProjectGraphDependency,
ProjectGraphNode,
ProjectGraphProjectNode, ProjectGraphProjectNode,
ProjectGraphExternalNode, ProjectGraphExternalNode,
ProjectGraphProcessorContext,
} from './config/project-graph'; } from './config/project-graph';
export type { GraphJson } from './command-line/graph/graph'; export type { GraphJson } from './command-line/graph/graph';
@ -170,7 +163,6 @@ export { DependencyType } from './config/project-graph';
* @category Project Graph * @category Project Graph
*/ */
export { export {
ProjectGraphBuilder,
RawProjectGraphDependency, RawProjectGraphDependency,
DynamicDependency, DynamicDependency,
ImplicitDependency, ImplicitDependency,
@ -208,11 +200,10 @@ export { stripIndents } from './utils/strip-indents';
*/ */
export { joinPathFragments, normalizePath } from './utils/path'; export { joinPathFragments, normalizePath } from './utils/path';
// TODO(v16): Change this to export from './utils/workspace-root'
/** /**
* @category Utils * @category Utils
*/ */
export { workspaceRoot, appRootPath } from './utils/app-root'; export { workspaceRoot } from './utils/workspace-root';
/** /**
* @category Utils * @category Utils

View File

@ -43,7 +43,6 @@ export function convertNxExecutor(executor: Executor) {
targetName: builderContext.target.target, targetName: builderContext.target.target,
target: builderContext.target.target, target: builderContext.target.target,
configurationName: builderContext.target.configuration, configurationName: builderContext.target.configuration,
workspace: { ...nxJsonConfiguration, ...projectsConfigurations },
projectsConfigurations, projectsConfigurations,
nxJsonConfiguration, nxJsonConfiguration,
cwd: process.cwd(), cwd: process.cwd(),

View File

@ -7,7 +7,7 @@ import { readJson, updateJson } from './json';
import { readNxJson as readNxJsonFromDisk } from '../../config/nx-json'; import { readNxJson as readNxJsonFromDisk } from '../../config/nx-json';
/** /**
* @deprecated You must pass a {@link Tree} * @deprecated You must pass a {@link Tree}. This will be removed in Nx 21.
*/ */
export function readNxJson(): NxJsonConfiguration | null; export function readNxJson(): NxJsonConfiguration | null;
export function readNxJson(tree: Tree): NxJsonConfiguration | null; export function readNxJson(tree: Tree): NxJsonConfiguration | null;

View File

@ -0,0 +1,33 @@
import { createTreeWithEmptyWorkspace } from '../../generators/testing-utils/create-tree-with-empty-workspace';
import { Tree } from '../../generators/tree';
import update from './move-use-daemon-process';
import { readNxJson, updateNxJson } from '../../generators/utils/nx-json';
describe('move-use-daemon-process migration', () => {
let tree: Tree;
beforeEach(() => {
tree = createTreeWithEmptyWorkspace();
});
it('should migrate useDaemonProcess', async () => {
updateNxJson(tree, {
tasksRunnerOptions: {
default: {
options: {
useDaemonProcess: false,
},
},
},
});
await update(tree);
expect(readNxJson(tree)).toMatchInlineSnapshot(`
{
"useDaemonProcess": false,
}
`);
});
});

View File

@ -0,0 +1,37 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Tree } from '../../generators/tree';
import { formatChangedFilesWithPrettierIfAvailable } from '../../generators/internal-utils/format-changed-files-with-prettier-if-available';
import { readNxJson, updateNxJson } from '../../generators/utils/nx-json';
import { NxJsonConfiguration } from '../../config/nx-json';
export default async function update(tree: Tree) {
const nxJson = readNxJson(tree) as NxJsonConfiguration;
if (
nxJson?.tasksRunnerOptions?.['default']?.options?.useDaemonProcess !==
undefined
) {
nxJson.useDaemonProcess =
nxJson.tasksRunnerOptions['default'].options.useDaemonProcess;
delete nxJson.tasksRunnerOptions['default'].options.useDaemonProcess;
if (
Object.keys(nxJson.tasksRunnerOptions['default'].options).length === 0
) {
delete nxJson.tasksRunnerOptions['default'].options;
}
if (Object.keys(nxJson.tasksRunnerOptions['default']).length === 0) {
delete nxJson.tasksRunnerOptions['default'];
}
if (Object.keys(nxJson.tasksRunnerOptions).length === 0) {
delete nxJson.tasksRunnerOptions;
}
updateNxJson(tree, nxJson);
}
await formatChangedFilesWithPrettierIfAvailable(tree);
}

View File

@ -983,9 +983,9 @@ describe('TargetProjectLocator', () => {
}); });
describe('isBuiltinModuleImport()', () => { describe('isBuiltinModuleImport()', () => {
const withExclusions = builtinModules.filter( const withExclusions = builtinModules
(s) => !['test/mock_loader'].includes(s) .concat(builtinModules.filter((a) => true).map((s) => 'node:' + s))
); .concat(['node:test', 'node:sqlite', 'node:test']);
it.each(withExclusions)( it.each(withExclusions)(
`should return true for %s builtin module`, `should return true for %s builtin module`,

View File

@ -1,5 +1,5 @@
import { builtinModules } from 'node:module'; import { isBuiltin } from 'node:module';
import { dirname, join, parse, posix, relative } from 'node:path'; import { dirname, join, posix, relative } from 'node:path';
import { clean } from 'semver'; import { clean } from 'semver';
import { import {
ProjectGraphExternalNode, ProjectGraphExternalNode,
@ -31,21 +31,11 @@ type NpmResolutionCache = Map<string, string | null>;
*/ */
const defaultNpmResolutionCache: NpmResolutionCache = new Map(); const defaultNpmResolutionCache: NpmResolutionCache = new Map();
const builtInModuleSet = new Set<string>([ const experimentalNodeModules = new Set(['node:sqlite']);
...builtinModules,
...builtinModules.map((x) => `node:${x}`),
// These are missing in the builtinModules list
// See: https://github.com/nodejs/node/issues/42785
// TODO(v20): We should be safe to use `isBuiltin` function instead of keep the set here (https://nodejs.org/api/module.html#moduleisbuiltinmodulename)
'test',
'node:test',
'node:sea',
'node:sqlite',
]);
export function isBuiltinModuleImport(importExpr: string): boolean { export function isBuiltinModuleImport(importExpr: string): boolean {
const packageName = getPackageNameFromImportPath(importExpr); const packageName = getPackageNameFromImportPath(importExpr);
return builtInModuleSet.has(packageName); return isBuiltin(packageName) || experimentalNodeModules.has(packageName);
} }
export class TargetProjectLocator { export class TargetProjectLocator {

View File

@ -13,7 +13,6 @@ import {
import { applyImplicitDependencies } from './utils/implicit-project-dependencies'; import { applyImplicitDependencies } from './utils/implicit-project-dependencies';
import { normalizeProjectNodes } from './utils/normalize-project-nodes'; import { normalizeProjectNodes } from './utils/normalize-project-nodes';
import { LoadedNxPlugin } from './plugins/internal-api'; import { LoadedNxPlugin } from './plugins/internal-api';
import { isNxPluginV1, isNxPluginV2 } from './plugins/utils';
import { import {
CreateDependenciesContext, CreateDependenciesContext,
CreateMetadataContext, CreateMetadataContext,
@ -32,7 +31,6 @@ import { ProjectConfiguration } from '../config/workspace-json-project-json';
import { readNxJson } from '../config/configuration'; import { readNxJson } from '../config/configuration';
import { existsSync } from 'fs'; import { existsSync } from 'fs';
import { PackageJson } from '../utils/package-json'; import { PackageJson } from '../utils/package-json';
import { output } from '../utils/output';
import { NxWorkspaceFilesExternals } from '../native'; import { NxWorkspaceFilesExternals } from '../native';
import { import {
AggregateProjectGraphError, AggregateProjectGraphError,
@ -40,7 +38,6 @@ import {
isAggregateProjectGraphError, isAggregateProjectGraphError,
isWorkspaceValidityError, isWorkspaceValidityError,
ProcessDependenciesError, ProcessDependenciesError,
ProcessProjectGraphError,
WorkspaceValidityError, WorkspaceValidityError,
} from './error-types'; } from './error-types';
import { import {
@ -99,10 +96,7 @@ export async function buildProjectGraphUsingProjectFileMap(
} }
const errors: Array< const errors: Array<
| CreateMetadataError CreateMetadataError | ProcessDependenciesError | WorkspaceValidityError
| ProcessDependenciesError
| ProcessProjectGraphError
| WorkspaceValidityError
> = []; > = [];
const nxJson = readNxJson(); const nxJson = readNxJson();
@ -306,52 +300,7 @@ async function updateProjectGraphWithPlugins(
sourceMap: ConfigurationSourceMaps sourceMap: ConfigurationSourceMaps
) { ) {
let graph = initProjectGraph; let graph = initProjectGraph;
const errors: Array< const errors: Array<ProcessDependenciesError | CreateMetadataError> = [];
ProcessDependenciesError | ProcessProjectGraphError | CreateMetadataError
> = [];
for (const plugin of plugins) {
try {
if (
isNxPluginV1(plugin) &&
plugin.processProjectGraph &&
!plugin.createDependencies
) {
output.warn({
title: `${plugin.name} is a v1 plugin.`,
bodyLines: [
'Nx has recently released a v2 model for project graph plugins. The `processProjectGraph` method is deprecated. Plugins should use some combination of `createNodes` and `createDependencies` instead.',
],
});
performance.mark(`${plugin.name}:processProjectGraph - start`);
graph = await plugin.processProjectGraph(graph, {
...context,
projectsConfigurations: {
projects: context.projects,
version: 2,
},
fileMap: context.fileMap.projectFileMap,
filesToProcess: context.filesToProcess.projectFileMap,
workspace: {
version: 2,
projects: context.projects,
...context.nxJsonConfiguration,
},
});
performance.mark(`${plugin.name}:processProjectGraph - end`);
performance.measure(
`${plugin.name}:processProjectGraph`,
`${plugin.name}:processProjectGraph - start`,
`${plugin.name}:processProjectGraph - end`
);
}
} catch (e) {
errors.push(
new ProcessProjectGraphError(plugin.name, {
cause: e,
})
);
}
}
const builder = new ProjectGraphBuilder( const builder = new ProjectGraphBuilder(
graph, graph,
@ -360,7 +309,7 @@ async function updateProjectGraphWithPlugins(
); );
const createDependencyPlugins = plugins.filter( const createDependencyPlugins = plugins.filter(
(plugin) => isNxPluginV2(plugin) && plugin.createDependencies (plugin) => plugin.createDependencies
); );
await Promise.all( await Promise.all(
createDependencyPlugins.map(async (plugin) => { createDependencyPlugins.map(async (plugin) => {
@ -439,10 +388,10 @@ export async function applyProjectMetadata(
const errors: CreateMetadataError[] = []; const errors: CreateMetadataError[] = [];
const promises = plugins.map(async (plugin) => { const promises = plugins.map(async (plugin) => {
if (isNxPluginV2(plugin) && plugin.createMetadata) { if (plugin.createMetadata) {
performance.mark(`${plugin.name}:createMetadata - start`); performance.mark(`${plugin.name}:createMetadata - start`);
try { try {
const metadata = await plugin.createMetadata(graph, undefined, context); const metadata = await plugin.createMetadata(graph, context);
results.push({ metadata, pluginName: plugin.name }); results.push({ metadata, pluginName: plugin.name });
} catch (e) { } catch (e) {
errors.push(new CreateMetadataError(e, plugin.name)); errors.push(new CreateMetadataError(e, plugin.name));

View File

@ -14,7 +14,6 @@ export class ProjectGraphError extends Error {
| ProjectsWithNoNameError | ProjectsWithNoNameError
| MultipleProjectsWithSameNameError | MultipleProjectsWithSameNameError
| ProcessDependenciesError | ProcessDependenciesError
| ProcessProjectGraphError
| WorkspaceValidityError | WorkspaceValidityError
>; >;
readonly #partialProjectGraph: ProjectGraph; readonly #partialProjectGraph: ProjectGraph;
@ -27,7 +26,6 @@ export class ProjectGraphError extends Error {
| ProjectsWithNoNameError | ProjectsWithNoNameError
| MultipleProjectsWithSameNameError | MultipleProjectsWithSameNameError
| ProcessDependenciesError | ProcessDependenciesError
| ProcessProjectGraphError
| CreateMetadataError | CreateMetadataError
| WorkspaceValidityError | WorkspaceValidityError
>, >,
@ -312,27 +310,10 @@ export function isWorkspaceValidityError(
e?.name === WorkspaceValidityError.name) e?.name === WorkspaceValidityError.name)
); );
} }
export class ProcessProjectGraphError extends Error {
constructor(public readonly pluginName: string, { cause }) {
super(
`The "${pluginName}" plugin threw an error while processing the project graph:`,
{
cause,
}
);
this.name = this.constructor.name;
this.stack = `${this.message}\n${indentString(cause, 2)}`;
}
}
export class AggregateProjectGraphError extends Error { export class AggregateProjectGraphError extends Error {
constructor( constructor(
public readonly errors: Array< public readonly errors: Array<
| CreateMetadataError CreateMetadataError | ProcessDependenciesError | WorkspaceValidityError
| ProcessDependenciesError
| ProcessProjectGraphError
| WorkspaceValidityError
>, >,
public readonly partialProjectGraph: ProjectGraph public readonly partialProjectGraph: ProjectGraph
) { ) {

View File

@ -180,7 +180,7 @@ export function readPackageJson(): any {
export { FileData }; export { FileData };
/** /**
* TODO(v20): Remove this function. * TODO(v21): Remove this function.
*/ */
function getProjectsSync( function getProjectsSync(
root: string, root: string,

View File

@ -313,7 +313,6 @@ describe('nx deps utils', () => {
const defaults: FileMapCache = { const defaults: FileMapCache = {
version: '6.0', version: '6.0',
nxVersion: nxVersion, nxVersion: nxVersion,
deps: {},
pathMappings: { pathMappings: {
mylib: ['libs/mylib/index.ts'], mylib: ['libs/mylib/index.ts'],
}, },

View File

@ -22,7 +22,6 @@ import { nxVersion } from '../utils/versions';
export interface FileMapCache { export interface FileMapCache {
version: string; version: string;
nxVersion: string; nxVersion: string;
deps: Record<string, string>;
pathMappings: Record<string, any>; pathMappings: Record<string, any>;
nxJsonPlugins: PluginData[]; nxJsonPlugins: PluginData[];
pluginsConfig?: any; pluginsConfig?: any;
@ -113,7 +112,6 @@ export function createProjectFileMapCache(
const newValue: FileMapCache = { const newValue: FileMapCache = {
version: '6.0', version: '6.0',
nxVersion: nxVersion, nxVersion: nxVersion,
deps: packageJsonDeps, // TODO(v19): We can remove this in favor of nxVersion
// compilerOptions may not exist, especially for package-based repos // compilerOptions may not exist, especially for package-based repos
pathMappings: tsConfig?.compilerOptions?.paths || {}, pathMappings: tsConfig?.compilerOptions?.paths || {},
nxJsonPlugins, nxJsonPlugins,

View File

@ -5,7 +5,6 @@ import { join } from 'path';
import { workspaceRoot } from '../../utils/workspace-root'; import { workspaceRoot } from '../../utils/workspace-root';
import { PluginConfiguration } from '../../config/nx-json'; import { PluginConfiguration } from '../../config/nx-json';
import { NxPluginV1 } from '../../utils/nx-plugin.deprecated';
import { shouldMergeAngularProjects } from '../../adapter/angular-json'; import { shouldMergeAngularProjects } from '../../adapter/angular-json';
import { import {
@ -17,10 +16,7 @@ import {
CreateNodesResult, CreateNodesResult,
NxPluginV2, NxPluginV2,
} from './public-api'; } from './public-api';
import { import { ProjectGraph } from '../../config/project-graph';
ProjectGraph,
ProjectGraphProcessor,
} from '../../config/project-graph';
import { loadNxPluginInIsolation } from './isolation'; import { loadNxPluginInIsolation } from './isolation';
import { loadNxPlugin, unregisterPluginTSTranspiler } from './loader'; import { loadNxPlugin, unregisterPluginTSTranspiler } from './loader';
import { createNodesFromFiles } from './utils'; import { createNodesFromFiles } from './utils';
@ -29,7 +25,7 @@ import {
isAggregateCreateNodesError, isAggregateCreateNodesError,
} from '../error-types'; } from '../error-types';
import { IS_WASM } from '../../native'; import { IS_WASM } from '../../native';
import { platform } from 'os'; import { output } from '../../utils/output';
export class LoadedNxPlugin { export class LoadedNxPlugin {
readonly name: string; readonly name: string;
@ -51,13 +47,12 @@ export class LoadedNxPlugin {
graph: ProjectGraph, graph: ProjectGraph,
context: CreateMetadataContext context: CreateMetadataContext
) => ReturnType<CreateMetadata>; ) => ReturnType<CreateMetadata>;
readonly processProjectGraph?: ProjectGraphProcessor;
readonly options?: unknown; readonly options?: unknown;
readonly include?: string[]; readonly include?: string[];
readonly exclude?: string[]; readonly exclude?: string[];
constructor(plugin: NormalizedPlugin, pluginDefinition: PluginConfiguration) { constructor(plugin: NxPluginV2, pluginDefinition: PluginConfiguration) {
this.name = plugin.name; this.name = plugin.name;
if (typeof pluginDefinition !== 'string') { if (typeof pluginDefinition !== 'string') {
this.options = pluginDefinition.options; this.options = pluginDefinition.options;
@ -124,8 +119,6 @@ export class LoadedNxPlugin {
this.createMetadata = (graph, context) => this.createMetadata = (graph, context) =>
plugin.createMetadata(graph, this.options, context); plugin.createMetadata(graph, this.options, context);
} }
this.processProjectGraph = plugin.processProjectGraph;
} }
} }
@ -134,9 +127,6 @@ export type CreateNodesResultWithContext = CreateNodesResult & {
pluginName: string; pluginName: string;
}; };
export type NormalizedPlugin = NxPluginV2 &
Pick<NxPluginV1, 'processProjectGraph'>;
// Short lived cache (cleared between cmd runs) // Short lived cache (cleared between cmd runs)
// holding resolved nx plugin objects. // holding resolved nx plugin objects.
// Allows loaded plugins to not be reloaded when // Allows loaded plugins to not be reloaded when

View File

@ -1,12 +1,8 @@
import { import { ProjectGraph } from '../../../config/project-graph';
ProjectGraph,
ProjectGraphProcessorContext,
} from '../../../config/project-graph';
import { PluginConfiguration } from '../../../config/nx-json'; import { PluginConfiguration } from '../../../config/nx-json';
import { import {
CreateDependenciesContext, CreateDependenciesContext,
CreateMetadataContext, CreateMetadataContext,
CreateNodesContext,
CreateNodesContextV2, CreateNodesContextV2,
} from '../public-api'; } from '../public-api';
import { LoadedNxPlugin } from '../internal-api'; import { LoadedNxPlugin } from '../internal-api';
@ -111,30 +107,6 @@ export interface PluginCreateMetadataResult {
}; };
} }
export interface PluginWorkerProcessProjectGraphMessage {
type: 'processProjectGraph';
payload: {
graph: ProjectGraph;
ctx: ProjectGraphProcessorContext;
tx: string;
};
}
export interface PluginWorkerProcessProjectGraphResult {
type: 'processProjectGraphResult';
payload:
| {
graph: ProjectGraph;
success: true;
tx: string;
}
| {
success: false;
error: Error;
tx: string;
};
}
export interface PluginWorkerShutdownMessage { export interface PluginWorkerShutdownMessage {
type: 'shutdown'; type: 'shutdown';
payload: {}; payload: {};
@ -145,14 +117,12 @@ export type PluginWorkerMessage =
| PluginWorkerShutdownMessage | PluginWorkerShutdownMessage
| PluginWorkerCreateNodesMessage | PluginWorkerCreateNodesMessage
| PluginCreateDependenciesMessage | PluginCreateDependenciesMessage
| PluginWorkerProcessProjectGraphMessage
| PluginCreateMetadataMessage; | PluginCreateMetadataMessage;
export type PluginWorkerResult = export type PluginWorkerResult =
| PluginWorkerLoadResult | PluginWorkerLoadResult
| PluginWorkerCreateNodesResult | PluginWorkerCreateNodesResult
| PluginCreateDependenciesResult | PluginCreateDependenciesResult
| PluginWorkerProcessProjectGraphResult
| PluginCreateMetadataResult; | PluginCreateMetadataResult;
export function isPluginWorkerMessage( export function isPluginWorkerMessage(

View File

@ -190,26 +190,6 @@ function createWorkerHandler(
); );
} }
: undefined, : undefined,
processProjectGraph: result.hasProcessProjectGraph
? (graph, ctx) => {
const tx =
pluginName + worker.pid + ':processProjectGraph:' + txId++;
return registerPendingPromise(
tx,
pending,
() => {
sendMessageOverSocket(socket, {
type: 'processProjectGraph',
payload: { graph, ctx, tx },
});
},
{
operation: 'processProjectGraph',
plugin: pluginName,
}
);
}
: undefined,
createMetadata: result.hasCreateMetadata createMetadata: result.hasCreateMetadata
? (graph, ctx) => { ? (graph, ctx) => {
const tx = const tx =
@ -251,14 +231,6 @@ function createWorkerHandler(
rejector(result.error); rejector(result.error);
} }
}, },
processProjectGraphResult: ({ tx, ...result }) => {
const { resolver, rejector } = pending.get(tx);
if (result.success) {
resolver(result.graph);
} else if (result.success === false) {
rejector(result.error);
}
},
createMetadataResult: ({ tx, ...result }) => { createMetadataResult: ({ tx, ...result }) => {
const { resolver, rejector } = pending.get(tx); const { resolver, rejector } = pending.get(tx);
if (result.success) { if (result.success) {

View File

@ -108,24 +108,6 @@ const server = createServer((socket) => {
}; };
} }
}, },
processProjectGraph: async ({ graph, ctx, tx }) => {
try {
const result = await plugin.processProjectGraph(graph, ctx);
return {
type: 'processProjectGraphResult',
payload: { graph: result, success: true, tx },
};
} catch (e) {
return {
type: 'processProjectGraphResult',
payload: {
success: false,
error: createSerializableError(e),
tx,
},
};
}
},
createMetadata: async ({ graph, context, tx }) => { createMetadata: async ({ graph, context, tx }) => {
try { try {
const result = await plugin.createMetadata(graph, context); const result = await plugin.createMetadata(graph, context);

View File

@ -27,7 +27,6 @@ import { extname } from 'node:path';
import { NxPlugin } from './public-api'; import { NxPlugin } from './public-api';
import { PluginConfiguration } from '../../config/nx-json'; import { PluginConfiguration } from '../../config/nx-json';
import { retrieveProjectConfigurationsWithoutPluginInference } from '../utils/retrieve-workspace-files'; import { retrieveProjectConfigurationsWithoutPluginInference } from '../utils/retrieve-workspace-files';
import { normalizeNxPlugin } from './utils';
import { LoadedNxPlugin } from './internal-api'; import { LoadedNxPlugin } from './internal-api';
import { LoadPluginError } from '../error-types'; import { LoadPluginError } from '../error-types';
import path = require('node:path/posix'); import path = require('node:path/posix');
@ -269,13 +268,13 @@ export async function loadNxPluginAsync(
} }
performance.mark(`Load Nx Plugin: ${moduleName} - start`); performance.mark(`Load Nx Plugin: ${moduleName} - start`);
let { pluginPath, name } = await getPluginPathAndName( const { pluginPath, name } = getPluginPathAndName(
moduleName, moduleName,
paths, paths,
projectsWithoutInference, projectsWithoutInference,
root root
); );
const plugin = normalizeNxPlugin(await importPluginModule(pluginPath)); const plugin = await importPluginModule(pluginPath);
plugin.name ??= name; plugin.name ??= name;
performance.mark(`Load Nx Plugin: ${moduleName} - end`); performance.mark(`Load Nx Plugin: ${moduleName} - end`);
performance.measure( performance.measure(

View File

@ -1,7 +1,6 @@
// This file represents the public API for plugins which live in nx.json's plugins array. // This file represents the public API for plugins which live in nx.json's plugins array.
// For methods to interact with plugins from within Nx, see `./internal-api.ts`. // For methods to interact with plugins from within Nx, see `./internal-api.ts`.
import { NxPluginV1 } from '../../utils/nx-plugin.deprecated';
import { import {
FileMap, FileMap,
ProjectGraph, ProjectGraph,
@ -66,12 +65,12 @@ export interface CreateNodesResult {
* A pair of file patterns and {@link CreateNodesFunction} * A pair of file patterns and {@link CreateNodesFunction}
* *
* Nx 19.2+: Both original `CreateNodes` and `CreateNodesV2` are supported. Nx will only invoke `CreateNodesV2` if it is present. * Nx 19.2+: Both original `CreateNodes` and `CreateNodesV2` are supported. Nx will only invoke `CreateNodesV2` if it is present.
* Nx 20.X : The `CreateNodesV2` will be the only supported API. This typing will still exist, but be identical to `CreateNodesV2`. * Nx 21.X : The `CreateNodesV2` will be the only supported API. This typing will still exist, but be identical to `CreateNodesV2`.
Nx **will not** invoke the original `plugin.createNodes` callback. This should give plugin authors a window to transition. Nx **will not** invoke the original `plugin.createNodes` callback. This should give plugin authors a window to transition.
Plugin authors should update their plugin's `createNodes` function to align with `CreateNodesV2` / the updated `CreateNodes`. Plugin authors should update their plugin's `createNodes` function to align with `CreateNodesV2` / the updated `CreateNodes`.
The plugin should contain something like: `export createNodes = createNodesV2;` during this period. This will allow the plugin The plugin should contain something like: `export createNodes = createNodesV2;` during this period. This will allow the plugin
to maintain compatibility with Nx 19.2 and up. to maintain compatibility with Nx 19.2 and up.
* Nx 21.X : The `CreateNodesV2` typing will be removed, as it has replaced `CreateNodes`. * Nx 22.X : The `CreateNodesV2` typing will be removed, as it has replaced `CreateNodes`.
* *
* @deprecated Use {@link CreateNodesV2} instead. CreateNodesV2 will replace this API. Read more about the transition above. * @deprecated Use {@link CreateNodesV2} instead. CreateNodesV2 will replace this API. Read more about the transition above.
*/ */
@ -82,7 +81,7 @@ export type CreateNodes<T = unknown> = readonly [
/** /**
* A pair of file patterns and {@link CreateNodesFunctionV2} * A pair of file patterns and {@link CreateNodesFunctionV2}
* In Nx 20 {@link CreateNodes} will be replaced with this type. In Nx 21, this type will be removed. * In Nx 21 {@link CreateNodes} will be replaced with this type. In Nx 22, this type will be removed.
*/ */
export type CreateNodesV2<T = unknown> = readonly [ export type CreateNodesV2<T = unknown> = readonly [
projectFilePattern: string, projectFilePattern: string,
@ -156,7 +155,7 @@ export type NxPluginV2<TOptions = unknown> = {
* Provides a file pattern and function that retrieves configuration info from * Provides a file pattern and function that retrieves configuration info from
* those files. e.g. { '**\/*.csproj': buildProjectsFromCsProjFile } * those files. e.g. { '**\/*.csproj': buildProjectsFromCsProjFile }
* *
* @deprecated Use {@link createNodesV2} instead. In Nx 20 support for calling createNodes with a single file for the first argument will be removed. * @deprecated Use {@link createNodesV2} instead. In Nx 21 support for calling createNodes with a single file for the first argument will be removed.
*/ */
createNodes?: CreateNodes<TOptions>; createNodes?: CreateNodes<TOptions>;
@ -164,7 +163,7 @@ export type NxPluginV2<TOptions = unknown> = {
* Provides a file pattern and function that retrieves configuration info from * Provides a file pattern and function that retrieves configuration info from
* those files. e.g. { '**\/*.csproj': buildProjectsFromCsProjFiles } * those files. e.g. { '**\/*.csproj': buildProjectsFromCsProjFiles }
* *
* In Nx 20 {@link createNodes} will be replaced with this property. In Nx 21, this property will be removed. * In Nx 21 {@link createNodes} will be replaced with this property. In Nx 22, this property will be removed.
*/ */
createNodesV2?: CreateNodesV2<TOptions>; createNodesV2?: CreateNodesV2<TOptions>;
@ -182,4 +181,4 @@ export type NxPluginV2<TOptions = unknown> = {
/** /**
* A plugin for Nx * A plugin for Nx
*/ */
export type NxPlugin = NxPluginV1 | NxPluginV2; export type NxPlugin = NxPluginV2;

View File

@ -1,62 +1,9 @@
import { dirname } from 'node:path';
import { toProjectName } from '../../config/to-project-name';
import { combineGlobPatterns } from '../../utils/globs';
import type { NxPluginV1 } from '../../utils/nx-plugin.deprecated';
import type { LoadedNxPlugin, NormalizedPlugin } from './internal-api';
import { import {
CreateNodesContextV2, CreateNodesContextV2,
CreateNodesFunction, CreateNodesFunction,
CreateNodesFunctionV2,
CreateNodesResult, CreateNodesResult,
type NxPlugin,
type NxPluginV2,
} from './public-api'; } from './public-api';
import { AggregateCreateNodesError } from '../error-types'; import { AggregateCreateNodesError } from '../error-types';
export function isNxPluginV2(plugin: NxPlugin): plugin is NxPluginV2 {
return 'createNodes' in plugin || 'createDependencies' in plugin;
}
export function isNxPluginV1(
plugin: NxPlugin | LoadedNxPlugin
): plugin is NxPluginV1 {
return 'processProjectGraph' in plugin || 'projectFilePatterns' in plugin;
}
export function normalizeNxPlugin(plugin: NxPlugin): NormalizedPlugin {
if (isNxPluginV2(plugin)) {
return plugin;
}
if (isNxPluginV1(plugin) && plugin.projectFilePatterns) {
return {
...plugin,
createNodes: [
`*/**/${combineGlobPatterns(plugin.projectFilePatterns)}`,
(configFilePath) => {
const root = dirname(configFilePath);
return {
projects: {
[root]: {
name: toProjectName(configFilePath),
targets: plugin.registerProjectTargets?.(configFilePath),
},
},
};
},
],
};
}
return plugin;
}
export type AsyncFn<T extends Function> = T extends (
...args: infer A
) => infer R
? (...args: A) => Promise<Awaited<R>>
: never;
export async function createNodesFromFiles<T = unknown>( export async function createNodesFromFiles<T = unknown>(
createNodes: CreateNodesFunction<T>, createNodes: CreateNodesFunction<T>,
configFiles: readonly string[], configFiles: readonly string[],

View File

@ -51,7 +51,6 @@ async function runTasks(
cwd: process.cwd(), cwd: process.cwd(),
projectsConfigurations, projectsConfigurations,
nxJsonConfiguration, nxJsonConfiguration,
workspace: { ...projectsConfigurations, ...nxJsonConfiguration },
isVerbose: false, isVerbose: false,
projectGraph, projectGraph,
taskGraph: fullTaskGraph, taskGraph: fullTaskGraph,

View File

@ -1,4 +1,3 @@
import { workspaceConfigurationCheck } from '../utils/workspace-configuration-check';
import { readNxJson } from '../config/configuration'; import { readNxJson } from '../config/configuration';
import { NxArgs } from '../utils/command-line-utils'; import { NxArgs } from '../utils/command-line-utils';
import { createProjectGraphAsync } from '../project-graph/project-graph'; import { createProjectGraphAsync } from '../project-graph/project-graph';
@ -13,7 +12,6 @@ import { TaskResult } from './life-cycle';
export async function initTasksRunner(nxArgs: NxArgs) { export async function initTasksRunner(nxArgs: NxArgs) {
performance.mark('init-local'); performance.mark('init-local');
loadRootEnvFiles(); loadRootEnvFiles();
workspaceConfigurationCheck();
const nxJson = readNxJson(); const nxJson = readNxJson();
if (nxArgs.verbose) { if (nxArgs.verbose) {
process.env.NX_VERBOSE_LOGGING = 'true'; process.env.NX_VERBOSE_LOGGING = 'true';

View File

@ -1,10 +0,0 @@
// TODO(v16): Remove this file
import { workspaceRoot } from './workspace-root';
/**
* The root of the workspace.
*
* @deprecated use workspaceRoot instead
*/
export const appRootPath = workspaceRoot;
export { workspaceRoot };

View File

@ -257,43 +257,6 @@ describe('splitArgs', () => {
}); });
describe('--runner environment handling', () => { describe('--runner environment handling', () => {
it('should set runner based on environment NX_RUNNER, if it is not provided directly on the command', () => {
withEnvironment({ NX_RUNNER: 'some-env-runner-name' }, () => {
expect(
splitArgsIntoNxArgsAndOverrides(
{
__overrides_unparsed__: ['--notNxArg', 'true', '--override'],
$0: '',
},
'run-one',
{} as any,
{
tasksRunnerOptions: {
'some-env-runner-name': { runner: '' },
},
}
).nxArgs.runner
).toEqual('some-env-runner-name');
expect(
splitArgsIntoNxArgsAndOverrides(
{
__overrides_unparsed__: ['--notNxArg', 'true', '--override'],
$0: '',
runner: 'directlyOnCommand', // higher priority than $NX_RUNNER
},
'run-one',
{} as any,
{
tasksRunnerOptions: {
'some-env-runner-name': { runner: '' },
},
}
).nxArgs.runner
).toEqual('directlyOnCommand');
});
});
it('should set runner based on environment NX_TASKS_RUNNER, if it is not provided directly on the command', () => { it('should set runner based on environment NX_TASKS_RUNNER, if it is not provided directly on the command', () => {
withEnvironment({ NX_TASKS_RUNNER: 'some-env-runner-name' }, () => { withEnvironment({ NX_TASKS_RUNNER: 'some-env-runner-name' }, () => {
expect( expect(

View File

@ -217,8 +217,7 @@ function normalizeNxArgsRunner(
options: { printWarnings: boolean } options: { printWarnings: boolean }
) { ) {
if (!nxArgs.runner) { if (!nxArgs.runner) {
// TODO: Remove NX_RUNNER environment variable support in Nx v17 const envKey = 'NX_TASKS_RUNNER';
for (const envKey of ['NX_TASKS_RUNNER', 'NX_RUNNER']) {
const runner = process.env[envKey]; const runner = process.env[envKey];
if (runner) { if (runner) {
const runnerExists = nxJson.tasksRunnerOptions?.[runner]; const runnerExists = nxJson.tasksRunnerOptions?.[runner];
@ -248,17 +247,8 @@ function normalizeNxArgsRunner(
} }
} }
if (runnerExists) { if (runnerExists) {
// TODO: Remove in v17
if (envKey === 'NX_RUNNER' && options.printWarnings) {
output.warn({
title:
'NX_RUNNER is deprecated, please use NX_TASKS_RUNNER instead.',
});
}
nxArgs.runner = runner; nxArgs.runner = runner;
} }
break;
}
} }
} }
} }

View File

@ -1,52 +0,0 @@
import { shouldMergeAngularProjects } from '../adapter/angular-json';
import { ProjectGraphProcessor } from '../config/project-graph';
import { TargetConfiguration } from '../config/workspace-json-project-json';
import ProjectJsonProjectsPlugin from '../plugins/project-json/build-nodes/project-json';
import * as PackageJsonWorkspacesPlugin from '../plugins/package-json';
import { NxPluginV2 } from '../project-graph/plugins';
/**
* @deprecated Add targets to the projects in a {@link CreateNodes} function instead. This will be removed in Nx 20
*/
export type ProjectTargetConfigurator = (
file: string
) => Record<string, TargetConfiguration>;
/**
* @deprecated Use {@link NxPluginV2} instead. This will be removed in Nx 20
*/
export type NxPluginV1 = {
name: string;
/**
* @deprecated Use {@link CreateNodes} and {@link CreateDependencies} instead. This will be removed in Nx 20
*/
processProjectGraph?: ProjectGraphProcessor;
/**
* @deprecated Add targets to the projects inside of {@link CreateNodes} instead. This will be removed in Nx 20
*/
registerProjectTargets?: ProjectTargetConfigurator;
/**
* A glob pattern to search for non-standard project files.
* @example: ["*.csproj", "pom.xml"]
* @deprecated Use {@link CreateNodes} instead. This will be removed in Nx 20
*/
projectFilePatterns?: string[];
};
/**
* @todo(@agentender) v20: Remove this fn when we remove readWorkspaceConfig
*/
export function getDefaultPluginsSync(root: string): NxPluginV2[] {
const plugins: NxPluginV2[] = [
require('../plugins/js'),
...(shouldMergeAngularProjects(root, false)
? [require('../adapter/angular-json').NxAngularJsonPlugin]
: []),
PackageJsonWorkspacesPlugin,
ProjectJsonProjectsPlugin,
];
return plugins;
}

View File

@ -6,9 +6,10 @@ import {
import { ProjectConfiguration } from '../../config/workspace-json-project-json'; import { ProjectConfiguration } from '../../config/workspace-json-project-json';
import { readJsonFile } from '../fileutils'; import { readJsonFile } from '../fileutils';
import { getNxRequirePaths } from '../installation-directory'; import { getNxRequirePaths } from '../installation-directory';
import { NxPlugin, readPluginPackageJson } from '../../project-graph/plugins'; import { readPluginPackageJson } from '../../project-graph/plugins';
import { loadNxPlugin } from '../../project-graph/plugins/loader'; import { loadNxPlugin } from '../../project-graph/plugins/loader';
import { PackageJson } from '../package-json'; import { PackageJson } from '../package-json';
import { LoadedNxPlugin } from '../../project-graph/plugins/internal-api';
export interface PluginCapabilities { export interface PluginCapabilities {
name: string; name: string;
@ -42,8 +43,7 @@ export async function getPluginCapabilities(
includeRuntimeCapabilities = false includeRuntimeCapabilities = false
): Promise<PluginCapabilities | null> { ): Promise<PluginCapabilities | null> {
try { try {
const { json: packageJson, path: packageJsonPath } = const { json: packageJson, path: packageJsonPath } = readPluginPackageJson(
await readPluginPackageJson(
pluginName, pluginName,
projects, projects,
getNxRequirePaths(workspaceRoot) getNxRequirePaths(workspaceRoot)
@ -106,7 +106,7 @@ export async function getPluginCapabilities(
async function tryGetModule( async function tryGetModule(
packageJson: PackageJson, packageJson: PackageJson,
workspaceRoot: string workspaceRoot: string
): Promise<NxPlugin | null> { ): Promise<LoadedNxPlugin | null> {
try { try {
if ( if (
packageJson.generators ?? packageJson.generators ??
@ -116,8 +116,7 @@ async function tryGetModule(
packageJson['builders'] packageJson['builders']
) { ) {
const [pluginPromise] = loadNxPlugin(packageJson.name, workspaceRoot); const [pluginPromise] = loadNxPlugin(packageJson.name, workspaceRoot);
const plugin = await pluginPromise; return await pluginPromise;
return plugin;
} else { } else {
return { return {
name: packageJson.name, name: packageJson.name,

View File

@ -1,37 +0,0 @@
import { workspaceRoot } from './workspace-root';
import { existsSync } from 'fs';
import { join } from 'path';
import { output } from './output';
import { readJsonFile } from '../utils/fileutils';
//TODO: vsavkin remove after Nx 19
export function workspaceConfigurationCheck() {
if (existsSync(join(workspaceRoot, 'workspace.json'))) {
output.warn({
title: 'workspace.json is ignored',
bodyLines: [
'Nx no longer reads configuration from workspace.json.',
'Run "nx g @nx/workspace:fix-configuration" to split workspace.json into individual project.json files.',
],
});
return;
}
if (existsSync(join(workspaceRoot, 'angular.json'))) {
const angularJson = readJsonFile(join(workspaceRoot, 'angular.json'));
const v2Props = Object.values(angularJson.projects).find(
(p: any) => !!p.targets
);
if (angularJson.version === 2 || v2Props) {
output.error({
title: 'angular.json format is incorrect',
bodyLines: [
'Nx no longer supports the v2 format of angular.json.',
'Run "nx g @nx/workspace:fix-configuration" to split angular.json into individual project.json files. (Recommended)',
'If you want to preserve angular.json, run "nx g @nx/workspace:fix-configuration --reformat"',
],
});
process.exit(1);
}
}
}

View File

@ -8,6 +8,15 @@ const context: ExecutorContext = {
root: '', root: '',
cwd: process.cwd(), cwd: process.cwd(),
isVerbose: false, isVerbose: false,
projectGraph: {
nodes: {},
dependencies: {},
},
projectsConfigurations: {
projects: {},
version: 2,
},
nxJsonConfiguration: {},
}; };
describe('<%= className %> Executor', () => { describe('<%= className %> Executor', () => {

View File

@ -49,7 +49,8 @@ export default async function* serveExecutor(
context: ExecutorContext context: ExecutorContext
) { ) {
const options = normalizeOptions(schema); const options = normalizeOptions(schema);
const projectRoot = context.workspace.projects[context.projectName].root; const projectRoot =
context.projectsConfigurations.projects[context.projectName].root;
const remixBin = require.resolve('@remix-run/dev/dist/cli'); const remixBin = require.resolve('@remix-run/dev/dist/cli');
const args = buildRemixDevArgs(options); const args = buildRemixDevArgs(options);

View File

@ -1,6 +1,7 @@
import { workspaceRoot } from '@nx/devkit'; import { workspaceRoot } from '@nx/devkit';
import { Configuration } from '@rspack/core'; import { Configuration } from '@rspack/core';
import { isNxRspackComposablePlugin } from './config'; import { isNxRspackComposablePlugin } from './config';
import { readNxJsonFromDisk } from 'nx/src/devkit-internals';
/** /**
* Reads the Rspack options from a give Rspack configuration. The configuration can be: * Reads the Rspack options from a give Rspack configuration. The configuration can be:
@ -25,7 +26,14 @@ export async function readRspackOptions(
projectRoot: '', projectRoot: '',
sourceRoot: '', sourceRoot: '',
}, },
context: { root: workspaceRoot, cwd: undefined, isVerbose: false }, context: {
root: workspaceRoot,
cwd: undefined,
isVerbose: false,
nxJsonConfiguration: readNxJsonFromDisk(workspaceRoot),
projectGraph: null,
projectsConfigurations: null,
},
} }
); );
} else if (typeof rspackConfig === 'function') { } else if (typeof rspackConfig === 'function') {

View File

@ -1,8 +1,14 @@
import { type ExecutorContext, readCachedProjectGraph } from '@nx/devkit'; import {
type ExecutorContext,
readCachedProjectGraph,
readProjectsConfigurationFromProjectGraph,
workspaceRoot,
} from '@nx/devkit';
import type { NxWebpackExecutionContext } from '../../utils/config'; import type { NxWebpackExecutionContext } from '../../utils/config';
import type { NxAppWebpackPluginOptions } from '../nx-webpack-plugin/nx-app-webpack-plugin-options'; import type { NxAppWebpackPluginOptions } from '../nx-webpack-plugin/nx-app-webpack-plugin-options';
import type { Compiler, Configuration } from 'webpack'; import type { Compiler, Configuration } from 'webpack';
import { normalizeOptions } from '../nx-webpack-plugin/lib/normalize-options'; import { normalizeOptions } from '../nx-webpack-plugin/lib/normalize-options';
import { readNxJson } from 'nx/src/config/configuration';
/** /**
* This function is used to wrap the legacy plugin function to be used with the `composePlugins` function. * This function is used to wrap the legacy plugin function to be used with the `composePlugins` function.
@ -49,8 +55,11 @@ export async function useLegacyNxPlugin(
const context: ExecutorContext = { const context: ExecutorContext = {
cwd: process.cwd(), cwd: process.cwd(),
isVerbose: process.env.NX_VERBOSE_LOGGING === 'true', isVerbose: process.env.NX_VERBOSE_LOGGING === 'true',
root: project.data.root, root: workspaceRoot,
projectGraph: readCachedProjectGraph(), projectGraph,
projectsConfigurations:
readProjectsConfigurationFromProjectGraph(projectGraph),
nxJsonConfiguration: readNxJson(workspaceRoot),
target: project.data.targets[targetName], target: project.data.targets[targetName],
targetName: targetName, targetName: targetName,
projectName: projectName, projectName: projectName,

View File

@ -1,11 +1,13 @@
import { import {
ExecutorContext, ExecutorContext,
readCachedProjectGraph, readCachedProjectGraph,
readProjectsConfigurationFromProjectGraph,
workspaceRoot, workspaceRoot,
} from '@nx/devkit'; } from '@nx/devkit';
import { Configuration } from 'webpack'; import { Configuration } from 'webpack';
import { NormalizedWebpackExecutorOptions } from '../executors/webpack/schema'; import { NormalizedWebpackExecutorOptions } from '../executors/webpack/schema';
import { readNxJson } from 'nx/src/config/configuration';
export const nxWebpackComposablePlugin = 'nxWebpackComposablePlugin'; export const nxWebpackComposablePlugin = 'nxWebpackComposablePlugin';
@ -102,6 +104,9 @@ function ensureNxWebpackExecutionContext(ctx: NxWebpackExecutionContext): void {
projectName, projectName,
targetName, targetName,
configurationName, configurationName,
projectsConfigurations:
readProjectsConfigurationFromProjectGraph(projectGraph),
nxJsonConfiguration: readNxJson(workspaceRoot),
cwd: process.cwd(), cwd: process.cwd(),
root: workspaceRoot, root: workspaceRoot,
isVerbose: process.env['NX_VERBOSE_LOGGING'] === 'true', isVerbose: process.env['NX_VERBOSE_LOGGING'] === 'true',

View File

@ -1,6 +1,7 @@
import { workspaceRoot } from '@nx/devkit'; import { workspaceRoot } from '@nx/devkit';
import { isNxWebpackComposablePlugin } from '../config'; import { isNxWebpackComposablePlugin } from '../config';
import { Configuration } from 'webpack'; import { Configuration } from 'webpack';
import { readNxJsonFromDisk } from 'nx/src/devkit-internals';
/** /**
* Reads the webpack options from a give webpack configuration. The configuration can be: * Reads the webpack options from a give webpack configuration. The configuration can be:
@ -28,7 +29,14 @@ export async function readWebpackOptions(
outputPath: undefined, outputPath: undefined,
assets: undefined, assets: undefined,
}, },
context: { root: workspaceRoot, cwd: undefined, isVerbose: false }, context: {
root: workspaceRoot,
cwd: undefined,
isVerbose: false,
projectsConfigurations: null,
projectGraph: null,
nxJsonConfiguration: readNxJsonFromDisk(workspaceRoot),
},
} }
); );
} else if (typeof webpackConfig === 'function') { } else if (typeof webpackConfig === 'function') {

509
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff