@nx/jest 17.3.0-beta.2 → 17.3.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/jest",
3
- "version": "17.3.0-beta.2",
3
+ "version": "17.3.0-beta.4",
4
4
  "private": false,
5
5
  "description": "The Nx Plugin for Jest contains executors and generators allowing your workspace to use the powerful Jest testing capabilities.",
6
6
  "repository": {
@@ -42,11 +42,12 @@
42
42
  "jest-config": "^29.4.1",
43
43
  "jest-resolve": "^29.4.1",
44
44
  "jest-util": "^29.4.1",
45
+ "minimatch": "3.0.5",
45
46
  "resolve.exports": "1.1.0",
46
47
  "tslib": "^2.3.0",
47
- "@nx/devkit": "17.3.0-beta.2",
48
- "@nx/js": "17.3.0-beta.2",
49
- "@nrwl/jest": "17.3.0-beta.2"
48
+ "@nx/devkit": "17.3.0-beta.4",
49
+ "@nx/js": "17.3.0-beta.4",
50
+ "@nrwl/jest": "17.3.0-beta.4"
50
51
  },
51
52
  "publishConfig": {
52
53
  "access": "public"
package/plugin.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { createNodes, createDependencies, JestPluginOptions, } from './src/plugins/plugin';
package/plugin.js ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createDependencies = exports.createNodes = void 0;
4
+ var plugin_1 = require("./src/plugins/plugin");
5
+ Object.defineProperty(exports, "createNodes", { enumerable: true, get: function () { return plugin_1.createNodes; } });
6
+ Object.defineProperty(exports, "createDependencies", { enumerable: true, get: function () { return plugin_1.createDependencies; } });
@@ -4,9 +4,13 @@ exports.configurationGenerator = void 0;
4
4
  const init_1 = require("../init/init");
5
5
  const check_for_test_target_1 = require("./lib/check-for-test-target");
6
6
  const create_files_1 = require("./lib/create-files");
7
+ const create_jest_config_1 = require("./lib/create-jest-config");
8
+ const ensure_dependencies_1 = require("./lib/ensure-dependencies");
7
9
  const update_tsconfig_1 = require("./lib/update-tsconfig");
10
+ const update_vscode_recommended_extensions_1 = require("./lib/update-vscode-recommended-extensions");
8
11
  const update_workspace_1 = require("./lib/update-workspace");
9
12
  const devkit_1 = require("@nx/devkit");
13
+ const js_1 = require("@nx/js");
10
14
  const schemaDefaults = {
11
15
  setupFile: 'none',
12
16
  babelJest: false,
@@ -41,15 +45,28 @@ function normalizeOptions(tree, options) {
41
45
  }
42
46
  async function configurationGenerator(tree, schema) {
43
47
  const options = normalizeOptions(tree, schema);
44
- const installTask = await (0, init_1.default)(tree, options);
48
+ const tasks = [];
49
+ tasks.push(await (0, js_1.initGenerator)(tree, { ...schema, skipFormat: true }));
50
+ tasks.push(await (0, init_1.jestInitGenerator)(tree, options));
51
+ if (!schema.skipPackageJson) {
52
+ tasks.push((0, ensure_dependencies_1.ensureDependencies)(tree, options));
53
+ }
54
+ await (0, create_jest_config_1.createJestConfig)(tree, options);
45
55
  (0, check_for_test_target_1.checkForTestTarget)(tree, options);
46
56
  (0, create_files_1.createFiles)(tree, options);
47
57
  (0, update_tsconfig_1.updateTsConfig)(tree, options);
48
- (0, update_workspace_1.updateWorkspace)(tree, options);
58
+ (0, update_vscode_recommended_extensions_1.updateVsCodeRecommendedExtensions)(tree);
59
+ const nxJson = (0, devkit_1.readNxJson)(tree);
60
+ const hasPlugin = nxJson.plugins?.some((p) => typeof p === 'string'
61
+ ? p === '@nx/jest/plugin'
62
+ : p.plugin === '@nx/jest/plugin');
63
+ if (!hasPlugin) {
64
+ (0, update_workspace_1.updateWorkspace)(tree, options);
65
+ }
49
66
  if (!schema.skipFormat) {
50
67
  await (0, devkit_1.formatFiles)(tree);
51
68
  }
52
- return installTask;
69
+ return (0, devkit_1.runTasksInSerial)(...tasks);
53
70
  }
54
71
  exports.configurationGenerator = configurationGenerator;
55
72
  exports.default = configurationGenerator;
@@ -0,0 +1,3 @@
1
+ import { type Tree } from '@nx/devkit';
2
+ import type { NormalizedJestProjectSchema } from '../schema';
3
+ export declare function createJestConfig(tree: Tree, options: Partial<NormalizedJestProjectSchema>): Promise<void>;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createJestConfig = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const project_configuration_utils_1 = require("nx/src/project-graph/utils/project-configuration-utils");
6
+ const find_root_jest_files_1 = require("../../../utils/config/find-root-jest-files");
7
+ async function createJestConfig(tree, options) {
8
+ if (!tree.exists('jest.preset.js')) {
9
+ // preset is always js file.
10
+ tree.write(`jest.preset.js`, `
11
+ const nxPreset = require('@nx/jest/preset').default;
12
+
13
+ module.exports = { ...nxPreset }`);
14
+ }
15
+ if (options.rootProject) {
16
+ // we don't want any config to be made because the `configurationGenerator` will do it.
17
+ // will copy the template config file
18
+ return;
19
+ }
20
+ const rootJestPath = (0, find_root_jest_files_1.findRootJestConfig)(tree);
21
+ if (!rootJestPath) {
22
+ // if there's not root jest config, we will create one and return
23
+ // this can happen when:
24
+ // - root jest config was renamed => in which case there is migration needed
25
+ // - root project didn't have jest setup => again, no migration is needed
26
+ generateGlobalConfig(tree, options.js);
27
+ return;
28
+ }
29
+ if (tree.exists(rootJestPath)) {
30
+ // moving from root project config to monorepo-style config
31
+ const { nodes: projects } = await (0, devkit_1.createProjectGraphAsync)();
32
+ const projectConfigurations = Object.values(projects);
33
+ const rootProject = projectConfigurations.find((projectNode) => projectNode.data?.root === '.');
34
+ // root project might have been removed,
35
+ // if it's missing there's nothing to migrate
36
+ if (rootProject) {
37
+ const jestTarget = Object.entries(rootProject.data?.targets ?? {}).find(([_, t]) => ((t?.executor === '@nx/jest:jest' ||
38
+ t?.executor === '@nrwl/jest:jest') &&
39
+ t?.options?.jestConfig === rootJestPath) ||
40
+ (t?.executor === 'nx:run-commands' && t?.options?.command === 'jest'));
41
+ if (!jestTarget) {
42
+ return;
43
+ }
44
+ const [jestTargetName, jestTargetConfigInGraph] = jestTarget;
45
+ // if root project doesn't have jest target, there's nothing to migrate
46
+ const rootProjectConfig = (0, devkit_1.readProjectConfiguration)(tree, rootProject.name);
47
+ if (rootProjectConfig.targets['test']?.executor === 'nx:run-commands'
48
+ ? rootProjectConfig.targets['test']?.command !== 'jest'
49
+ : rootProjectConfig.targets['test']?.options?.jestConfig !==
50
+ rootJestPath) {
51
+ // Jest target has already been updated
52
+ return;
53
+ }
54
+ const jestProjectConfig = `jest.config.${rootProjectConfig.projectType === 'application' ? 'app' : 'lib'}.${options.js ? 'js' : 'ts'}`;
55
+ tree.rename(rootJestPath, jestProjectConfig);
56
+ const nxJson = (0, devkit_1.readNxJson)(tree);
57
+ const targetDefaults = (0, project_configuration_utils_1.readTargetDefaultsForTarget)(jestTargetName, nxJson.targetDefaults, jestTargetConfigInGraph.executor);
58
+ const target = (rootProjectConfig.targets[jestTargetName] ??=
59
+ jestTargetConfigInGraph.executor === 'nx:run-commands'
60
+ ? { command: `jest --config ${jestProjectConfig}` }
61
+ : {
62
+ executor: jestTargetConfigInGraph.executor,
63
+ options: {},
64
+ });
65
+ if (target.executor === '@nx/jest:jest') {
66
+ target.options.jestConfig = jestProjectConfig;
67
+ }
68
+ if (targetDefaults?.cache === undefined) {
69
+ target.cache = jestTargetConfigInGraph.cache;
70
+ }
71
+ if (targetDefaults?.inputs === undefined) {
72
+ target.inputs = jestTargetConfigInGraph.inputs;
73
+ }
74
+ if (targetDefaults?.outputs === undefined) {
75
+ target.outputs = jestTargetConfigInGraph.outputs;
76
+ }
77
+ if (targetDefaults?.dependsOn === undefined) {
78
+ target.dependsOn = jestTargetConfigInGraph.dependsOn;
79
+ }
80
+ (0, devkit_1.updateProjectConfiguration)(tree, rootProject.name, rootProjectConfig);
81
+ // generate new global config as it was move to project config or is missing
82
+ generateGlobalConfig(tree, options.js);
83
+ }
84
+ }
85
+ }
86
+ exports.createJestConfig = createJestConfig;
87
+ function generateGlobalConfig(tree, isJS) {
88
+ const contents = isJS
89
+ ? (0, devkit_1.stripIndents) `
90
+ const { getJestProjects } = require('@nx/jest');
91
+
92
+ module.exports = {
93
+ projects: getJestProjects()
94
+ };`
95
+ : (0, devkit_1.stripIndents) `
96
+ import { getJestProjects } from '@nx/jest';
97
+
98
+ export default {
99
+ projects: getJestProjects()
100
+ };`;
101
+ tree.write(`jest.config.${isJS ? 'js' : 'ts'}`, contents);
102
+ }
@@ -0,0 +1,3 @@
1
+ import { type Tree } from '@nx/devkit';
2
+ import type { NormalizedJestProjectSchema } from '../schema';
3
+ export declare function ensureDependencies(tree: Tree, options: Partial<NormalizedJestProjectSchema>): import("@nx/devkit").GeneratorCallback;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ensureDependencies = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const versions_1 = require("../../../utils/versions");
6
+ function ensureDependencies(tree, options) {
7
+ const dependencies = {
8
+ tslib: versions_1.tslibVersion,
9
+ };
10
+ const devDeps = {
11
+ // because the default jest-preset uses ts-jest,
12
+ // jest will throw an error if it's not installed
13
+ // even if not using it in overriding transformers
14
+ 'ts-jest': versions_1.tsJestVersion,
15
+ };
16
+ if (options.testEnvironment !== 'none') {
17
+ devDeps[`jest-environment-${options.testEnvironment}`] = versions_1.jestVersion;
18
+ }
19
+ if (!options.js) {
20
+ devDeps['ts-node'] = versions_1.tsNodeVersion;
21
+ devDeps['@types/jest'] = versions_1.jestTypesVersion;
22
+ devDeps['@types/node'] = versions_1.typesNodeVersion;
23
+ }
24
+ if (options.compiler === 'babel' || options.babelJest) {
25
+ devDeps['babel-jest'] = versions_1.babelJestVersion;
26
+ // in some cases @nx/js will not already be present i.e. node only projects
27
+ devDeps['@nx/js'] = versions_1.nxVersion;
28
+ }
29
+ else if (options.compiler === 'swc') {
30
+ devDeps['@swc/jest'] = versions_1.swcJestVersion;
31
+ }
32
+ return (0, devkit_1.addDependenciesToPackageJson)(tree, dependencies, devDeps);
33
+ }
34
+ exports.ensureDependencies = ensureDependencies;
@@ -0,0 +1,2 @@
1
+ import { type Tree } from '@nx/devkit';
2
+ export declare function updateVsCodeRecommendedExtensions(host: Tree): void;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.updateVsCodeRecommendedExtensions = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ function updateVsCodeRecommendedExtensions(host) {
6
+ if (!host.exists('.vscode/extensions.json')) {
7
+ return;
8
+ }
9
+ (0, devkit_1.updateJson)(host, '.vscode/extensions.json', (json) => {
10
+ json.recommendations = json.recommendations || [];
11
+ const extension = 'firsttris.vscode-jest-runner';
12
+ if (!json.recommendations.includes(extension)) {
13
+ json.recommendations.push(extension);
14
+ }
15
+ return json;
16
+ });
17
+ }
18
+ exports.updateVsCodeRecommendedExtensions = updateVsCodeRecommendedExtensions;
@@ -1,4 +1,4 @@
1
- import { GeneratorCallback, Tree } from '@nx/devkit';
2
- import { JestInitSchema } from './schema';
3
- export declare function jestInitGenerator(tree: Tree, schema: JestInitSchema): Promise<GeneratorCallback>;
1
+ import { type GeneratorCallback, type Tree } from '@nx/devkit';
2
+ import type { JestInitSchema } from './schema';
3
+ export declare function jestInitGenerator(tree: Tree, options: JestInitSchema): Promise<GeneratorCallback>;
4
4
  export default jestInitGenerator;
@@ -2,77 +2,21 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.jestInitGenerator = void 0;
4
4
  const devkit_1 = require("@nx/devkit");
5
- const js_1 = require("@nx/js");
6
- const find_root_jest_files_1 = require("../../utils/config/find-root-jest-files");
7
5
  const versions_1 = require("../../utils/versions");
8
- const schemaDefaults = {
9
- compiler: 'tsc',
10
- js: false,
11
- rootProject: false,
12
- testEnvironment: 'jsdom',
13
- };
14
- function generateGlobalConfig(tree, isJS) {
15
- const contents = isJS
16
- ? (0, devkit_1.stripIndents) `
17
- const { getJestProjects } = require('@nx/jest');
18
-
19
- module.exports = {
20
- projects: getJestProjects()
21
- };`
22
- : (0, devkit_1.stripIndents) `
23
- import { getJestProjects } from '@nx/jest';
24
-
25
- export default {
26
- projects: getJestProjects()
27
- };`;
28
- tree.write(`jest.config.${isJS ? 'js' : 'ts'}`, contents);
29
- }
30
- function createJestConfig(tree, options) {
31
- if (!tree.exists('jest.preset.js')) {
32
- // preset is always js file.
33
- tree.write(`jest.preset.js`, `
34
- const nxPreset = require('@nx/jest/preset').default;
35
-
36
- module.exports = { ...nxPreset }`);
37
- updateProductionFileSet(tree);
38
- addJestTargetDefaults(tree);
39
- }
40
- if (options.rootProject) {
41
- // we don't want any config to be made because the `configurationGenerator` will do it.
42
- // will copy the template config file
43
- return;
44
- }
45
- const rootJestPath = (0, find_root_jest_files_1.findRootJestConfig)(tree);
46
- if (!rootJestPath) {
47
- // if there's not root jest config, we will create one and return
48
- // this can happen when:
49
- // - root jest config was renamed => in which case there is migration needed
50
- // - root project didn't have jest setup => again, no migration is needed
51
- generateGlobalConfig(tree, options.js);
52
- return;
53
- }
54
- if (tree.exists(rootJestPath)) {
55
- // moving from root project config to monorepo-style config
56
- const projects = (0, devkit_1.getProjects)(tree);
57
- const projectNames = Array.from(projects.keys());
58
- const rootProject = projectNames.find((projectName) => projects.get(projectName)?.root === '.');
59
- // root project might have been removed,
60
- // if it's missing there's nothing to migrate
61
- if (rootProject) {
62
- const rootProjectConfig = projects.get(rootProject);
63
- const jestTarget = Object.values(rootProjectConfig.targets || {}).find((t) => t?.executor === '@nx/jest:jest' || t?.executor === '@nrwl/jest:jest');
64
- const isProjectConfig = jestTarget?.options?.jestConfig === rootJestPath;
65
- // if root project doesn't have jest target, there's nothing to migrate
66
- if (isProjectConfig) {
67
- const jestProjectConfig = `jest.config.${rootProjectConfig.projectType === 'application' ? 'app' : 'lib'}.${options.js ? 'js' : 'ts'}`;
68
- tree.rename(rootJestPath, jestProjectConfig);
69
- jestTarget.options.jestConfig = jestProjectConfig;
70
- (0, devkit_1.updateProjectConfiguration)(tree, rootProject, rootProjectConfig);
71
- }
72
- // generate new global config as it was move to project config or is missing
73
- generateGlobalConfig(tree, options.js);
74
- }
6
+ function addPlugin(tree) {
7
+ const nxJson = (0, devkit_1.readNxJson)(tree);
8
+ nxJson.plugins ??= [];
9
+ if (!nxJson.plugins.some((p) => typeof p === 'string'
10
+ ? p === '@nx/jest/plugin'
11
+ : p.plugin === '@nx/jest/plugin')) {
12
+ nxJson.plugins.push({
13
+ plugin: '@nx/jest/plugin',
14
+ options: {
15
+ targetName: 'test',
16
+ },
17
+ });
75
18
  }
19
+ (0, devkit_1.updateNxJson)(tree, nxJson);
76
20
  }
77
21
  function updateProductionFileSet(tree) {
78
22
  const nxJson = (0, devkit_1.readNxJson)(tree);
@@ -96,9 +40,9 @@ function updateProductionFileSet(tree) {
96
40
  }
97
41
  function addJestTargetDefaults(tree) {
98
42
  const nxJson = (0, devkit_1.readNxJson)(tree);
99
- const productionFileSet = nxJson.namedInputs?.production;
100
43
  nxJson.targetDefaults ??= {};
101
44
  nxJson.targetDefaults['@nx/jest:jest'] ??= {};
45
+ const productionFileSet = nxJson.namedInputs?.production;
102
46
  nxJson.targetDefaults['@nx/jest:jest'].cache ??= true;
103
47
  // Test targets depend on all their project's sources + production sources of dependencies
104
48
  nxJson.targetDefaults['@nx/jest:jest'].inputs ??= [
@@ -117,70 +61,31 @@ function addJestTargetDefaults(tree) {
117
61
  };
118
62
  (0, devkit_1.updateNxJson)(tree, nxJson);
119
63
  }
120
- function updateDependencies(tree, options) {
121
- const dependencies = {
122
- tslib: versions_1.tslibVersion,
123
- };
124
- const devDeps = {
64
+ function updateDependencies(tree) {
65
+ return (0, devkit_1.addDependenciesToPackageJson)(tree, {}, {
125
66
  '@nx/jest': versions_1.nxVersion,
126
67
  jest: versions_1.jestVersion,
127
- // because the default jest-preset uses ts-jest,
128
- // jest will throw an error if it's not installed
129
- // even if not using it in overriding transformers
130
- 'ts-jest': versions_1.tsJestVersion,
131
- };
132
- if (options.testEnvironment !== 'none') {
133
- devDeps[`jest-environment-${options.testEnvironment}`] = versions_1.jestVersion;
134
- }
135
- if (!options.js) {
136
- devDeps['ts-node'] = versions_1.tsNodeVersion;
137
- devDeps['@types/jest'] = versions_1.jestTypesVersion;
138
- devDeps['@types/node'] = versions_1.typesNodeVersion;
139
- }
140
- if (options.compiler === 'babel' || options.babelJest) {
141
- devDeps['babel-jest'] = versions_1.babelJestVersion;
142
- // in some cases @nx/js will not already be present i.e. node only projects
143
- devDeps['@nx/js'] = versions_1.nxVersion;
144
- }
145
- else if (options.compiler === 'swc') {
146
- devDeps['@swc/jest'] = versions_1.swcJestVersion;
147
- }
148
- return (0, devkit_1.addDependenciesToPackageJson)(tree, dependencies, devDeps);
149
- }
150
- function updateExtensions(host) {
151
- if (!host.exists('.vscode/extensions.json')) {
152
- return;
153
- }
154
- (0, devkit_1.updateJson)(host, '.vscode/extensions.json', (json) => {
155
- json.recommendations = json.recommendations || [];
156
- const extension = 'firsttris.vscode-jest-runner';
157
- if (!json.recommendations.includes(extension)) {
158
- json.recommendations.push(extension);
159
- }
160
- return json;
161
68
  });
162
69
  }
163
- async function jestInitGenerator(tree, schema) {
164
- const options = normalizeOptions(schema);
70
+ async function jestInitGenerator(tree, options) {
71
+ if (!tree.exists('jest.preset.js')) {
72
+ updateProductionFileSet(tree);
73
+ if (process.env.NX_PCV3 === 'true') {
74
+ addPlugin(tree);
75
+ }
76
+ else {
77
+ addJestTargetDefaults(tree);
78
+ }
79
+ }
165
80
  const tasks = [];
166
- tasks.push(await (0, js_1.initGenerator)(tree, {
167
- ...schema,
168
- skipFormat: true,
169
- }));
170
- createJestConfig(tree, options);
171
81
  if (!options.skipPackageJson) {
172
- (0, devkit_1.removeDependenciesFromPackageJson)(tree, ['@nx/jest'], []);
173
- const installTask = updateDependencies(tree, options);
174
- tasks.push(installTask);
82
+ tasks.push((0, devkit_1.removeDependenciesFromPackageJson)(tree, ['@nx/jest'], []));
83
+ tasks.push(updateDependencies(tree));
84
+ }
85
+ if (!options.skipFormat) {
86
+ await (0, devkit_1.formatFiles)(tree);
175
87
  }
176
- updateExtensions(tree);
177
88
  return (0, devkit_1.runTasksInSerial)(...tasks);
178
89
  }
179
90
  exports.jestInitGenerator = jestInitGenerator;
180
- function normalizeOptions(options) {
181
- return {
182
- ...schemaDefaults,
183
- ...options,
184
- };
185
- }
186
91
  exports.default = jestInitGenerator;
@@ -1,11 +1,4 @@
1
1
  export interface JestInitSchema {
2
- compiler?: 'tsc' | 'babel' | 'swc';
3
- js?: boolean;
2
+ skipFormat?: boolean;
4
3
  skipPackageJson?: boolean;
5
- testEnvironment?: 'node' | 'jsdom' | 'none';
6
- /**
7
- * @deprecated
8
- */
9
- babelJest?: boolean;
10
- rootProject?: boolean;
11
4
  }
@@ -6,35 +6,16 @@
6
6
  "description": "Add Jest Configuration to a workspace.",
7
7
  "type": "object",
8
8
  "properties": {
9
- "babelJest": {
10
- "type": "boolean",
11
- "alias": "babel-jest",
12
- "description": "Use `babel-jest` instead of `ts-jest`.",
13
- "default": false
14
- },
15
- "skipPackageJson": {
9
+ "skipFormat": {
10
+ "description": "Skip formatting files.",
16
11
  "type": "boolean",
17
12
  "default": false,
18
- "description": "Do not add dependencies to `package.json`.",
19
13
  "x-priority": "internal"
20
14
  },
21
- "testEnvironment": {
22
- "type": "string",
23
- "enum": ["jsdom", "node", "none"],
24
- "description": "The test environment for jest. This controls which jest-environment-* package is installed",
25
- "default": "jsdom",
26
- "x-priority": "important"
27
- },
28
- "js": {
29
- "type": "boolean",
30
- "default": false,
31
- "description": "Use JavaScript instead of TypeScript for config files"
32
- },
33
- "rootProject": {
34
- "description": "initialize Jest for an application at the root of the workspace",
15
+ "skipPackageJson": {
35
16
  "type": "boolean",
36
17
  "default": false,
37
- "hidden": true,
18
+ "description": "Do not add dependencies to `package.json`.",
38
19
  "x-priority": "internal"
39
20
  }
40
21
  },
@@ -0,0 +1,6 @@
1
+ import { CreateDependencies, CreateNodes } from '@nx/devkit';
2
+ export interface JestPluginOptions {
3
+ targetName?: string;
4
+ }
5
+ export declare const createDependencies: CreateDependencies;
6
+ export declare const createNodes: CreateNodes<JestPluginOptions>;
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createNodes = exports.createDependencies = void 0;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const path_1 = require("path");
6
+ const project_configuration_utils_1 = require("nx/src/project-graph/utils/project-configuration-utils");
7
+ const get_named_inputs_1 = require("@nx/devkit/src/utils/get-named-inputs");
8
+ const fs_1 = require("fs");
9
+ const jest_config_1 = require("jest-config");
10
+ const cache_directory_1 = require("nx/src/utils/cache-directory");
11
+ const calculate_hash_for_create_nodes_1 = require("@nx/devkit/src/utils/calculate-hash-for-create-nodes");
12
+ const package_json_workspaces_1 = require("nx/plugins/package-json-workspaces");
13
+ const globs_1 = require("nx/src/utils/globs");
14
+ const minimatch = require("minimatch");
15
+ const cachePath = (0, path_1.join)(cache_directory_1.projectGraphCacheDirectory, 'jest.hash');
16
+ const targetsCache = (0, fs_1.existsSync)(cachePath) ? readTargetsCache() : {};
17
+ const calculatedTargets = {};
18
+ function readTargetsCache() {
19
+ return (0, devkit_1.readJsonFile)(cachePath);
20
+ }
21
+ function writeTargetsToCache(targets) {
22
+ (0, devkit_1.writeJsonFile)(cachePath, targets);
23
+ }
24
+ const createDependencies = () => {
25
+ writeTargetsToCache(calculatedTargets);
26
+ return [];
27
+ };
28
+ exports.createDependencies = createDependencies;
29
+ exports.createNodes = [
30
+ '**/jest.config.{cjs,mjs,js,cts,mts,ts}',
31
+ async (configFilePath, options, context) => {
32
+ const projectRoot = (0, path_1.dirname)(configFilePath);
33
+ const packageManagerWorkspacesGlob = (0, globs_1.combineGlobPatterns)((0, package_json_workspaces_1.getGlobPatternsFromPackageManagerWorkspaces)(context.workspaceRoot));
34
+ // Do not create a project if package.json and project.json isn't there.
35
+ const siblingFiles = (0, fs_1.readdirSync)((0, path_1.join)(context.workspaceRoot, projectRoot));
36
+ if (!siblingFiles.includes('package.json') &&
37
+ !siblingFiles.includes('project.json')) {
38
+ return {};
39
+ }
40
+ else if (!siblingFiles.includes('project.json') &&
41
+ siblingFiles.includes('package.json')) {
42
+ const path = (0, devkit_1.joinPathFragments)(projectRoot, 'package.json');
43
+ const isPackageJsonProject = minimatch(path, packageManagerWorkspacesGlob);
44
+ if (!isPackageJsonProject) {
45
+ return {};
46
+ }
47
+ }
48
+ options = normalizeOptions(options);
49
+ const hash = (0, calculate_hash_for_create_nodes_1.calculateHashForCreateNodes)(projectRoot, options, context);
50
+ const targets = targetsCache[hash] ??
51
+ (await buildJestTargets(configFilePath, projectRoot, options, context));
52
+ calculatedTargets[hash] = targets;
53
+ return {
54
+ projects: {
55
+ [projectRoot]: {
56
+ root: projectRoot,
57
+ targets: targets,
58
+ },
59
+ },
60
+ };
61
+ },
62
+ ];
63
+ async function buildJestTargets(configFilePath, projectRoot, options, context) {
64
+ const config = await (0, jest_config_1.readConfig)({
65
+ _: [],
66
+ $0: undefined,
67
+ }, (0, path_1.resolve)(context.workspaceRoot, configFilePath), true, null, undefined, true);
68
+ const targetDefaults = (0, project_configuration_utils_1.readTargetDefaultsForTarget)(options.targetName, context.nxJsonConfiguration.targetDefaults, 'nx:run-commands');
69
+ const namedInputs = (0, get_named_inputs_1.getNamedInputs)(projectRoot, context);
70
+ const targets = {};
71
+ const target = (targets[options.targetName] = {
72
+ command: 'jest',
73
+ options: {
74
+ cwd: projectRoot,
75
+ },
76
+ });
77
+ if (!targetDefaults?.cache) {
78
+ target.cache = true;
79
+ }
80
+ if (!targetDefaults?.inputs) {
81
+ target.inputs = getInputs(namedInputs);
82
+ }
83
+ if (!targetDefaults?.outputs) {
84
+ target.outputs = getOutputs(projectRoot, config, context);
85
+ }
86
+ return targets;
87
+ }
88
+ function getInputs(namedInputs) {
89
+ return [
90
+ ...('production' in namedInputs
91
+ ? ['default', '^production']
92
+ : ['default', '^default']),
93
+ {
94
+ externalDependencies: ['jest'],
95
+ },
96
+ ];
97
+ }
98
+ function getOutputs(projectRoot, { globalConfig }, context) {
99
+ function getOutput(path) {
100
+ const relativePath = (0, path_1.relative)((0, path_1.join)(context.workspaceRoot, projectRoot), path);
101
+ if (relativePath.startsWith('..')) {
102
+ return (0, path_1.join)('{workspaceRoot}', (0, path_1.join)(projectRoot, relativePath));
103
+ }
104
+ else {
105
+ return (0, path_1.join)('{projectRoot}', relativePath);
106
+ }
107
+ }
108
+ const outputs = [];
109
+ for (const outputOption of [
110
+ globalConfig.coverageDirectory,
111
+ globalConfig.outputFile,
112
+ ]) {
113
+ if (outputOption) {
114
+ outputs.push(getOutput(outputOption));
115
+ }
116
+ }
117
+ return outputs;
118
+ }
119
+ function normalizeOptions(options) {
120
+ options ??= {};
121
+ options.targetName ??= 'test';
122
+ return options;
123
+ }