|
| 1 | +import fs from 'fs'; |
| 2 | +import path from 'path'; |
| 3 | +import { promisify } from 'util'; |
| 4 | + |
| 5 | +import resolve from 'resolve'; |
| 6 | + |
| 7 | +import { getPackageName } from './util'; |
| 8 | +import { exists, realpath } from './fs'; |
| 9 | + |
| 10 | +const resolveImportPath = promisify(resolve); |
| 11 | +const readFile = promisify(fs.readFile); |
| 12 | + |
| 13 | +const pathNotFoundError = (subPath, pkgPath) => |
| 14 | + new Error(`Package subpath '${subPath}' is not defined by "exports" in ${pkgPath}`); |
| 15 | + |
| 16 | +function findExportKeyMatch(exportMap, subPath) { |
| 17 | + for (const key of Object.keys(exportMap)) { |
| 18 | + if (key.endsWith('*')) { |
| 19 | + // star match: "./foo/*": "./foo/*.js" |
| 20 | + const keyWithoutStar = key.substring(0, key.length - 1); |
| 21 | + if (subPath.startsWith(keyWithoutStar)) { |
| 22 | + return key; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + if (key.endsWith('/') && subPath.startsWith(key)) { |
| 27 | + // directory match (deprecated by node): "./foo/": "./foo/.js" |
| 28 | + return key; |
| 29 | + } |
| 30 | + |
| 31 | + if (key === subPath) { |
| 32 | + // literal match |
| 33 | + return key; |
| 34 | + } |
| 35 | + } |
| 36 | + return null; |
| 37 | +} |
| 38 | + |
| 39 | +function mapSubPath(pkgJsonPath, subPath, key, value) { |
| 40 | + if (typeof value === 'string') { |
| 41 | + if (typeof key === 'string' && key.endsWith('*')) { |
| 42 | + // star match: "./foo/*": "./foo/*.js" |
| 43 | + const keyWithoutStar = key.substring(0, key.length - 1); |
| 44 | + const subPathAfterKey = subPath.substring(keyWithoutStar.length); |
| 45 | + return value.replace(/\*/g, subPathAfterKey); |
| 46 | + } |
| 47 | + |
| 48 | + if (value.endsWith('/')) { |
| 49 | + // directory match (deprecated by node): "./foo/": "./foo/.js" |
| 50 | + return `${value}${subPath.substring(key.length)}`; |
| 51 | + } |
| 52 | + |
| 53 | + // mapping is a string, for example { "./foo": "./dist/foo.js" } |
| 54 | + return value; |
| 55 | + } |
| 56 | + |
| 57 | + if (Array.isArray(value)) { |
| 58 | + // mapping is an array with fallbacks, for example { "./foo": ["foo:bar", "./dist/foo.js"] } |
| 59 | + return value.find((v) => v.startsWith('./')); |
| 60 | + } |
| 61 | + |
| 62 | + throw pathNotFoundError(subPath, pkgJsonPath); |
| 63 | +} |
| 64 | + |
| 65 | +function findEntrypoint(pkgJsonPath, subPath, exportMap, conditions, key) { |
| 66 | + if (typeof exportMap !== 'object') { |
| 67 | + return mapSubPath(pkgJsonPath, subPath, key, exportMap); |
| 68 | + } |
| 69 | + |
| 70 | + // iterate conditions recursively, find the first that matches all conditions |
| 71 | + for (const [condition, subExportMap] of Object.entries(exportMap)) { |
| 72 | + if (conditions.includes(condition)) { |
| 73 | + const mappedSubPath = findEntrypoint(pkgJsonPath, subPath, subExportMap, conditions, key); |
| 74 | + if (mappedSubPath) { |
| 75 | + return mappedSubPath; |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + throw pathNotFoundError(subPath, pkgJsonPath); |
| 80 | +} |
| 81 | + |
| 82 | +export function findEntrypointTopLevel(pkgJsonPath, subPath, exportMap, conditions) { |
| 83 | + if (typeof exportMap !== 'object') { |
| 84 | + // the export map shorthand, for example { exports: "./index.js" } |
| 85 | + if (subPath !== '.') { |
| 86 | + // shorthand only supports a main entrypoint |
| 87 | + throw pathNotFoundError(subPath, pkgJsonPath); |
| 88 | + } |
| 89 | + return mapSubPath(pkgJsonPath, subPath, null, exportMap); |
| 90 | + } |
| 91 | + |
| 92 | + // export map is an object, the top level can be either conditions or sub path mappings |
| 93 | + const keys = Object.keys(exportMap); |
| 94 | + const isConditions = keys.every((k) => !k.startsWith('.')); |
| 95 | + const isMappings = keys.every((k) => k.startsWith('.')); |
| 96 | + |
| 97 | + if (!isConditions && !isMappings) { |
| 98 | + throw new Error( |
| 99 | + `Invalid package config ${pkgJsonPath}, "exports" cannot contain some keys starting with '.'` + |
| 100 | + ' and some not. The exports object must either be an object of package subpath keys or an object of main entry' + |
| 101 | + ' condition name keys only.' |
| 102 | + ); |
| 103 | + } |
| 104 | + |
| 105 | + let key = null; |
| 106 | + let exportMapForSubPath; |
| 107 | + |
| 108 | + if (isConditions) { |
| 109 | + // top level is conditions, for example { "import": ..., "require": ..., "module": ... } |
| 110 | + if (subPath !== '.') { |
| 111 | + // package with top level conditions means it only supports a main entrypoint |
| 112 | + throw pathNotFoundError(subPath, pkgJsonPath); |
| 113 | + } |
| 114 | + exportMapForSubPath = exportMap; |
| 115 | + } else { |
| 116 | + // top level is sub path mappings, for example { ".": ..., "./foo": ..., "./bar": ... } |
| 117 | + key = findExportKeyMatch(exportMap, subPath); |
| 118 | + if (!key) { |
| 119 | + throw pathNotFoundError(subPath, pkgJsonPath); |
| 120 | + } |
| 121 | + exportMapForSubPath = exportMap[key]; |
| 122 | + } |
| 123 | + |
| 124 | + return findEntrypoint(pkgJsonPath, subPath, exportMapForSubPath, conditions, key); |
| 125 | +} |
| 126 | + |
| 127 | +async function resolveId(importPath, options, exportConditions, warn) { |
| 128 | + const pkgName = getPackageName(importPath); |
| 129 | + if (pkgName) { |
| 130 | + let pkgJsonPath; |
| 131 | + let pkgJson; |
| 132 | + try { |
| 133 | + pkgJsonPath = await resolveImportPath(`${pkgName}/package.json`, options); |
| 134 | + pkgJson = JSON.parse(await readFile(pkgJsonPath, 'utf-8')); |
| 135 | + } catch (_) { |
| 136 | + // if there is no package.json we defer to regular resolve behavior |
| 137 | + } |
| 138 | + |
| 139 | + if (pkgJsonPath && pkgJson && pkgJson.exports) { |
| 140 | + try { |
| 141 | + const packageSubPath = |
| 142 | + pkgName === importPath ? '.' : `.${importPath.substring(pkgName.length)}`; |
| 143 | + const mappedSubPath = findEntrypointTopLevel( |
| 144 | + pkgJsonPath, |
| 145 | + packageSubPath, |
| 146 | + pkgJson.exports, |
| 147 | + exportConditions |
| 148 | + ); |
| 149 | + const pkgDir = path.dirname(pkgJsonPath); |
| 150 | + return path.join(pkgDir, mappedSubPath); |
| 151 | + } catch (error) { |
| 152 | + warn(error); |
| 153 | + return null; |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + return resolveImportPath(importPath, options); |
| 159 | +} |
| 160 | + |
| 161 | +// Resolve module specifiers in order. Promise resolves to the first module that resolves |
| 162 | +// successfully, or the error that resulted from the last attempted module resolution. |
| 163 | +export function resolveImportSpecifiers( |
| 164 | + importSpecifierList, |
| 165 | + resolveOptions, |
| 166 | + exportConditions, |
| 167 | + warn |
| 168 | +) { |
| 169 | + let promise = Promise.resolve(); |
| 170 | + |
| 171 | + for (let i = 0; i < importSpecifierList.length; i++) { |
| 172 | + // eslint-disable-next-line no-loop-func |
| 173 | + promise = promise.then(async (value) => { |
| 174 | + // if we've already resolved to something, just return it. |
| 175 | + if (value) { |
| 176 | + return value; |
| 177 | + } |
| 178 | + |
| 179 | + let result = await resolveId(importSpecifierList[i], resolveOptions, exportConditions, warn); |
| 180 | + if (!resolveOptions.preserveSymlinks) { |
| 181 | + if (await exists(result)) { |
| 182 | + result = await realpath(result); |
| 183 | + } |
| 184 | + } |
| 185 | + return result; |
| 186 | + }); |
| 187 | + |
| 188 | + // swallow MODULE_NOT_FOUND errors |
| 189 | + promise = promise.catch((error) => { |
| 190 | + if (error.code !== 'MODULE_NOT_FOUND') { |
| 191 | + throw error; |
| 192 | + } |
| 193 | + }); |
| 194 | + } |
| 195 | + |
| 196 | + return promise; |
| 197 | +} |
0 commit comments