feat(core): extract js related code from affected and hasher (#16244)

This commit is contained in:
Miroslav Jonaš 2023-04-18 16:42:05 +02:00 committed by GitHub
parent 0d7dbbc525
commit 2dd59c3b57
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
77 changed files with 397 additions and 329 deletions

View File

@ -101,8 +101,6 @@ It only uses language primitives and immutable objects
- [applySharedFunction](../../devkit/documents/nrwl_devkit#applysharedfunction)
- [convertNxExecutor](../../devkit/documents/nrwl_devkit#convertnxexecutor)
- [convertNxGenerator](../../devkit/documents/nrwl_devkit#convertnxgenerator)
- [createLockFile](../../devkit/documents/nrwl_devkit#createlockfile)
- [createPackageJson](../../devkit/documents/nrwl_devkit#createpackagejson)
- [createProjectGraphAsync](../../devkit/documents/nrwl_devkit#createprojectgraphasync)
- [defaultTasksRunner](../../devkit/documents/nrwl_devkit#defaulttasksrunner)
- [detectPackageManager](../../devkit/documents/nrwl_devkit#detectpackagemanager)
@ -1054,53 +1052,6 @@ Convert an Nx Generator into an Angular Devkit Schematic.
---
### createLockFile
**createLockFile**(`packageJson`, `packageManager?`): `string`
**`Deprecated`**
Import this from @nrwl/js instead
#### Parameters
| Name | Type |
| :--------------- | :-------------------------------------------------------------------- |
| `packageJson` | `PackageJson` |
| `packageManager` | [`PackageManager`](../../devkit/documents/nrwl_devkit#packagemanager) |
#### Returns
`string`
---
### createPackageJson
**createPackageJson**(`projectName`, `graph`, `options?`): `PackageJson`
**`Deprecated`**
Import this from @nrwl/js instead
#### Parameters
| Name | Type |
| :---------------------------- | :---------------------------------------------------------------- |
| `projectName` | `string` |
| `graph` | [`ProjectGraph`](../../devkit/documents/nrwl_devkit#projectgraph) |
| `options` | `Object` |
| `options.helperDependencies?` | `string`[] |
| `options.isProduction?` | `boolean` |
| `options.root?` | `string` |
| `options.target?` | `string` |
#### Returns
`PackageJson`
---
### createProjectGraphAsync
**createProjectGraphAsync**(`opts?`): `Promise`<[`ProjectGraph`](../../devkit/documents/nrwl_devkit#projectgraph)\>

View File

@ -101,8 +101,6 @@ It only uses language primitives and immutable objects
- [applySharedFunction](../../devkit/documents/nrwl_devkit#applysharedfunction)
- [convertNxExecutor](../../devkit/documents/nrwl_devkit#convertnxexecutor)
- [convertNxGenerator](../../devkit/documents/nrwl_devkit#convertnxgenerator)
- [createLockFile](../../devkit/documents/nrwl_devkit#createlockfile)
- [createPackageJson](../../devkit/documents/nrwl_devkit#createpackagejson)
- [createProjectGraphAsync](../../devkit/documents/nrwl_devkit#createprojectgraphasync)
- [defaultTasksRunner](../../devkit/documents/nrwl_devkit#defaulttasksrunner)
- [detectPackageManager](../../devkit/documents/nrwl_devkit#detectpackagemanager)
@ -1054,53 +1052,6 @@ Convert an Nx Generator into an Angular Devkit Schematic.
---
### createLockFile
**createLockFile**(`packageJson`, `packageManager?`): `string`
**`Deprecated`**
Import this from @nrwl/js instead
#### Parameters
| Name | Type |
| :--------------- | :-------------------------------------------------------------------- |
| `packageJson` | `PackageJson` |
| `packageManager` | [`PackageManager`](../../devkit/documents/nrwl_devkit#packagemanager) |
#### Returns
`string`
---
### createPackageJson
**createPackageJson**(`projectName`, `graph`, `options?`): `PackageJson`
**`Deprecated`**
Import this from @nrwl/js instead
#### Parameters
| Name | Type |
| :---------------------------- | :---------------------------------------------------------------- |
| `projectName` | `string` |
| `graph` | [`ProjectGraph`](../../devkit/documents/nrwl_devkit#projectgraph) |
| `options` | `Object` |
| `options.helperDependencies?` | `string`[] |
| `options.isProduction?` | `boolean` |
| `options.root?` | `string` |
| `options.target?` | `string` |
#### Returns
`PackageJson`
---
### createProjectGraphAsync
**createProjectGraphAsync**(`opts?`): `Promise`<[`ProjectGraph`](../../devkit/documents/nrwl_devkit#projectgraph)\>

View File

@ -135,7 +135,7 @@ In order to use Jest's global setup/teardown functions that reference nx librari
Nx provides a helper function that you can import within your setup/teardown file.
```typescript {% fileName="global-setup.ts" %}
import { registerTsProject } from 'nx/src/utils/register';
import { registerTsProject } from '@nrwl/js/src/internal';
const cleanupRegisteredPaths = registerTsProject('.', 'tsconfig.base.json');
import { yourFancyFunction } from '@some-org/my-util-library';

View File

@ -135,7 +135,7 @@ In order to use Jest's global setup/teardown functions that reference nx librari
Nx provides a helper function that you can import within your setup/teardown file.
```typescript {% fileName="global-setup.ts" %}
import { registerTsProject } from 'nx/src/utils/register';
import { registerTsProject } from '@nrwl/js/src/internal';
const cleanupRegisteredPaths = registerTsProject('.', 'tsconfig.base.json');
import { yourFancyFunction } from '@some-org/my-util-library';

View File

@ -48,7 +48,7 @@ describe('Jest', () => {
updateFile(
`libs/${mylib}/setup.ts`,
stripIndents`
const { registerTsProject } = require('nx/src/utils/register');
const { registerTsProject } = require('@nx/js/src/internal');
const cleanup = registerTsProject('.', 'tsconfig.base.json');
import {setup} from '@global-fun/globals';
@ -61,7 +61,7 @@ describe('Jest', () => {
updateFile(
`libs/${mylib}/teardown.ts`,
stripIndents`
import { registerTsProject } from 'nx/src/utils/register';
const { registerTsProject } = require('@nx/js/src/internal');
const cleanup = registerTsProject('.', 'tsconfig.base.json');
import {teardown} from '@global-fun/globals';
@ -73,15 +73,14 @@ describe('Jest', () => {
updateFile(
`libs/${mylib}/jest.config.ts`,
stripIndents`
module.exports = {
testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
export default {
displayName: "${mylib}",
preset: "../../jest.preset.js",
transform: {
'^.+\\.(ts|js|html)$': 'ts-jest'
"^.+\\.[tj]s$": ["ts-jest", { tsconfig: "<rootDir>/tsconfig.spec.json" }],
},
resolver: '@nrwl/jest/plugins/resolver',
moduleFileExtensions: ['ts', 'js', 'html'],
coverageReporters: ['html'],
passWithNoTests: true,
moduleFileExtensions: ["ts", "js", "html"],
coverageDirectory: "../../coverage/libs/${mylib}",
globals: { testGlobal: ${testGlobal} },
globalSetup: '<rootDir>/setup.ts',
globalTeardown: '<rootDir>/teardown.ts'

View File

@ -14,7 +14,6 @@ import {
packageManagerLockFile,
promisifiedTreeKill,
readFile,
readJson,
runCLI,
runCLIAsync,
runCommand,
@ -26,7 +25,7 @@ import {
} from '@nrwl/e2e/utils';
import { exec, execSync } from 'child_process';
import * as http from 'http';
import { getLockFileName } from 'nx/src/plugins/js/lock-file/lock-file';
import { getLockFileName } from '@nx/js';
import { satisfies } from 'semver';
function getData(port, path = '/api'): Promise<any> {

View File

@ -17,7 +17,7 @@ import type { Schema } from './schema';
import { createTmpTsConfigForBuildableLibs } from '../utilities/buildable-libs';
import { from } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { getRootTsConfigPath } from 'nx/src/utils/typescript';
import { getRootTsConfigPath } from '@nx/js';
type BuildTargetOptions = {
tsConfig: string;

View File

@ -1,6 +1,6 @@
import type { Tree } from '@nx/devkit';
import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import type { PropertyAssignment } from 'typescript';
import {

View File

@ -5,7 +5,7 @@ import {
stripIndents,
visitNotIgnoredFiles,
} from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import { extname } from 'path';
import type {
ClassDeclaration,

View File

@ -1,6 +1,5 @@
import type { Tree } from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript';
import { getSourceNodes } from '@nx/js';
import { findNodes, getSourceNodes } from '@nx/js';
import type { PropertyDeclaration } from 'typescript';
import { getTsSourceFile } from '../../../utils/nx-devkit/ast-utils';
import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript';

View File

@ -1,5 +1,5 @@
import type * as ts from 'typescript';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import {
getImport,
getSourceNodes,

View File

@ -1,6 +1,5 @@
import type { Tree } from 'nx/src/generators/tree';
// eslint-disable-next-line @typescript-eslint/no-restricted-imports
import { typescriptVersion } from 'nx/src/utils/versions';
import { typescriptVersion } from '../utils/versions';
import { ensurePackage } from '../utils/package-json';
/**

View File

@ -12,7 +12,7 @@ import {
collectWorkspaceLibrarySecondaryEntryPoints,
} from './secondary-entry-points';
// eslint-disable-next-line @typescript-eslint/no-restricted-imports
import { getRootTsConfigPath } from 'nx/src/utils/typescript';
import { getRootTsConfigPath } from 'nx/src/plugins/js/utils/typescript';
import type { ProjectGraph } from 'nx/src/config/project-graph';
import { requireNx } from '../../../nx';

View File

@ -1,7 +1,7 @@
import { existsSync } from 'fs';
import { ParsedCommandLine } from 'typescript';
// eslint-disable-next-line @typescript-eslint/no-restricted-imports
import { getRootTsConfigPath } from 'nx/src/utils/typescript';
import { getRootTsConfigPath } from 'nx/src/plugins/js/utils/typescript';
import { dirname } from 'path';
let tsConfig: ParsedCommandLine;

View File

@ -0,0 +1 @@
export const typescriptVersion = '~4.9.5';

View File

@ -33,11 +33,12 @@
}
},
"dependencies": {
"@nx/devkit": "file:../devkit",
"@nx/js": "file:../js",
"@typescript-eslint/utils": "^5.58.0",
"chalk": "^4.1.0",
"confusing-browser-globals": "^1.0.9",
"semver": "7.3.4",
"@nx/devkit": "file:../devkit"
"semver": "7.3.4"
},
"publishConfig": {
"access": "public"

View File

@ -1,6 +1,6 @@
import type { TSESLint } from '@typescript-eslint/utils';
import { existsSync } from 'fs';
import { registerTsProject } from 'nx/src/utils/register';
import { registerTsProject } from '@nx/js/src/internal';
import { WORKSPACE_PLUGIN_DIR, WORKSPACE_RULE_NAMESPACE } from './constants';
type ESLintRules = Record<string, TSESLint.RuleModule<string, unknown[]>>;

View File

@ -33,7 +33,7 @@ import {
isComboDepConstraint,
} from '../utils/runtime-lint-utils';
import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
import { TargetProjectLocator } from 'nx/src/plugins/js/project-graph/build-dependencies/target-project-locator';
import { TargetProjectLocator } from '@nx/js/src/internal';
import { basename, dirname, relative } from 'path';
import {
getBarrelEntryPointByImportScope,

View File

@ -8,7 +8,7 @@ import {
} from '@nx/devkit';
import { findProject, getSourceFilePath } from '../utils/runtime-lint-utils';
import { existsSync } from 'fs';
import { registerTsProject } from 'nx/src/utils/register';
import { registerTsProject } from '@nx/js/src/internal';
import * as path from 'path';
import { createESLintRule } from '../utils/create-eslint-rule';

View File

@ -3,7 +3,7 @@ import {
ProjectGraphProjectNode,
readJsonFile,
} from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from 'nx/src/plugins/js/utils/typescript';
import { existsSync, readFileSync } from 'fs';
import { dirname } from 'path';
import ts = require('typescript');

View File

@ -13,15 +13,15 @@ import {
} from '@nx/devkit';
import { getPath, pathExists } from './graph-utils';
import { readFileIfExisting } from 'nx/src/utils/fileutils';
import { TargetProjectLocator } from 'nx/src/plugins/js/project-graph/build-dependencies/target-project-locator';
import {
findProjectForPath,
ProjectRootMappings,
} from 'nx/src/project-graph/utils/find-project-for-path';
import { getRootTsConfigFileName } from '@nx/js';
import {
getRootTsConfigFileName,
resolveModuleByImport,
} from 'nx/src/utils/typescript';
TargetProjectLocator,
} from '@nx/js/src/internal';
export type Deps = { [projectName: string]: ProjectGraphDependency[] };
type SingleSourceTagConstraint = {

View File

@ -1,4 +1,4 @@
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import * as ts from 'typescript';
import { ChangeType, StringChange } from '@nx/devkit';

View File

@ -11,5 +11,13 @@ export * from './utils/assets';
export * from './utils/package-json/update-package-json';
export { libraryGenerator } from './generators/library/library';
export { initGenerator } from './generators/init/init';
export { createLockFile } from 'nx/src/plugins/js/lock-file/lock-file';
export {
createLockFile,
getLockFileName,
} from 'nx/src/plugins/js/lock-file/lock-file';
export { createPackageJson } from 'nx/src/plugins/js/package-json/create-package-json';
export {
findNodes,
getRootTsConfigPath,
} from 'nx/src/plugins/js/utils/typescript';

View File

@ -0,0 +1,6 @@
export { resolveModuleByImport } from 'nx/src/plugins/js/utils/typescript';
export {
registerTsProject,
registerTsConfigPaths,
} from 'nx/src/plugins/js/utils/register';
export { TargetProjectLocator } from 'nx/src/plugins/js/project-graph/build-dependencies/target-project-locator';

View File

@ -1,5 +1,10 @@
import { addDependenciesToPackageJson, Tree } from '@nx/devkit';
import { swcCliVersion, swcCoreVersion, swcHelpersVersion } from '../versions';
import {
swcCliVersion,
swcCoreVersion,
swcHelpersVersion,
swcNodeVersion,
} from '../versions';
export function addSwcDependencies(tree: Tree) {
return addDependenciesToPackageJson(
@ -13,3 +18,11 @@ export function addSwcDependencies(tree: Tree) {
}
);
}
export function addSwcRegisterDependencies(tree: Tree) {
return addDependenciesToPackageJson(
tree,
{},
{ '@swc-node/register': swcNodeVersion, '@swc/core': swcCoreVersion }
);
}

View File

@ -0,0 +1,12 @@
import { addDependenciesToPackageJson, Tree } from '@nx/devkit';
import { tsLibVersion } from '../versions';
export function addTsLibDependencies(tree: Tree) {
addDependenciesToPackageJson(
tree,
{
tslib: tsLibVersion,
},
{}
);
}

View File

@ -2,7 +2,7 @@ import type { Tree } from '@nx/devkit';
import type * as ts from 'typescript';
// TODO(colum): replace when https://github.com/nrwl/nx/pull/15497 is merged
import { getSourceNodes } from '@nx/workspace/src/utilities/typescript';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from 'nx/src/plugins/js/utils/typescript';
import { ensureTypescript } from './ensure-typescript';
let tsModule: typeof import('typescript');

View File

@ -42,9 +42,13 @@ export function getRelativePathToRootTsConfig(
return offsetFromRoot(targetPath) + getRootTsConfigPathInTree(tree);
}
export function getRootTsConfigFileName(tree: Tree): string | null {
export function getRootTsConfigFileName(tree?: Tree): string | null {
for (const tsConfigName of ['tsconfig.base.json', 'tsconfig.json']) {
if (tree.exists(tsConfigName)) {
const pathExists = tree
? tree.exists(tsConfigName)
: existsSync(join(workspaceRoot, tsConfigName));
if (pathExists) {
return tsConfigName;
}
}

View File

@ -1,10 +1,11 @@
export { swcCoreVersion } from 'nx/src/utils/versions';
export const nxVersion = require('../../package.json').version;
export const esbuildVersion = '^0.17.5';
export const prettierVersion = '^2.6.2';
export const swcCliVersion = '~0.1.55';
export const swcCoreVersion = '^1.2.173';
export const swcNodeVersion = '^1.4.2';
export const swcHelpersVersion = '~0.4.11';
export const tsLibVersion = '^2.3.0';
export const typesNodeVersion = '18.7.1';
export const typescriptVersion = '~4.9.5';

View File

@ -1,5 +1,4 @@
import {
addDependenciesToPackageJson,
addProjectConfiguration,
convertNxGenerator,
ensurePackage,
@ -14,10 +13,10 @@ import {
updateNxJson,
} from '@nx/devkit';
import { getRelativePathToRootTsConfig } from '@nx/js';
import { addSwcRegisterDependencies } from '@nx/js/src/utils/swc/add-swc-dependencies';
import { join } from 'path';
import { workspaceLintPluginDir } from '../../utils/workspace-lint-rules';
import { swcCoreVersion, swcNodeVersion } from 'nx/src/utils/versions';
import { nxVersion } from '../../utils/versions';
import { workspaceLintPluginDir } from '../../utils/workspace-lint-rules';
export const WORKSPACE_RULES_PROJECT_NAME = 'eslint-rules';
@ -105,11 +104,7 @@ export async function lintWorkspaceRulesProjectGenerator(
);
// Add swc dependencies
addDependenciesToPackageJson(
tree,
{},
{ '@swc-node/register': swcNodeVersion, '@swc/core': swcCoreVersion }
);
addSwcRegisterDependencies(tree);
// Add extra config to the jest.config.ts file to allow ESLint 8 exports mapping to work with jest
addPropertyToJestConfig(

View File

@ -1,15 +1,11 @@
import { addDependenciesToPackageJson, formatFiles, Tree } from '@nx/devkit';
import { swcCoreVersion, swcNodeVersion } from 'nx/src/utils/versions';
import { formatFiles, Tree } from '@nx/devkit';
import { addSwcRegisterDependencies } from '@nx/js/src/utils/swc/add-swc-dependencies';
import { WORKSPACE_PLUGIN_DIR } from '../../generators/workspace-rules-project/workspace-rules-project';
export default async function addSwcNodeIfNeeded(tree: Tree) {
try {
if (tree.exists(WORKSPACE_PLUGIN_DIR)) {
addDependenciesToPackageJson(
tree,
{},
{ '@swc-node/register': swcNodeVersion, '@swc/core': swcCoreVersion }
);
addSwcRegisterDependencies(tree);
await formatFiles(tree);
return;
}

View File

@ -1,7 +1,6 @@
export const nxVersion = require('../../package.json').version;
export const tslintToEslintConfigVersion = '^2.13.0';
export const typescriptESLintVersion = '^5.58.0';
export const eslintVersion = '~8.15.0';
export const eslintConfigPrettierVersion = '8.1.0';
export const tslintToEslintConfigVersion = '^2.13.0';
export const typescriptESLintVersion = '^5.58.0';

View File

@ -5,7 +5,7 @@ import {
workspaceRoot,
writeJsonFile,
} from '@nx/devkit';
import { createLockFile, createPackageJson } from '@nx/js';
import { createLockFile, createPackageJson, getLockFileName } from '@nx/js';
import build from 'next/dist/build';
import { join, resolve } from 'path';
import { copySync, existsSync, mkdir, writeFileSync } from 'fs-extra';
@ -18,8 +18,6 @@ import { createNextConfigFile } from './lib/create-next-config-file';
import { checkPublicDirectory } from './lib/check-project';
import { NextBuildBuilderOptions } from '../../utils/types';
import { getLockFileName } from 'nx/src/plugins/js/lock-file/lock-file';
export default async function buildExecutor(
options: NextBuildBuilderOptions,
context: ExecutorContext

View File

@ -12,18 +12,19 @@ import {
import { libraryGenerator as jsLibraryGenerator } from '@nx/js';
import { addSwcDependencies } from '@nx/js/src/utils/swc/add-swc-dependencies';
import { Linter } from '@nx/linter';
import { swcNodeVersion } from 'nx/src/utils/versions';
import * as path from 'path';
import { nxVersion, tsLibVersion } from '../../utils/versions';
import { e2eProjectGenerator } from '../e2e-project/e2e';
import { executorGenerator } from '../executor/executor';
import { generatorGenerator } from '../generator/generator';
import pluginLintCheckGenerator from '../lint-checks/generator';
import { NormalizedSchema, normalizeOptions } from './utils/normalize-schema';
import { addTsLibDependencies } from '@nx/js/src/utils/typescript/add-tslib-dependencies';
import { addSwcRegisterDependencies } from '@nx/js/src/utils/swc/add-swc-dependencies';
import type { Schema } from './schema';
const nxVersion = require('../../../package.json').version;
async function addFiles(host: Tree, options: NormalizedSchema) {
host.delete(normalizePath(`${options.projectRoot}/src/lib`));
@ -102,19 +103,19 @@ export async function pluginGenerator(host: Tree, schema: Schema) {
host,
{
'@nx/devkit': nxVersion,
tslib: tsLibVersion,
},
{
'@nx/jest': nxVersion,
'@nx/js': nxVersion,
'@nx/nx-plugin': nxVersion,
'@swc-node/register': swcNodeVersion,
}
);
addTsLibDependencies(host);
// Ensures Swc Deps are installed to handle running
// local plugin generators and executors
addSwcDependencies(host);
addSwcRegisterDependencies(host);
await addFiles(host, options);
updatePluginConfig(host, options);

View File

@ -1,17 +1,8 @@
import {
addDependenciesToPackageJson,
formatFiles,
installPackagesTask,
Tree,
} from '@nx/devkit';
import { swcCoreVersion, swcNodeVersion } from 'nx/src/utils/versions';
import { formatFiles, installPackagesTask, Tree } from '@nx/devkit';
import { addSwcRegisterDependencies } from '@nx/js/src/utils/swc/add-swc-dependencies';
export default async function addSwcNodeIfNeeded(tree: Tree) {
addDependenciesToPackageJson(
tree,
{},
{ '@swc-node/register': swcNodeVersion, '@swc/core': swcCoreVersion }
);
addSwcRegisterDependencies(tree);
await formatFiles(tree);
return installPackagesTask(tree);
}

View File

@ -1,3 +1 @@
export const nxVersion = require('../../package.json').version;
export const jsoncEslintParserVersion = '^2.1.0';
export const tsLibVersion = '^2.3.0';

View File

@ -15,7 +15,7 @@ import { sortObjectByKeys } from '../utils/object-sort';
import {
getRootTsConfigFileName,
getRootTsConfigPath,
} from '../utils/typescript';
} from '../plugins/js/utils/typescript';
import { createProjectGraphAsync } from '../project-graph/project-graph';
import { filterAffected } from '../project-graph/affected/affected-project-graph';
import { readNxJson } from '../config/configuration';

View File

@ -225,18 +225,3 @@ export { Hash, Hasher } from './hasher/hasher';
* @category Utils
*/
export { cacheDir } from './utils/cache-directory';
import { createLockFile as _createLockFile } from './plugins/js/lock-file/lock-file';
import { createPackageJson as _createPackageJson } from './plugins/js/package-json/create-package-json';
/**
* @category Package Manager
*/
/**
* @deprecated Import this from @nrwl/js instead
*/
export const createLockFile = _createLockFile;
/**
* @deprecated Import this from @nrwl/js instead
*/
export const createPackageJson = _createPackageJson;

View File

@ -1,17 +1,20 @@
// This must come before the Hasher import
import { DependencyType } from '../config/project-graph';
jest.doMock('../utils/workspace-root', () => {
jest.mock('../utils/workspace-root', () => {
return {
workspaceRoot: '/root',
};
});
jest.mock('fs', () => require('memfs').fs);
jest.mock('../utils/typescript');
jest.mock('../plugins/js/utils/typescript', () => ({
getRootTsConfigFileName: jest
.fn()
.mockImplementation(() => '/root/tsconfig.base.json'),
}));
import { vol } from 'memfs';
import tsUtils = require('../utils/typescript');
import {
expandNamedInput,
filterUsingGlobPatterns,
@ -59,7 +62,6 @@ describe('Hasher', () => {
},
'/root'
);
tsUtils.getRootTsConfigFileName = () => '/root/tsconfig.base.json';
});
afterEach(() => {

View File

@ -1,6 +1,5 @@
import { exec } from 'child_process';
import * as minimatch from 'minimatch';
import { getRootTsConfigFileName } from '../utils/typescript';
import { defaultHashing, HashingImpl } from './hashing-impl';
import {
FileData,
@ -10,9 +9,8 @@ import {
} from '../config/project-graph';
import { NxJsonConfiguration } from '../config/nx-json';
import { Task } from '../config/task-graph';
import { readJsonFile } from '../utils/fileutils';
import { InputDefinition } from '../config/workspace-json-project-json';
import { getImportPath } from '../utils/path';
import { hashTsConfig } from '../plugins/js/hasher/hasher';
type ExpandedSelfInput =
| { fileset: string }
@ -42,14 +40,6 @@ export interface Hash {
};
}
interface CompilerOptions {
paths: Record<string, string[]>;
}
interface TsconfigJsonConfiguration {
compilerOptions: CompilerOptions;
}
/**
* The default hasher used by executors.
*/
@ -94,7 +84,6 @@ export class Hasher {
legacyRuntimeInputs,
legacyFilesetInputs,
this.projectGraph,
this.readTsConfig(),
this.hashing,
{ selectivelyHashTsConfig: this.options.selectivelyHashTsConfig ?? false }
);
@ -171,18 +160,6 @@ export class Hasher {
hashFile(path: string): string {
return this.hashing.hashFile(path);
}
private readTsConfig() {
try {
const res = readJsonFile(getRootTsConfigFileName());
res.compilerOptions.paths ??= {};
return res;
} catch {
return {
compilerOptions: { paths: {} },
};
}
}
}
const DEFAULT_INPUTS: ReadonlyArray<InputDefinition> = [
@ -209,7 +186,6 @@ class TaskHasher {
private readonly legacyRuntimeInputs: { runtime: string }[],
private readonly legacyFilesetInputs: { fileset: string }[],
private readonly projectGraph: ProjectGraph,
private readonly tsConfigJson: TsconfigJsonConfiguration,
private readonly hashing: HashingImpl,
private readonly options: { selectivelyHashTsConfig: boolean }
) {}
@ -490,13 +466,11 @@ class TaskHasher {
const fileNames = filteredFiles.map((f) => f.file);
const values = filteredFiles.map((f) => f.hash);
let tsConfig: string;
tsConfig = this.hashTsConfig(p);
const value = this.hashing.hashArray([
...fileNames,
...values,
JSON.stringify({ ...p.data, files: undefined }),
tsConfig,
hashTsConfig(p, this.nxJson, this.options),
]);
res({
value,
@ -536,30 +510,6 @@ class TaskHasher {
value,
};
}
private hashTsConfig(p: ProjectGraphProjectNode) {
if (this.options.selectivelyHashTsConfig) {
return this.removeOtherProjectsPathRecords(p);
} else {
return JSON.stringify(this.tsConfigJson);
}
}
private removeOtherProjectsPathRecords(p: ProjectGraphProjectNode) {
const { paths, ...compilerOptions } = this.tsConfigJson.compilerOptions;
const rootPath = p.data.root.split('/');
rootPath.shift();
const pathAlias = getImportPath(this.nxJson?.npmScope, rootPath.join('/'));
return JSON.stringify({
compilerOptions: {
...compilerOptions,
paths: {
[pathAlias]: paths[pathAlias] ?? [],
},
},
});
}
}
export function getNamedInputs(

View File

@ -0,0 +1,62 @@
import { getImportPath } from '../../../utils/path';
import { ProjectGraphProjectNode } from '../../../config/project-graph';
import { readJsonFile } from '../../../utils/fileutils';
import { getRootTsConfigFileName } from '../utils/typescript';
import { NxJsonConfiguration } from '../../../config/nx-json';
interface CompilerOptions {
paths: Record<string, string[]>;
}
interface TsconfigJsonConfiguration {
compilerOptions: CompilerOptions;
}
function readTsConfigJson(): TsconfigJsonConfiguration {
try {
const res = readJsonFile(getRootTsConfigFileName());
res.compilerOptions.paths ??= {};
return res;
} catch {
return {
compilerOptions: { paths: {} },
};
}
}
let tsConfigJson: TsconfigJsonConfiguration;
export function hashTsConfig(
p: ProjectGraphProjectNode,
nxJson: NxJsonConfiguration,
{ selectivelyHashTsConfig }: { selectivelyHashTsConfig: boolean }
) {
if (!tsConfigJson) {
tsConfigJson = readTsConfigJson();
}
if (selectivelyHashTsConfig) {
return removeOtherProjectsPathRecords(p, tsConfigJson, nxJson);
} else {
return JSON.stringify(tsConfigJson);
}
}
function removeOtherProjectsPathRecords(
p: ProjectGraphProjectNode,
tsConfigJson: TsconfigJsonConfiguration,
nxJson: NxJsonConfiguration
) {
const { paths, ...compilerOptions } = tsConfigJson.compilerOptions;
const rootPath = p.data.root.split('/');
rootPath.shift();
const pathAlias = getImportPath(nxJson?.npmScope, rootPath.join('/'));
return JSON.stringify({
compilerOptions: {
...compilerOptions,
paths: {
[pathAlias]: paths[pathAlias] ?? [],
},
},
});
}

View File

@ -16,7 +16,7 @@ import { projectGraphCacheDirectory } from '../../utils/cache-directory';
import { readFileSync, writeFileSync } from 'fs';
import { workspaceRoot } from '../../utils/workspace-root';
import { ensureDirSync } from 'fs-extra';
import { removeNpmNodes } from 'nx/src/plugins/js/lock-file/remove-npm-nodes';
import { removeNpmNodes } from './lock-file/remove-npm-nodes';
export const processProjectGraph: ProjectGraphProcessor = async (
graph,

View File

@ -0,0 +1,75 @@
import { ProjectGraph } from '../../../../config/project-graph';
import { WholeFileChange } from '../../../../project-graph/file-utils';
import { getTouchedProjectsFromLockFile } from './lock-file-changes';
describe('getTouchedProjectsFromLockFile', () => {
let graph: ProjectGraph;
let allNodes = [];
beforeEach(() => {
graph = {
nodes: {
proj1: {
name: 'proj1',
type: 'app',
data: {
root: 'libs/proj1',
files: [],
},
},
proj2: {
name: 'proj2',
type: 'lib',
data: {
root: 'packages/proj2',
files: [],
},
},
app1: {
name: 'app1',
type: 'app',
data: {
root: 'apps/app1',
files: [],
},
},
},
dependencies: {},
};
allNodes = Object.keys(graph.nodes);
});
['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'pnpm-lock.yml'].forEach(
(lockFile) => {
describe(`"${lockFile}"`, () => {
it(`should not return changes when "${lockFile}" is not touched`, () => {
const result = getTouchedProjectsFromLockFile(
[
{
file: 'source.ts',
hash: 'some-hash',
getChanges: () => [new WholeFileChange()],
},
],
graph.nodes
);
expect(result).toEqual([]);
});
it(`should return all nodes when "${lockFile}" is touched`, () => {
const result = getTouchedProjectsFromLockFile(
[
{
file: lockFile,
hash: 'some-hash',
getChanges: () => [new WholeFileChange()],
},
],
graph.nodes
);
expect(result).toEqual(allNodes);
});
});
}
);
});

View File

@ -0,0 +1,19 @@
import { TouchedProjectLocator } from '../../../../project-graph/affected/affected-project-graph-models';
import { WholeFileChange } from '../../../../project-graph/file-utils';
import { JsonChange } from '../../../../utils/json-diff';
export const getTouchedProjectsFromLockFile: TouchedProjectLocator<
WholeFileChange | JsonChange
> = (fileChanges, projectGraphNodes): string[] => {
const lockFiles = [
'package-lock.json',
'yarn.lock',
'pnpm-lock.yaml',
'pnpm-lock.yml',
];
if (fileChanges.some((f) => lockFiles.includes(f.file))) {
return Object.values(projectGraphNodes).map((p) => p.name);
}
return [];
};

View File

@ -1,8 +1,8 @@
import { NxJsonConfiguration } from '../../../config/nx-json';
import { ProjectGraph } from '../../../config/project-graph';
import { JsonDiffType } from '../../../utils/json-diff';
import { logger } from '../../../utils/logger';
import { WholeFileChange } from '../../file-utils';
import { NxJsonConfiguration } from '../../../../config/nx-json';
import { ProjectGraph } from '../../../../config/project-graph';
import { JsonDiffType } from '../../../../utils/json-diff';
import { logger } from '../../../../utils/logger';
import { WholeFileChange } from '../../../../project-graph/file-utils';
import { getTouchedNpmPackages } from './npm-packages';
describe('getTouchedNpmPackages', () => {

View File

@ -1,15 +1,18 @@
import { isWholeFileChange, WholeFileChange } from '../../file-utils';
import {
isWholeFileChange,
WholeFileChange,
} from '../../../../project-graph/file-utils';
import {
JsonDiffType,
isJsonChange,
JsonChange,
} from '../../../utils/json-diff';
import { logger } from '../../../utils/logger';
import { TouchedProjectLocator } from '../affected-project-graph-models';
} from '../../../../utils/json-diff';
import { logger } from '../../../../utils/logger';
import { TouchedProjectLocator } from '../../../../project-graph/affected/affected-project-graph-models';
import {
ProjectGraphExternalNode,
ProjectGraphProjectNode,
} from '../../../config/project-graph';
} from '../../../../config/project-graph';
export const getTouchedNpmPackages: TouchedProjectLocator<
WholeFileChange | JsonChange

View File

@ -0,0 +1,26 @@
import { TouchedProjectLocator } from '../../../../project-graph/affected/affected-project-graph-models';
import { getTouchedProjectsFromLockFile } from './lock-file-changes';
import { getTouchedNpmPackages } from './npm-packages';
import { getTouchedProjectsFromTsConfig } from './tsconfig-json-changes';
export const getTouchedProjects: TouchedProjectLocator = (
touchedFiles,
nodes,
nxJson,
packageJson,
graph
): string[] => {
const touchedProjects = new Set<string>();
[
getTouchedProjectsFromLockFile,
getTouchedNpmPackages,
getTouchedProjectsFromTsConfig,
].forEach((fn) => {
(fn(touchedFiles, nodes, nxJson, packageJson, graph) as string[]).forEach(
(p) => touchedProjects.add(p)
);
});
return Array.from(touchedProjects);
};

View File

@ -1,8 +1,8 @@
import { WholeFileChange } from '../../file-utils';
import { jsonDiff } from '../../../utils/json-diff';
import { WholeFileChange } from '../../../../project-graph/file-utils';
import { jsonDiff } from '../../../../utils/json-diff';
import { getTouchedProjectsFromTsConfig } from './tsconfig-json-changes';
import * as tsUtils from '../../../utils/typescript';
import { DependencyType, ProjectGraph } from '../../../config/project-graph';
import * as tsUtils from '../../utils/typescript';
import { DependencyType, ProjectGraph } from '../../../../config/project-graph';
describe('getTouchedProjectsFromTsConfig', () => {
let graph: ProjectGraph;

View File

@ -1,12 +1,12 @@
import { WholeFileChange } from '../../file-utils';
import { WholeFileChange } from '../../../../project-graph/file-utils';
import {
JsonDiffType,
isJsonChange,
JsonChange,
} from '../../../utils/json-diff';
import { getRootTsConfigFileName } from '../../../utils/typescript';
import { TouchedProjectLocator } from '../affected-project-graph-models';
import { ProjectGraphProjectNode } from '../../../config/project-graph';
} from '../../../../utils/json-diff';
import { getRootTsConfigFileName } from '../../utils/typescript';
import { TouchedProjectLocator } from '../../../../project-graph/affected/affected-project-graph-models';
import { ProjectGraphProjectNode } from '../../../../config/project-graph';
export const getTouchedProjectsFromTsConfig: TouchedProjectLocator<
WholeFileChange | JsonChange

View File

@ -1,7 +1,7 @@
import {
getRootTsConfigFileName,
resolveModuleByImport,
} from '../../../../utils/typescript';
} from '../../utils/typescript';
import { isRelativePath, readJsonFile } from '../../../../utils/fileutils';
import { dirname, join, posix } from 'path';
import { workspaceRoot } from '../../../../utils/workspace-root';

View File

@ -1,6 +1,6 @@
import { dirname, join } from 'path';
import type { CompilerOptions, ModuleResolutionKind } from 'typescript';
import { logger, NX_PREFIX, stripIndent } from './logger';
import type { CompilerOptions } from 'typescript';
import { logger, NX_PREFIX, stripIndent } from '../../../utils/logger';
const swcNodeInstalled = packageIsInstalled('@swc-node/register');
const tsNodeInstalled = packageIsInstalled('ts-node/register');

View File

@ -1,4 +1,4 @@
import { workspaceRoot } from './workspace-root';
import { workspaceRoot } from '../../../utils/workspace-root';
import { existsSync } from 'fs';
import { dirname, join } from 'path';
import type * as ts from 'typescript';

View File

@ -0,0 +1 @@
export const typescriptVersion = '~4.9.5';

View File

@ -4,7 +4,6 @@ import {
ProjectGraph,
ProjectGraphProjectNode,
} from '../../config/project-graph';
import { ProjectConfiguration } from '../../config/workspace-json-project-json';
export interface AffectedProjectGraphContext {
projectGraphNodes: Record<string, ProjectGraphProjectNode>;

View File

@ -3,12 +3,11 @@ import {
getImplicitlyTouchedProjects,
getTouchedProjects,
} from './locators/workspace-projects';
import { getTouchedNpmPackages } from './locators/npm-packages';
import { getTouchedProjects as getJSTouchedProjects } from '../../plugins/js/project-graph/affected/touched-projects';
import {
AffectedProjectGraphContext,
TouchedProjectLocator,
} from './affected-project-graph-models';
import { getTouchedProjectsFromTsConfig } from './locators/tsconfig-json-changes';
import { NxJsonConfiguration } from '../../config/nx-json';
import { ProjectGraph } from '../../config/project-graph';
import { reverse } from '../operators';
@ -25,9 +24,8 @@ export async function filterAffected(
const touchedProjectLocators: TouchedProjectLocator[] = [
getTouchedProjects,
getImplicitlyTouchedProjects,
getTouchedNpmPackages,
getTouchedProjectsFromTsConfig,
getTouchedProjectsFromProjectGlobChanges,
getJSTouchedProjects,
];
const touchedProjects = [];

View File

@ -27,14 +27,7 @@ export const getImplicitlyTouchedProjects: TouchedProjectLocator = (
nxJson
): string[] => {
const implicits = {};
const globalFiles = [
...extractGlobalFilesFromInputs(nxJson),
'nx.json',
'package-lock.json',
'yarn.lock',
'pnpm-lock.yaml',
'pnpm-lock.yml',
];
const globalFiles = [...extractGlobalFilesFromInputs(nxJson), 'nx.json'];
globalFiles.forEach((file) => {
implicits[file] = '*' as any;
});

View File

@ -16,7 +16,7 @@ import { buildWorkspaceProjectNodes } from './build-nodes';
import { loadNxPlugins } from '../utils/nx-plugin';
import { defaultFileHasher } from '../hasher/file-hasher';
import { createProjectFileMap } from './file-map-utils';
import { getRootTsConfigPath } from '../utils/typescript';
import { getRootTsConfigPath } from '../plugins/js/utils/typescript';
import {
ProjectFileMap,
ProjectGraph,

View File

@ -10,7 +10,10 @@ import {
PackageJson,
readModulePackageJsonWithoutFallbacks,
} from './package-json';
import { registerTranspiler, registerTsConfigPaths } from './register';
import {
registerTranspiler,
registerTsConfigPaths,
} from '../plugins/js/utils/register';
import {
ProjectConfiguration,
ProjectsConfigurations,
@ -24,7 +27,7 @@ import {
import { normalizePath } from './path';
import { join } from 'path';
import { getNxRequirePaths } from './installation-directory';
import { readTsConfig } from './typescript';
import { readTsConfig } from '../plugins/js/utils/typescript';
import type * as ts from 'typescript';

View File

@ -1,5 +1,5 @@
import { JsxEmit, ModuleKind, ScriptTarget } from 'typescript';
import { getTsNodeCompilerOptions } from './register';
import { getTsNodeCompilerOptions } from '../plugins/js/utils/register';
describe('getTsNodeCompilerOptions', () => {
it('should replace enum value with enum key for module', () => {

View File

@ -1,10 +1 @@
export const nxVersion = require('../../package.json').version;
export const angularCliVersion = '~15.2.0';
export const typescriptVersion = '~4.9.5';
export const prettierVersion = '^2.6.2';
export const typescriptESLintVersion = '^5.58.0';
export const eslintVersion = '~8.15.0';
export const eslintConfigPrettierVersion = '8.1.0';
export const swcNodeVersion = '^1.4.2';
export const swcCoreVersion = '^1.2.173';

View File

@ -1,4 +1,4 @@
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import type * as ts from 'typescript';
import { ChangeType, StringChange } from '@nx/devkit';
import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript';

View File

@ -7,7 +7,7 @@ import {
} from '@nx/devkit';
import ts = require('typescript');
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
export async function migrateToWebPack5(tree: Tree) {
allReactProjectsWithStorybookConfiguration(tree).forEach((project) => {

View File

@ -7,7 +7,7 @@ import {
Tree,
formatFiles,
} from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import * as ts from 'typescript';
export async function update(tree: Tree) {

View File

@ -1,6 +1,7 @@
import type * as ts from 'typescript';
import { ChangeType, StringChange } from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import {
findClosestOpening,
findElements,

View File

@ -1,5 +1,5 @@
import type * as ts from 'typescript';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import { ChangeType, logger, StringChange, StringInsertion } from '@nx/devkit';
import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript';

View File

@ -1,5 +1,5 @@
import { joinPathFragments, logger } from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import 'dotenv/config';
import { existsSync, readFileSync } from 'fs';
import { join } from 'path';

View File

@ -6,7 +6,7 @@ import {
import { joinPathFragments, writeJson } from '@nx/devkit';
import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';
import { storybookVersion } from '@nx/storybook';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import * as ts from 'typescript';
import { SyntaxKind } from 'typescript';
import { nxVersion } from '../../../utils/versions';

View File

@ -9,7 +9,7 @@ import {
visitNotIgnoredFiles,
} from '@nx/devkit';
import { fileExists } from '@nx/workspace/src/utilities/fileutils';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import { join, normalize } from 'path';
import { SyntaxKind } from 'typescript';
import { getTsSourceFile } from '../../../utils/utilities';

View File

@ -2,7 +2,7 @@ import { readJson, readJsonFile, TargetConfiguration, Tree } from '@nx/devkit';
import { CompilerOptions } from 'typescript';
import { storybookVersion } from './versions';
import { statSync } from 'fs';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import ts = require('typescript');
import { gte, lt, major } from 'semver';
import { join } from 'path';

View File

@ -11,7 +11,7 @@ import { existsSync } from 'fs';
import { resolve } from 'path';
import { createAsyncIterable } from '@nx/devkit/src/utils/async-iterable';
import { registerTsConfigPaths } from 'nx/src/utils/register';
import { registerTsConfigPaths } from '@nx/js/src/internal';
export async function* viteBuildExecutor(
options: ViteBuildExecutorOptions,

View File

@ -11,7 +11,7 @@ import {
import { ViteDevServerExecutorOptions } from './schema';
import { ViteBuildExecutorOptions } from '../build/schema';
import { registerTsConfigPaths } from 'nx/src/utils/register';
import { registerTsConfigPaths } from '@nx/js/src/internal';
import { resolve } from 'path';
export async function* viteDevServerExecutor(

View File

@ -7,7 +7,7 @@ import {
} from '@nx/devkit';
import { forEachExecutorOptions } from '@nx/devkit/src/generators/executor-options-utils';
import { tsquery } from '@phenomnomnominal/tsquery';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import { normalizeViteConfigFilePathWithTree } from '../../utils/generator-utils';
import ts = require('typescript');

View File

@ -1,5 +1,5 @@
import { applyChangesToString, ChangeType, Tree } from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript';
import { findNodes } from '@nx/js';
import { TargetFlags } from './generator-utils';
import type { Node, ReturnStatement } from 'typescript';

View File

@ -3,10 +3,10 @@ import { createLockFile, createPackageJson } from '@nx/js';
import { ExecutorContext, type ProjectGraph, serializeJson } from '@nx/devkit';
import {
getHelperDependenciesFromProjectGraph,
getLockFileName,
HelperDependency,
readTsConfig,
} from '@nx/js';
import { getLockFileName } from 'nx/src/plugins/js/lock-file/lock-file';
const pluginName = 'GeneratePackageJsonPlugin';

View File

@ -13,8 +13,10 @@ import {
getImportPath,
} from '@nx/devkit';
import type * as ts from 'typescript';
import { getRootTsConfigPathInTree } from '../../../utilities/ts-config';
import { findNodes } from 'nx/src/utils/typescript';
import {
getRootTsConfigPathInTree,
findNodes,
} from '../../../utilities/ts-config';
import { NormalizedSchema } from '../schema';
import { normalizeSlashes } from './utils';
import { relative } from 'path';

View File

@ -1,6 +1,7 @@
import { offsetFromRoot, Tree, workspaceRoot } from '@nx/devkit';
import { existsSync } from 'fs';
import { dirname, join } from 'path';
import type { Node, SyntaxKind } from 'typescript';
import { ensureTypescript } from './typescript';
let tsModule: typeof import('typescript');
@ -47,3 +48,38 @@ export function getRootTsConfigFileName(): string | null {
return null;
}
export function findNodes(
node: Node,
kind: SyntaxKind | SyntaxKind[],
max = Infinity
): Node[] {
if (!node || max == 0) {
return [];
}
const arr: Node[] = [];
const hasMatch = Array.isArray(kind)
? kind.includes(node.kind)
: node.kind === kind;
if (hasMatch) {
arr.push(node);
max--;
}
if (max > 0) {
for (const child of node.getChildren()) {
findNodes(child, kind, max).forEach((node) => {
if (max > 0) {
arr.push(node);
}
max--;
});
if (max <= 0) {
break;
}
}
}
return arr;
}

View File

@ -93,9 +93,9 @@
"@nx/nx-plugin": ["packages/nx-plugin"],
"@nx/nx-plugin/*": ["packages/nx-plugin/*"],
"@nx/react": ["packages/react"],
"@nx/react/*": ["packages/react/*"],
"@nx/react-native": ["packages/react-native"],
"@nx/react-native/*": ["packages/react-native/*"],
"@nx/react/*": ["packages/react/*"],
"@nx/rollup": ["packages/rollup"],
"@nx/rollup/*": ["packages/rollup/*"],
"@nx/storybook": ["packages/storybook"],