| 1 | 'use strict';
|
|---|
| 2 |
|
|---|
| 3 | const resolve = require('resolve/sync');
|
|---|
| 4 | const isCoreModule = require('is-core-module');
|
|---|
| 5 | const path = require('path');
|
|---|
| 6 |
|
|---|
| 7 | const log = require('debug')('eslint-plugin-import:resolver:node');
|
|---|
| 8 |
|
|---|
| 9 | exports.interfaceVersion = 2;
|
|---|
| 10 |
|
|---|
| 11 | function opts(file, config, packageFilter) {
|
|---|
| 12 | return Object.assign({ // more closely matches Node (#333)
|
|---|
| 13 | // plus 'mjs' for native modules! (#939)
|
|---|
| 14 | extensions: ['.mjs', '.js', '.json', '.node'],
|
|---|
| 15 | // TODO: semver-major: remove this to match Node's default behavior
|
|---|
| 16 | preserveSymlinks: true,
|
|---|
| 17 | }, config, {
|
|---|
| 18 | // path.resolve will handle paths relative to CWD
|
|---|
| 19 | basedir: path.dirname(path.resolve(file)),
|
|---|
| 20 | packageFilter,
|
|---|
| 21 | });
|
|---|
| 22 | }
|
|---|
| 23 |
|
|---|
| 24 | function identity(x) { return x; }
|
|---|
| 25 |
|
|---|
| 26 | function packageFilter(pkg, dir, config) {
|
|---|
| 27 | let found = false;
|
|---|
| 28 | const file = path.join(dir, 'dummy.js');
|
|---|
| 29 | if (pkg.module) {
|
|---|
| 30 | try {
|
|---|
| 31 | resolve(String(pkg.module).replace(/^(?:\.\/)?/, './'), opts(file, config, identity));
|
|---|
| 32 | pkg.main = pkg.module;
|
|---|
| 33 | found = true;
|
|---|
| 34 | } catch (err) {
|
|---|
| 35 | log('resolve threw error trying to find pkg.module:', err);
|
|---|
| 36 | }
|
|---|
| 37 | }
|
|---|
| 38 | if (!found && pkg['jsnext:main']) {
|
|---|
| 39 | try {
|
|---|
| 40 | resolve(String(pkg['jsnext:main']).replace(/^(?:\.\/)?/, './'), opts(file, config, identity));
|
|---|
| 41 | pkg.main = pkg['jsnext:main'];
|
|---|
| 42 | found = true;
|
|---|
| 43 | } catch (err) {
|
|---|
| 44 | log('resolve threw error trying to find pkg[\'jsnext:main\']:', err);
|
|---|
| 45 | }
|
|---|
| 46 | }
|
|---|
| 47 | return pkg;
|
|---|
| 48 | }
|
|---|
| 49 |
|
|---|
| 50 | exports.resolve = function (source, file, config) {
|
|---|
| 51 | log('Resolving:', source, 'from:', file);
|
|---|
| 52 | let resolvedPath;
|
|---|
| 53 |
|
|---|
| 54 | if (isCoreModule(source)) {
|
|---|
| 55 | log('resolved to core');
|
|---|
| 56 | return { found: true, path: null };
|
|---|
| 57 | }
|
|---|
| 58 |
|
|---|
| 59 | try {
|
|---|
| 60 | const cachedFilter = function (pkg, pkgFileOrDir, maybeDir) { return packageFilter(pkg, maybeDir || pkgFileOrDir, config); };
|
|---|
| 61 | resolvedPath = resolve(source, opts(file, config, cachedFilter));
|
|---|
| 62 | log('Resolved to:', resolvedPath);
|
|---|
| 63 | return { found: true, path: resolvedPath };
|
|---|
| 64 | } catch (err) {
|
|---|
| 65 | log('resolve threw error:', err);
|
|---|
| 66 | return { found: false };
|
|---|
| 67 | }
|
|---|
| 68 | };
|
|---|