| 1 | let globalPnpApi;
|
|---|
| 2 | try {
|
|---|
| 3 | globalPnpApi = require(`pnpapi`);
|
|---|
| 4 | } catch {
|
|---|
| 5 | // Just ignore if we don't have a global PnP instance - perhaps
|
|---|
| 6 | // we'll eventually find one at runtime due to multi-tree
|
|---|
| 7 | }
|
|---|
| 8 |
|
|---|
| 9 | const createRequire = require(`./createRequire`);
|
|---|
| 10 | const getDefaultResolver = require(`./getDefaultResolver`);
|
|---|
| 11 |
|
|---|
| 12 | module.exports = (request, options) => {
|
|---|
| 13 | const {
|
|---|
| 14 | basedir,
|
|---|
| 15 | defaultResolver = getDefaultResolver(),
|
|---|
| 16 | extensions,
|
|---|
| 17 | } = options;
|
|---|
| 18 |
|
|---|
| 19 | if (process.versions.pnp) {
|
|---|
| 20 | let pnpApi = globalPnpApi;
|
|---|
| 21 |
|
|---|
| 22 | // While technically it would be more correct to run this code
|
|---|
| 23 | // everytime (since they file being run *may* belong to a
|
|---|
| 24 | // different dependency tree than the one owning Jest), in
|
|---|
| 25 | // practice this doesn't happen anywhere else than on the Jest
|
|---|
| 26 | // repository itself (in the test env). So in order to preserve
|
|---|
| 27 | // the performances, we can afford a slight incoherence here.
|
|---|
| 28 | if (!pnpApi) {
|
|---|
| 29 | try {
|
|---|
| 30 | const baseReq = createRequire(`${basedir}/internal.js`);
|
|---|
| 31 | pnpApi = baseReq(`pnpapi`);
|
|---|
| 32 | } catch {
|
|---|
| 33 | // The file isn't part of a PnP dependency tree, so we can
|
|---|
| 34 | // just use the default Jest resolver.
|
|---|
| 35 | }
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|
| 38 | if (pnpApi) {
|
|---|
| 39 | const resolution = pnpApi.resolveRequest(request, `${basedir}/`, {extensions});
|
|---|
| 40 |
|
|---|
| 41 | // When the request is a native module, Jest expects to get the string back unmodified, but pnp returns null instead.
|
|---|
| 42 | if (resolution === null)
|
|---|
| 43 | return request;
|
|---|
| 44 |
|
|---|
| 45 | return resolution;
|
|---|
| 46 | }
|
|---|
| 47 | }
|
|---|
| 48 |
|
|---|
| 49 | return defaultResolver(request, {...options, allowPnp: false});
|
|---|
| 50 | };
|
|---|