-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathpatched-jest-resolver.js
More file actions
256 lines (225 loc) · 8.07 KB
/
patched-jest-resolver.js
File metadata and controls
256 lines (225 loc) · 8.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
'use strict';
const path = require('path');
const fs = require('fs');
/**
* Custom resolver which will respect package exports (until Jest supports it natively
* by resolving https://github.com/facebook/jest/issues/9771)
*
* Also needed for TypeScript project references support:
* - ts-jest doesn't support TypeScript project references (https://github.com/kulshekhar/ts-jest/issues/1648)
* - When using TS project references, Jest needs to resolve imports like '@nx/devkit' to TypeScript source files
* - Without this resolver, Jest will fail to resolve these imports correctly
*/
const enhancedResolver = require('enhanced-resolve').create.sync({
conditionNames: ['require', 'node', 'default'],
extensions: ['.js', '.json', '.node', '.ts', '.tsx'],
});
if (
process.argv[1].indexOf('jest-worker') > -1 ||
(process.argv.length >= 4 && process.argv[3].split(':')[1] === 'test')
) {
const root = path.join(__dirname, '..', 'tmp', 'unit');
try {
if (!fs.existsSync(root)) {
fs.mkdirSync(root);
}
} catch (_err) {}
process.env.NX_WORKSPACE_ROOT_PATH = root;
}
const excludedPackages = [
'@nx/conformance',
'@nx/owners',
'@nx/key',
'@nx/s3-cache',
'@nx/azure-cache',
'@nx/gcs-cache',
'@nx/shared-fs-cache',
];
module.exports = function (modulePath, options) {
// Skip sequencer
if (modulePath === 'jest-sequencer-@jest/test-sequencer') return;
// Only use custom resolution for workspace packages
// Let default resolver handle published packages and everything else
const workspacePackages = [
'@nx/rollup',
'@nx/eslint',
'@nx/vite',
'@nx/jest',
'@nx/docker',
'@nx/js',
'@nx/next',
'@nx/storybook',
'@nx/rsbuild',
'@nx/react-native',
'@nx/express',
'@nx/web',
'@nx/vue',
'@nx/workspace',
'@nx/module-federation',
'@nx/rspack',
'@nx/eslint-plugin',
'@nx/angular',
'@nx/create-nx-plugin',
'@nx/create-nx-workspace',
'@nx/detox',
'@nx/devkit',
'@nx/esbuild',
'@nx/expo',
'@nx/gradle',
'@nx/nest',
'@nx/node',
'@nx/nuxt',
'@nx/playwright',
'@nx/react',
'@nx/remix',
'@nx/webpack',
];
const isWorkspacePackage =
workspacePackages.some((pkg) => modulePath.startsWith(pkg)) ||
modulePath.startsWith('nx/');
if (!isWorkspacePackage) {
// Global modules which must be resolved by defaultResolver
if (['child_process', 'fs', 'http', 'path'].includes(modulePath)) {
return options.defaultResolver(modulePath, options);
}
return enhancedResolver(path.resolve(options.basedir), modulePath);
}
const ext = path.extname(modulePath);
// Handle CSS imports
if (ext === '.css' || ext === '.scss' || ext === '.sass' || ext === '.less') {
return require.resolve('identity-obj-proxy');
}
try {
// Detect if we're running from e2e directory
const isE2E = options.rootDir.includes('/e2e/');
// For e2e tests, skip workspace resolution and use default resolver
if (isE2E) {
return options.defaultResolver(modulePath, options);
}
// Find workspace root - avoid filesystem lookups inside node_modules
// For PNPM workspaces, we know the structure: workspace/packages/packageName
let workspaceRoot = options.rootDir;
// If we're in a packages subdirectory, go up two levels to workspace root
if (workspaceRoot.includes('/packages/')) {
const packagesIndex = workspaceRoot.lastIndexOf('/packages/');
workspaceRoot = workspaceRoot.substring(0, packagesIndex);
} else {
// Fallback: go up directories until we find packages/ (but check pnpm-lock.yaml for validation)
while (workspaceRoot && workspaceRoot !== path.dirname(workspaceRoot)) {
const pnpmLock = path.join(workspaceRoot, 'pnpm-lock.yaml');
const packagesDir = path.join(workspaceRoot, 'packages');
if (fs.existsSync(pnpmLock) && fs.existsSync(packagesDir)) {
break;
}
workspaceRoot = path.dirname(workspaceRoot);
}
}
const packagesPath = path.join(workspaceRoot, 'packages');
// Handle main @nx/* package imports (e.g., '@nx/devkit', '@nx/js')
const nxPackageMatch = modulePath.match(/^@nx\/([^/]+)$/);
if (nxPackageMatch) {
const packageName = nxPackageMatch[1];
// Check if this package exists in workspace
const packageDir = path.join(packagesPath, packageName);
// Try different entry points based on package structure
const possibleEntries = [
path.join(packageDir, 'index.ts'),
path.join(packageDir, 'src', 'index.ts'),
];
for (const entry of possibleEntries) {
if (fs.existsSync(entry) && fs.lstatSync(entry).isFile()) {
return entry;
}
}
}
// Handle @nx/*/src/* subpath imports (e.g., '@nx/devkit/src/utils/something')
const nxSubpathMatch = modulePath.match(/^@nx\/([^/]+)\/src\/(.+)$/);
if (nxSubpathMatch) {
const packageName = nxSubpathMatch[1];
const subpath = nxSubpathMatch[2];
// Try different patterns for subpath resolution
const possiblePaths = [
path.join(packagesPath, packageName, 'src', subpath + '.ts'), // Direct file
path.join(packagesPath, packageName, 'src', subpath, 'index.ts'), // Directory with index.ts
];
for (const possiblePath of possiblePaths) {
if (
fs.existsSync(possiblePath) &&
fs.lstatSync(possiblePath).isFile()
) {
return possiblePath;
}
}
}
// Handle @nx/* other subpaths (e.g., '@nx/devkit/testing', '@nx/devkit/package.json')
const nxOtherMatch = modulePath.match(/^@nx\/([^/]+)\/(.+)$/);
if (nxOtherMatch) {
const packageName = nxOtherMatch[1];
const subpath = nxOtherMatch[2];
const packageDir = path.join(packagesPath, packageName);
// Try different patterns for subpath resolution
const possiblePaths = [
path.join(packageDir, subpath), // For files like package.json
path.join(packageDir, subpath + '.ts'),
path.join(packageDir, 'src', subpath + '.ts'),
];
for (const possiblePath of possiblePaths) {
if (
fs.existsSync(possiblePath) &&
fs.lstatSync(possiblePath).isFile()
) {
return possiblePath;
}
}
}
// Handle nx/src/* imports (direct nx package imports)
const nxSrcMatch = modulePath.match(/^nx\/src\/(.+)$/);
if (nxSrcMatch) {
const subpath = nxSrcMatch[1];
const resolvedPath = path.join(
packagesPath,
'nx',
'src',
subpath + '.ts'
);
if (fs.existsSync(resolvedPath) && fs.lstatSync(resolvedPath).isFile()) {
return resolvedPath;
}
}
// Handle nx/package.json specifically
if (modulePath === 'nx/package.json') {
return path.join(packagesPath, 'nx', 'package.json');
}
// Handle other nx/* patterns
const nxOtherPatternMatch = modulePath.match(/^nx\/(.+)$/);
if (nxOtherPatternMatch) {
const subpath = nxOtherPatternMatch[1];
const resolvedPath = path.join(packagesPath, 'nx', subpath + '.ts');
if (fs.existsSync(resolvedPath)) {
return resolvedPath;
}
}
// Block excluded Nx packages from auto-resolution
if (
modulePath.startsWith('@nx/') &&
!modulePath.startsWith('@nx/powerpack-') &&
!excludedPackages.some((pkg) => modulePath.startsWith(pkg))
) {
// If we get here, it means the workspace package couldn't be resolved above
// This might indicate a missing file or incorrect import
console.warn(
`[resolver] Could not resolve workspace package: ${modulePath}`
);
}
return enhancedResolver(path.resolve(options.basedir), modulePath);
} catch (e) {
// Final fallback: use default resolver for packages we can't handle
// This preserves the old behavior where packages that couldn't be resolved
// by the custom resolver would fall back to default resolution
try {
return options.defaultResolver(modulePath, options);
} catch (defaultResolverError) {
throw new Error(`[resolver] Could not resolve module: ${modulePath}`);
}
}
};