resolver.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. 'use strict';
  2. // The Resolver is currently experimental and might be exposed to users in the future.
  3. const pa = require('path');
  4. const fs = require('fs');
  5. const {
  6. VMError
  7. } = require('./bridge');
  8. const { VMScript } = require('./script');
  9. // This should match. Note that '\', '%' are invalid characters
  10. // 1. name/.*
  11. // 2. @scope/name/.*
  12. const EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^/\\%]+)(\/.*)?$/;
  13. // See https://tc39.es/ecma262/#integer-index
  14. function isArrayIndex(key) {
  15. const keyNum = +key;
  16. if (`${keyNum}` !== key) return false;
  17. return keyNum >= 0 && keyNum < 0xFFFFFFFF;
  18. }
  19. class Resolver {
  20. constructor(builtinModules, globalPaths, hostRequire) {
  21. this.builtinModules = builtinModules;
  22. this.globalPaths = globalPaths;
  23. this.hostRequire = hostRequire;
  24. }
  25. init(vm) {
  26. }
  27. pathResolve(path) {
  28. return pa.resolve(path);
  29. }
  30. pathIsRelative(path) {
  31. if (path === '' || path[0] !== '.') return false;
  32. if (path.length === 1) return true;
  33. const idx = path[1] === '.' ? 2 : 1;
  34. if (path.length <= idx) return false;
  35. return path[idx] === '/' || path[idx] === pa.sep;
  36. }
  37. pathIsAbsolute(path) {
  38. return pa.isAbsolute(path);
  39. }
  40. pathConcat(...paths) {
  41. return pa.join(...paths);
  42. }
  43. pathBasename(path) {
  44. return pa.basename(path);
  45. }
  46. pathDirname(path) {
  47. return pa.dirname(path);
  48. }
  49. lookupPaths(mod, id) {
  50. if (typeof id === 'string') throw new Error('Id is not a string');
  51. if (this.pathIsRelative(id)) return [mod.path || '.'];
  52. return [...mod.paths, ...this.globalPaths];
  53. }
  54. getBuiltinModulesList() {
  55. return Object.getOwnPropertyNames(this.builtinModules);
  56. }
  57. loadBuiltinModule(vm, id) {
  58. const handler = this.builtinModules[id];
  59. return handler && handler(this, vm, id);
  60. }
  61. loadJS(vm, mod, filename) {
  62. throw new VMError(`Access denied to require '${filename}'`, 'EDENIED');
  63. }
  64. loadJSON(vm, mod, filename) {
  65. throw new VMError(`Access denied to require '${filename}'`, 'EDENIED');
  66. }
  67. loadNode(vm, mod, filename) {
  68. throw new VMError(`Access denied to require '${filename}'`, 'EDENIED');
  69. }
  70. registerModule(mod, filename, path, parent, direct) {
  71. }
  72. resolve(mod, x, options, ext, direct) {
  73. if (typeof x !== 'string') throw new Error('Id is not a string');
  74. if (x.startsWith('node:') || this.builtinModules[x]) {
  75. // a. return the core module
  76. // b. STOP
  77. return x;
  78. }
  79. return this.resolveFull(mod, x, options, ext, direct);
  80. }
  81. resolveFull(mod, x, options, ext, direct) {
  82. // 7. THROW "not found"
  83. throw new VMError(`Cannot find module '${x}'`, 'ENOTFOUND');
  84. }
  85. // NODE_MODULES_PATHS(START)
  86. genLookupPaths(path) {
  87. // 1. let PARTS = path split(START)
  88. // 2. let I = count of PARTS - 1
  89. // 3. let DIRS = []
  90. const dirs = [];
  91. // 4. while I >= 0,
  92. while (true) {
  93. const name = this.pathBasename(path);
  94. // a. if PARTS[I] = "node_modules" CONTINUE
  95. if (name !== 'node_modules') {
  96. // b. DIR = path join(PARTS[0 .. I] + "node_modules")
  97. // c. DIRS = DIR + DIRS // Note: this seems wrong. Should be DIRS + DIR
  98. dirs.push(this.pathConcat(path, 'node_modules'));
  99. }
  100. const dir = this.pathDirname(path);
  101. if (dir == path) break;
  102. // d. let I = I - 1
  103. path = dir;
  104. }
  105. return dirs;
  106. // This is done later on
  107. // 5. return DIRS + GLOBAL_FOLDERS
  108. }
  109. }
  110. class DefaultResolver extends Resolver {
  111. constructor(builtinModules, checkPath, globalPaths, pathContext, customResolver, hostRequire, compiler) {
  112. super(builtinModules, globalPaths, hostRequire);
  113. this.checkPath = checkPath;
  114. this.pathContext = pathContext;
  115. this.customResolver = customResolver;
  116. this.compiler = compiler;
  117. this.packageCache = {__proto__: null};
  118. this.scriptCache = {__proto__: null};
  119. }
  120. isPathAllowed(path) {
  121. return this.checkPath(path);
  122. }
  123. pathTestIsDirectory(path) {
  124. try {
  125. const stat = fs.statSync(path, {__proto__: null, throwIfNoEntry: false});
  126. return stat && stat.isDirectory();
  127. } catch (e) {
  128. return false;
  129. }
  130. }
  131. pathTestIsFile(path) {
  132. try {
  133. const stat = fs.statSync(path, {__proto__: null, throwIfNoEntry: false});
  134. return stat && stat.isFile();
  135. } catch (e) {
  136. return false;
  137. }
  138. }
  139. readFile(path) {
  140. return fs.readFileSync(path, {encoding: 'utf8'});
  141. }
  142. readFileWhenExists(path) {
  143. return this.pathTestIsFile(path) ? this.readFile(path) : undefined;
  144. }
  145. readScript(filename) {
  146. let script = this.scriptCache[filename];
  147. if (!script) {
  148. script = new VMScript(this.readFile(filename), {filename, compiler: this.compiler});
  149. this.scriptCache[filename] = script;
  150. }
  151. return script;
  152. }
  153. checkAccess(mod, filename) {
  154. if (!this.isPathAllowed(filename)) {
  155. throw new VMError(`Module '${filename}' is not allowed to be required. The path is outside the border!`, 'EDENIED');
  156. }
  157. }
  158. loadJS(vm, mod, filename) {
  159. filename = this.pathResolve(filename);
  160. this.checkAccess(mod, filename);
  161. if (this.pathContext(filename, 'js') === 'sandbox') {
  162. const script = this.readScript(filename);
  163. vm.run(script, {filename, strict: true, module: mod, wrapper: 'none', dirname: mod.path});
  164. } else {
  165. const m = this.hostRequire(filename);
  166. mod.exports = vm.readonly(m);
  167. }
  168. }
  169. loadJSON(vm, mod, filename) {
  170. filename = this.pathResolve(filename);
  171. this.checkAccess(mod, filename);
  172. const json = this.readFile(filename);
  173. mod.exports = vm._jsonParse(json);
  174. }
  175. loadNode(vm, mod, filename) {
  176. filename = this.pathResolve(filename);
  177. this.checkAccess(mod, filename);
  178. if (this.pathContext(filename, 'node') === 'sandbox') throw new VMError('Native modules can be required only with context set to \'host\'.');
  179. const m = this.hostRequire(filename);
  180. mod.exports = vm.readonly(m);
  181. }
  182. // require(X) from module at path Y
  183. resolveFull(mod, x, options, ext, direct) {
  184. // Note: core module handled by caller
  185. const extList = Object.getOwnPropertyNames(ext);
  186. const path = mod.path || '.';
  187. // 5. LOAD_PACKAGE_SELF(X, dirname(Y))
  188. let f = this.loadPackageSelf(x, path, extList);
  189. if (f) return f;
  190. // 4. If X begins with '#'
  191. if (x[0] === '#') {
  192. // a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))
  193. f = this.loadPackageImports(x, path, extList);
  194. if (f) return f;
  195. }
  196. // 2. If X begins with '/'
  197. if (this.pathIsAbsolute(x)) {
  198. // a. set Y to be the filesystem root
  199. f = this.loadAsFileOrDirecotry(x, extList);
  200. if (f) return f;
  201. // c. THROW "not found"
  202. throw new VMError(`Cannot find module '${x}'`, 'ENOTFOUND');
  203. // 3. If X begins with './' or '/' or '../'
  204. } else if (this.pathIsRelative(x)) {
  205. if (typeof options === 'object' && options !== null) {
  206. const paths = options.paths;
  207. if (Array.isArray(paths)) {
  208. for (let i = 0; i < paths.length; i++) {
  209. // a. LOAD_AS_FILE(Y + X)
  210. // b. LOAD_AS_DIRECTORY(Y + X)
  211. f = this.loadAsFileOrDirecotry(this.pathConcat(paths[i], x), extList);
  212. if (f) return f;
  213. }
  214. } else if (paths === undefined) {
  215. // a. LOAD_AS_FILE(Y + X)
  216. // b. LOAD_AS_DIRECTORY(Y + X)
  217. f = this.loadAsFileOrDirecotry(this.pathConcat(path, x), extList);
  218. if (f) return f;
  219. } else {
  220. throw new VMError('Invalid options.paths option.');
  221. }
  222. } else {
  223. // a. LOAD_AS_FILE(Y + X)
  224. // b. LOAD_AS_DIRECTORY(Y + X)
  225. f = this.loadAsFileOrDirecotry(this.pathConcat(path, x), extList);
  226. if (f) return f;
  227. }
  228. // c. THROW "not found"
  229. throw new VMError(`Cannot find module '${x}'`, 'ENOTFOUND');
  230. }
  231. let dirs;
  232. if (typeof options === 'object' && options !== null) {
  233. const paths = options.paths;
  234. if (Array.isArray(paths)) {
  235. dirs = [];
  236. for (let i = 0; i < paths.length; i++) {
  237. const lookups = this.genLookupPaths(paths[i]);
  238. for (let j = 0; j < lookups.length; j++) {
  239. if (!dirs.includes(lookups[j])) dirs.push(lookups[j]);
  240. }
  241. if (i === 0) {
  242. const globalPaths = this.globalPaths;
  243. for (let j = 0; j < globalPaths.length; j++) {
  244. if (!dirs.includes(globalPaths[j])) dirs.push(globalPaths[j]);
  245. }
  246. }
  247. }
  248. } else if (paths === undefined) {
  249. dirs = [...mod.paths, ...this.globalPaths];
  250. } else {
  251. throw new VMError('Invalid options.paths option.');
  252. }
  253. } else {
  254. dirs = [...mod.paths, ...this.globalPaths];
  255. }
  256. // 6. LOAD_NODE_MODULES(X, dirname(Y))
  257. f = this.loadNodeModules(x, dirs, extList);
  258. if (f) return f;
  259. f = this.customResolver(this, x, path, extList);
  260. if (f) return f;
  261. return super.resolveFull(mod, x, options, ext, direct);
  262. }
  263. loadAsFileOrDirecotry(x, extList) {
  264. // a. LOAD_AS_FILE(X)
  265. const f = this.loadAsFile(x, extList);
  266. if (f) return f;
  267. // b. LOAD_AS_DIRECTORY(X)
  268. return this.loadAsDirectory(x, extList);
  269. }
  270. tryFile(x) {
  271. x = this.pathResolve(x);
  272. return this.isPathAllowed(x) && this.pathTestIsFile(x) ? x : undefined;
  273. }
  274. tryWithExtension(x, extList) {
  275. for (let i = 0; i < extList.length; i++) {
  276. const ext = extList[i];
  277. if (ext !== this.pathBasename(ext)) continue;
  278. const f = this.tryFile(x + ext);
  279. if (f) return f;
  280. }
  281. return undefined;
  282. }
  283. readPackage(path) {
  284. const packagePath = this.pathResolve(this.pathConcat(path, 'package.json'));
  285. const cache = this.packageCache[packagePath];
  286. if (cache !== undefined) return cache;
  287. if (!this.isPathAllowed(packagePath)) return undefined;
  288. const content = this.readFileWhenExists(packagePath);
  289. if (!content) {
  290. this.packageCache[packagePath] = false;
  291. return false;
  292. }
  293. let parsed;
  294. try {
  295. parsed = JSON.parse(content);
  296. } catch (e) {
  297. e.path = packagePath;
  298. e.message = 'Error parsing ' + packagePath + ': ' + e.message;
  299. throw e;
  300. }
  301. const filtered = {
  302. name: parsed.name,
  303. main: parsed.main,
  304. exports: parsed.exports,
  305. imports: parsed.imports,
  306. type: parsed.type
  307. };
  308. this.packageCache[packagePath] = filtered;
  309. return filtered;
  310. }
  311. readPackageScope(path) {
  312. while (true) {
  313. const dir = this.pathDirname(path);
  314. if (dir === path) break;
  315. const basename = this.pathBasename(dir);
  316. if (basename === 'node_modules') break;
  317. const pack = this.readPackage(dir);
  318. if (pack) return {data: pack, scope: dir};
  319. path = dir;
  320. }
  321. return {data: undefined, scope: undefined};
  322. }
  323. // LOAD_AS_FILE(X)
  324. loadAsFile(x, extList) {
  325. // 1. If X is a file, load X as its file extension format. STOP
  326. const f = this.tryFile(x);
  327. if (f) return f;
  328. // 2. If X.js is a file, load X.js as JavaScript text. STOP
  329. // 3. If X.json is a file, parse X.json to a JavaScript Object. STOP
  330. // 4. If X.node is a file, load X.node as binary addon. STOP
  331. return this.tryWithExtension(x, extList);
  332. }
  333. // LOAD_INDEX(X)
  334. loadIndex(x, extList) {
  335. // 1. If X/index.js is a file, load X/index.js as JavaScript text. STOP
  336. // 2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
  337. // 3. If X/index.node is a file, load X/index.node as binary addon. STOP
  338. return this.tryWithExtension(this.pathConcat(x, 'index'), extList);
  339. }
  340. // LOAD_AS_DIRECTORY(X)
  341. loadAsPackage(x, pack, extList) {
  342. // 1. If X/package.json is a file,
  343. // already done.
  344. if (pack) {
  345. // a. Parse X/package.json, and look for "main" field.
  346. // b. If "main" is a falsy value, GOTO 2.
  347. if (typeof pack.main === 'string') {
  348. // c. let M = X + (json main field)
  349. const m = this.pathConcat(x, pack.main);
  350. // d. LOAD_AS_FILE(M)
  351. let f = this.loadAsFile(m, extList);
  352. if (f) return f;
  353. // e. LOAD_INDEX(M)
  354. f = this.loadIndex(m, extList);
  355. if (f) return f;
  356. // f. LOAD_INDEX(X) DEPRECATED
  357. f = this.loadIndex(x, extList);
  358. if (f) return f;
  359. // g. THROW "not found"
  360. throw new VMError(`Cannot find module '${x}'`, 'ENOTFOUND');
  361. }
  362. }
  363. // 2. LOAD_INDEX(X)
  364. return this.loadIndex(x, extList);
  365. }
  366. // LOAD_AS_DIRECTORY(X)
  367. loadAsDirectory(x, extList) {
  368. // 1. If X/package.json is a file,
  369. const pack = this.readPackage(x);
  370. return this.loadAsPackage(x, pack, extList);
  371. }
  372. // LOAD_NODE_MODULES(X, START)
  373. loadNodeModules(x, dirs, extList) {
  374. // 1. let DIRS = NODE_MODULES_PATHS(START)
  375. // This step is already done.
  376. // 2. for each DIR in DIRS:
  377. for (let i = 0; i < dirs.length; i++) {
  378. const dir = dirs[i];
  379. // a. LOAD_PACKAGE_EXPORTS(X, DIR)
  380. let f = this.loadPackageExports(x, dir, extList);
  381. if (f) return f;
  382. // b. LOAD_AS_FILE(DIR/X)
  383. f = this.loadAsFile(dir + '/' + x, extList);
  384. if (f) return f;
  385. // c. LOAD_AS_DIRECTORY(DIR/X)
  386. f = this.loadAsDirectory(dir + '/' + x, extList);
  387. if (f) return f;
  388. }
  389. return undefined;
  390. }
  391. // LOAD_PACKAGE_IMPORTS(X, DIR)
  392. loadPackageImports(x, dir, extList) {
  393. // 1. Find the closest package scope SCOPE to DIR.
  394. const {data, scope} = this.readPackageScope(dir);
  395. // 2. If no scope was found, return.
  396. if (!data) return undefined;
  397. // 3. If the SCOPE/package.json "imports" is null or undefined, return.
  398. if (typeof data.imports !== 'object' || data.imports === null || Array.isArray(data.imports)) return undefined;
  399. // 4. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),
  400. // ["node", "require"]) defined in the ESM resolver.
  401. // PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)
  402. // 1. Assert: specifier begins with "#".
  403. // 2. If specifier is exactly equal to "#" or starts with "#/", then
  404. if (x === '#' || x.startsWith('#/')) {
  405. // a. Throw an Invalid Module Specifier error.
  406. throw new VMError(`Invalid module specifier '${x}'`, 'ERR_INVALID_MODULE_SPECIFIER');
  407. }
  408. // 3. Let packageURL be the result of LOOKUP_PACKAGE_SCOPE(parentURL).
  409. // Note: packageURL === parentURL === scope
  410. // 4. If packageURL is not null, then
  411. // Always true
  412. // a. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
  413. // pjson === data
  414. // b. If pjson.imports is a non-null Object, then
  415. // Already tested
  416. // x. Let resolved be the result of PACKAGE_IMPORTS_EXPORTS_RESOLVE( specifier, pjson.imports, packageURL, true, conditions).
  417. const match = this.packageImportsExportsResolve(x, data.imports, scope, true, ['node', 'require'], extList);
  418. // y. If resolved is not null or undefined, return resolved.
  419. if (!match) {
  420. // 5. Throw a Package Import Not Defined error.
  421. throw new VMError(`Package import not defined for '${x}'`, 'ERR_PACKAGE_IMPORT_NOT_DEFINED');
  422. }
  423. // END PACKAGE_IMPORTS_RESOLVE
  424. // 5. RESOLVE_ESM_MATCH(MATCH).
  425. return this.resolveEsmMatch(match, x, extList);
  426. }
  427. // LOAD_PACKAGE_EXPORTS(X, DIR)
  428. loadPackageExports(x, dir, extList) {
  429. // 1. Try to interpret X as a combination of NAME and SUBPATH where the name
  430. // may have a @scope/ prefix and the subpath begins with a slash (`/`).
  431. const res = x.match(EXPORTS_PATTERN);
  432. // 2. If X does not match this pattern or DIR/NAME/package.json is not a file,
  433. // return.
  434. if (!res) return undefined;
  435. const scope = this.pathConcat(dir, res[1]);
  436. const pack = this.readPackage(scope);
  437. if (!pack) return undefined;
  438. // 3. Parse DIR/NAME/package.json, and look for "exports" field.
  439. // 4. If "exports" is null or undefined, return.
  440. if (!pack.exports) return undefined;
  441. // 5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH,
  442. // `package.json` "exports", ["node", "require"]) defined in the ESM resolver.
  443. const match = this.packageExportsResolve(scope, '.' + (res[2] || ''), pack.exports, ['node', 'require'], extList);
  444. // 6. RESOLVE_ESM_MATCH(MATCH)
  445. return this.resolveEsmMatch(match, x, extList);
  446. }
  447. // LOAD_PACKAGE_SELF(X, DIR)
  448. loadPackageSelf(x, dir, extList) {
  449. // 1. Find the closest package scope SCOPE to DIR.
  450. const {data, scope} = this.readPackageScope(dir);
  451. // 2. If no scope was found, return.
  452. if (!data) return undefined;
  453. // 3. If the SCOPE/package.json "exports" is null or undefined, return.
  454. if (!data.exports) return undefined;
  455. // 4. If the SCOPE/package.json "name" is not the first segment of X, return.
  456. if (x !== data.name && !x.startsWith(data.name + '/')) return undefined;
  457. // 5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),
  458. // "." + X.slice("name".length), `package.json` "exports", ["node", "require"])
  459. // defined in the ESM resolver.
  460. const match = this.packageExportsResolve(scope, '.' + x.slice(data.name.length), data.exports, ['node', 'require'], extList);
  461. // 6. RESOLVE_ESM_MATCH(MATCH)
  462. return this.resolveEsmMatch(match, x, extList);
  463. }
  464. // RESOLVE_ESM_MATCH(MATCH)
  465. resolveEsmMatch(match, x, extList) {
  466. // 1. let { RESOLVED, EXACT } = MATCH
  467. const resolved = match;
  468. const exact = true;
  469. // 2. let RESOLVED_PATH = fileURLToPath(RESOLVED)
  470. const resolvedPath = resolved;
  471. let f;
  472. // 3. If EXACT is true,
  473. if (exact) {
  474. // a. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension
  475. // format. STOP
  476. f = this.tryFile(resolvedPath);
  477. // 4. Otherwise, if EXACT is false,
  478. } else {
  479. // a. LOAD_AS_FILE(RESOLVED_PATH)
  480. // b. LOAD_AS_DIRECTORY(RESOLVED_PATH)
  481. f = this.loadAsFileOrDirecotry(resolvedPath, extList);
  482. }
  483. if (f) return f;
  484. // 5. THROW "not found"
  485. throw new VMError(`Cannot find module '${x}'`, 'ENOTFOUND');
  486. }
  487. // PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)
  488. packageExportsResolve(packageURL, subpath, rexports, conditions, extList) {
  489. // 1. If exports is an Object with both a key starting with "." and a key not starting with ".", throw an Invalid Package Configuration error.
  490. let hasDots = false;
  491. if (typeof rexports === 'object' && !Array.isArray(rexports)) {
  492. const keys = Object.getOwnPropertyNames(rexports);
  493. if (keys.length > 0) {
  494. hasDots = keys[0][0] === '.';
  495. for (let i = 0; i < keys.length; i++) {
  496. if (hasDots !== (keys[i][0] === '.')) {
  497. throw new VMError('Invalid package configuration', 'ERR_INVALID_PACKAGE_CONFIGURATION');
  498. }
  499. }
  500. }
  501. }
  502. // 2. If subpath is equal to ".", then
  503. if (subpath === '.') {
  504. // a. Let mainExport be undefined.
  505. let mainExport = undefined;
  506. // b. If exports is a String or Array, or an Object containing no keys starting with ".", then
  507. if (typeof rexports === 'string' || Array.isArray(rexports) || !hasDots) {
  508. // x. Set mainExport to exports.
  509. mainExport = rexports;
  510. // c. Otherwise if exports is an Object containing a "." property, then
  511. } else if (hasDots) {
  512. // x. Set mainExport to exports["."].
  513. mainExport = rexports['.'];
  514. }
  515. // d. If mainExport is not undefined, then
  516. if (mainExport) {
  517. // x. Let resolved be the result of PACKAGE_TARGET_RESOLVE( packageURL, mainExport, "", false, false, conditions).
  518. const resolved = this.packageTargetResolve(packageURL, mainExport, '', false, false, conditions, extList);
  519. // y. If resolved is not null or undefined, return resolved.
  520. if (resolved) return resolved;
  521. }
  522. // 3. Otherwise, if exports is an Object and all keys of exports start with ".", then
  523. } else if (hasDots) {
  524. // a. Let matchKey be the string "./" concatenated with subpath.
  525. // Note: Here subpath starts already with './'
  526. // b. Let resolved be the result of PACKAGE_IMPORTS_EXPORTS_RESOLVE( matchKey, exports, packageURL, false, conditions).
  527. const resolved = this.packageImportsExportsResolve(subpath, rexports, packageURL, false, conditions, extList);
  528. // c. If resolved is not null or undefined, return resolved.
  529. if (resolved) return resolved;
  530. }
  531. // 4. Throw a Package Path Not Exported error.
  532. throw new VMError(`Package path '${subpath}' is not exported`, 'ERR_PACKAGE_PATH_NOT_EXPORTED');
  533. }
  534. // PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL, isImports, conditions)
  535. packageImportsExportsResolve(matchKey, matchObj, packageURL, isImports, conditions, extList) {
  536. // 1. If matchKey is a key of matchObj and does not contain "*", then
  537. let target = matchObj[matchKey];
  538. if (target && matchKey.indexOf('*') === -1) {
  539. // a. Let target be the value of matchObj[matchKey].
  540. // b. Return the result of PACKAGE_TARGET_RESOLVE(packageURL, target, "", false, isImports, conditions).
  541. return this.packageTargetResolve(packageURL, target, '', false, isImports, conditions, extList);
  542. }
  543. // 2. Let expansionKeys be the list of keys of matchObj containing only a single "*",
  544. // sorted by the sorting function PATTERN_KEY_COMPARE which orders in descending order of specificity.
  545. const expansionKeys = Object.getOwnPropertyNames(matchObj);
  546. let bestKey = '';
  547. let bestSubpath;
  548. // 3. For each key expansionKey in expansionKeys, do
  549. for (let i = 0; i < expansionKeys.length; i++) {
  550. const expansionKey = expansionKeys[i];
  551. if (matchKey.length < expansionKey.length) continue;
  552. // a. Let patternBase be the substring of expansionKey up to but excluding the first "*" character.
  553. const star = expansionKey.indexOf('*');
  554. if (star === -1) continue; // Note: expansionKeys was not filtered
  555. const patternBase = expansionKey.slice(0, star);
  556. // b. If matchKey starts with but is not equal to patternBase, then
  557. if (matchKey.startsWith(patternBase) && expansionKey.indexOf('*', star + 1) === -1) { // Note: expansionKeys was not filtered
  558. // 1. Let patternTrailer be the substring of expansionKey from the index after the first "*" character.
  559. const patternTrailer = expansionKey.slice(star + 1);
  560. // 2. If patternTrailer has zero length, or if matchKey ends with patternTrailer and the length of matchKey is greater than or
  561. // equal to the length of expansionKey, then
  562. if (matchKey.endsWith(patternTrailer) && this.patternKeyCompare(bestKey, expansionKey) === 1) { // Note: expansionKeys was not sorted
  563. // a. Let target be the value of matchObj[expansionKey].
  564. target = matchObj[expansionKey];
  565. // b. Let subpath be the substring of matchKey starting at the index of the length of patternBase up to the length of
  566. // matchKey minus the length of patternTrailer.
  567. bestKey = expansionKey;
  568. bestSubpath = matchKey.slice(patternBase.length, matchKey.length - patternTrailer.length);
  569. }
  570. }
  571. }
  572. if (bestSubpath) { // Note: expansionKeys was not sorted
  573. // c. Return the result of PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, true, isImports, conditions).
  574. return this.packageTargetResolve(packageURL, target, bestSubpath, true, isImports, conditions, extList);
  575. }
  576. // 4. Return null.
  577. return null;
  578. }
  579. // PATTERN_KEY_COMPARE(keyA, keyB)
  580. patternKeyCompare(keyA, keyB) {
  581. // 1. Assert: keyA ends with "/" or contains only a single "*".
  582. // 2. Assert: keyB ends with "/" or contains only a single "*".
  583. // 3. Let baseLengthA be the index of "*" in keyA plus one, if keyA contains "*", or the length of keyA otherwise.
  584. const baseAStar = keyA.indexOf('*');
  585. const baseLengthA = baseAStar === -1 ? keyA.length : baseAStar + 1;
  586. // 4. Let baseLengthB be the index of "*" in keyB plus one, if keyB contains "*", or the length of keyB otherwise.
  587. const baseBStar = keyB.indexOf('*');
  588. const baseLengthB = baseBStar === -1 ? keyB.length : baseBStar + 1;
  589. // 5. If baseLengthA is greater than baseLengthB, return -1.
  590. if (baseLengthA > baseLengthB) return -1;
  591. // 6. If baseLengthB is greater than baseLengthA, return 1.
  592. if (baseLengthB > baseLengthA) return 1;
  593. // 7. If keyA does not contain "*", return 1.
  594. if (baseAStar === -1) return 1;
  595. // 8. If keyB does not contain "*", return -1.
  596. if (baseBStar === -1) return -1;
  597. // 9. If the length of keyA is greater than the length of keyB, return -1.
  598. if (keyA.length > keyB.length) return -1;
  599. // 10. If the length of keyB is greater than the length of keyA, return 1.
  600. if (keyB.length > keyA.length) return 1;
  601. // 11. Return 0.
  602. return 0;
  603. }
  604. // PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, pattern, internal, conditions)
  605. packageTargetResolve(packageURL, target, subpath, pattern, internal, conditions, extList) {
  606. // 1. If target is a String, then
  607. if (typeof target === 'string') {
  608. // a. If pattern is false, subpath has non-zero length and target does not end with "/", throw an Invalid Module Specifier error.
  609. if (!pattern && subpath.length > 0 && !target.endsWith('/')) {
  610. throw new VMError(`Invalid package specifier '${subpath}'`, 'ERR_INVALID_MODULE_SPECIFIER');
  611. }
  612. // b. If target does not start with "./", then
  613. if (!target.startsWith('./')) {
  614. // 1. If internal is true and target does not start with "../" or "/" and is not a valid URL, then
  615. if (internal && !target.startsWith('../') && !target.startsWith('/')) {
  616. let isURL = false;
  617. try {
  618. // eslint-disable-next-line no-new
  619. new URL(target);
  620. isURL = true;
  621. } catch (e) {}
  622. if (!isURL) {
  623. // a. If pattern is true, then
  624. if (pattern) {
  625. // 1. Return PACKAGE_RESOLVE(target with every instance of "*" replaced by subpath, packageURL + "/").
  626. return this.packageResolve(target.replace(/\*/g, subpath), packageURL, conditions, extList);
  627. }
  628. // b. Return PACKAGE_RESOLVE(target + subpath, packageURL + "/").
  629. return this.packageResolve(this.pathConcat(target, subpath), packageURL, conditions, extList);
  630. }
  631. }
  632. // Otherwise, throw an Invalid Package Target error.
  633. throw new VMError(`Invalid package target for '${subpath}'`, 'ERR_INVALID_PACKAGE_TARGET');
  634. }
  635. target = decodeURI(target);
  636. // c. If target split on "/" or "\" contains any ".", ".." or "node_modules" segments after the first segment, case insensitive
  637. // and including percent encoded variants, throw an Invalid Package Target error.
  638. if (target.split(/[/\\]/).slice(1).findIndex(x => x === '.' || x === '..' || x.toLowerCase() === 'node_modules') !== -1) {
  639. throw new VMError(`Invalid package target for '${subpath}'`, 'ERR_INVALID_PACKAGE_TARGET');
  640. }
  641. // d. Let resolvedTarget be the URL resolution of the concatenation of packageURL and target.
  642. const resolvedTarget = this.pathConcat(packageURL, target);
  643. // e. Assert: resolvedTarget is contained in packageURL.
  644. subpath = decodeURI(subpath);
  645. // f. If subpath split on "/" or "\" contains any ".", ".." or "node_modules" segments, case insensitive and including percent
  646. // encoded variants, throw an Invalid Module Specifier error.
  647. if (subpath.split(/[/\\]/).findIndex(x => x === '.' || x === '..' || x.toLowerCase() === 'node_modules') !== -1) {
  648. throw new VMError(`Invalid package specifier '${subpath}'`, 'ERR_INVALID_MODULE_SPECIFIER');
  649. }
  650. // g. If pattern is true, then
  651. if (pattern) {
  652. // 1. Return the URL resolution of resolvedTarget with every instance of "*" replaced with subpath.
  653. return resolvedTarget.replace(/\*/g, subpath);
  654. }
  655. // h. Otherwise,
  656. // 1. Return the URL resolution of the concatenation of subpath and resolvedTarget.
  657. return this.pathConcat(resolvedTarget, subpath);
  658. // 3. Otherwise, if target is an Array, then
  659. } else if (Array.isArray(target)) {
  660. // a. If target.length is zero, return null.
  661. if (target.length === 0) return null;
  662. let lastException = undefined;
  663. // b. For each item targetValue in target, do
  664. for (let i = 0; i < target.length; i++) {
  665. const targetValue = target[i];
  666. // 1. Let resolved be the result of PACKAGE_TARGET_RESOLVE( packageURL, targetValue, subpath, pattern, internal, conditions),
  667. // continuing the loop on any Invalid Package Target error.
  668. let resolved;
  669. try {
  670. resolved = this.packageTargetResolve(packageURL, targetValue, subpath, pattern, internal, conditions, extList);
  671. } catch (e) {
  672. if (e.code !== 'ERR_INVALID_PACKAGE_TARGET') throw e;
  673. lastException = e;
  674. continue;
  675. }
  676. // 2. If resolved is undefined, continue the loop.
  677. // 3. Return resolved.
  678. if (resolved !== undefined) return resolved;
  679. if (resolved === null) {
  680. lastException = null;
  681. }
  682. }
  683. // c. Return or throw the last fallback resolution null return or error.
  684. if (lastException === undefined || lastException === null) return lastException;
  685. throw lastException;
  686. // 2. Otherwise, if target is a non-null Object, then
  687. } else if (typeof target === 'object' && target !== null) {
  688. const keys = Object.getOwnPropertyNames(target);
  689. // a. If exports contains any index property keys, as defined in ECMA-262 6.1.7 Array Index, throw an Invalid Package Configuration error.
  690. for (let i = 0; i < keys.length; i++) {
  691. const p = keys[i];
  692. if (isArrayIndex(p)) throw new VMError(`Invalid package configuration for '${subpath}'`, 'ERR_INVALID_PACKAGE_CONFIGURATION');
  693. }
  694. // b. For each property p of target, in object insertion order as,
  695. for (let i = 0; i < keys.length; i++) {
  696. const p = keys[i];
  697. // 1. If p equals "default" or conditions contains an entry for p, then
  698. if (p === 'default' || conditions.includes(p)) {
  699. // a. Let targetValue be the value of the p property in target.
  700. const targetValue = target[p];
  701. // b. Let resolved be the result of PACKAGE_TARGET_RESOLVE( packageURL, targetValue, subpath, pattern, internal, conditions).
  702. const resolved = this.packageTargetResolve(packageURL, targetValue, subpath, pattern, internal, conditions, extList);
  703. // c. If resolved is equal to undefined, continue the loop.
  704. // d. Return resolved.
  705. if (resolved !== undefined) return resolved;
  706. }
  707. }
  708. // c. Return undefined.
  709. return undefined;
  710. // 4. Otherwise, if target is null, return null.
  711. } else if (target == null) {
  712. return null;
  713. }
  714. // Otherwise throw an Invalid Package Target error.
  715. throw new VMError(`Invalid package target for '${subpath}'`, 'ERR_INVALID_PACKAGE_TARGET');
  716. }
  717. // PACKAGE_RESOLVE(packageSpecifier, parentURL)
  718. packageResolve(packageSpecifier, parentURL, conditions, extList) {
  719. // 1. Let packageName be undefined.
  720. let packageName = undefined;
  721. // 2. If packageSpecifier is an empty string, then
  722. if (packageSpecifier === '') {
  723. // a. Throw an Invalid Module Specifier error.
  724. throw new VMError(`Invalid package specifier '${packageSpecifier}'`, 'ERR_INVALID_MODULE_SPECIFIER');
  725. }
  726. // 3. If packageSpecifier is a Node.js builtin module name, then
  727. if (this.builtinModules[packageSpecifier]) {
  728. // a. Return the string "node:" concatenated with packageSpecifier.
  729. return 'node:' + packageSpecifier;
  730. }
  731. let idx = packageSpecifier.indexOf('/');
  732. // 5. Otherwise,
  733. if (packageSpecifier[0] === '@') {
  734. // a. If packageSpecifier does not contain a "/" separator, then
  735. if (idx === -1) {
  736. // x. Throw an Invalid Module Specifier error.
  737. throw new VMError(`Invalid package specifier '${packageSpecifier}'`, 'ERR_INVALID_MODULE_SPECIFIER');
  738. }
  739. // b. Set packageName to the substring of packageSpecifier until the second "/" separator or the end of the string.
  740. idx = packageSpecifier.indexOf('/', idx + 1);
  741. }
  742. // else
  743. // 4. If packageSpecifier does not start with "@", then
  744. // a. Set packageName to the substring of packageSpecifier until the first "/" separator or the end of the string.
  745. packageName = idx === -1 ? packageSpecifier : packageSpecifier.slice(0, idx);
  746. // 6. If packageName starts with "." or contains "\" or "%", then
  747. if (idx !== 0 && (packageName[0] === '.' || packageName.indexOf('\\') >= 0 || packageName.indexOf('%') >= 0)) {
  748. // a. Throw an Invalid Module Specifier error.
  749. throw new VMError(`Invalid package specifier '${packageSpecifier}'`, 'ERR_INVALID_MODULE_SPECIFIER');
  750. }
  751. // 7. Let packageSubpath be "." concatenated with the substring of packageSpecifier from the position at the length of packageName.
  752. const packageSubpath = '.' + packageSpecifier.slice(packageName.length);
  753. // 8. If packageSubpath ends in "/", then
  754. if (packageSubpath[packageSubpath.length - 1] === '/') {
  755. // a. Throw an Invalid Module Specifier error.
  756. throw new VMError(`Invalid package specifier '${packageSpecifier}'`, 'ERR_INVALID_MODULE_SPECIFIER');
  757. }
  758. // 9. Let selfUrl be the result of PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).
  759. const selfUrl = this.packageSelfResolve(packageName, packageSubpath, parentURL);
  760. // 10. If selfUrl is not undefined, return selfUrl.
  761. if (selfUrl) return selfUrl;
  762. // 11. While parentURL is not the file system root,
  763. let packageURL;
  764. while (true) {
  765. // a. Let packageURL be the URL resolution of "node_modules/" concatenated with packageSpecifier, relative to parentURL.
  766. packageURL = this.pathResolve(this.pathConcat(parentURL, 'node_modules', packageSpecifier));
  767. // b. Set parentURL to the parent folder URL of parentURL.
  768. const parentParentURL = this.pathDirname(parentURL);
  769. // c. If the folder at packageURL does not exist, then
  770. if (this.isPathAllowed(packageURL) && this.pathTestIsDirectory(packageURL)) break;
  771. // 1. Continue the next loop iteration.
  772. if (parentParentURL === parentURL) {
  773. // 12. Throw a Module Not Found error.
  774. throw new VMError(`Cannot find module '${packageSpecifier}'`, 'ENOTFOUND');
  775. }
  776. parentURL = parentParentURL;
  777. }
  778. // d. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
  779. const pack = this.readPackage(packageURL);
  780. // e. If pjson is not null and pjson.exports is not null or undefined, then
  781. if (pack && pack.exports) {
  782. // 1. Return the result of PACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath, pjson.exports, defaultConditions).
  783. return this.packageExportsResolve(packageURL, packageSubpath, pack.exports, conditions, extList);
  784. }
  785. // f. Otherwise, if packageSubpath is equal to ".", then
  786. if (packageSubpath === '.') {
  787. // 1. If pjson.main is a string, then
  788. // a. Return the URL resolution of main in packageURL.
  789. return this.loadAsPackage(packageSubpath, pack, extList);
  790. }
  791. // g. Otherwise,
  792. // 1. Return the URL resolution of packageSubpath in packageURL.
  793. return this.pathConcat(packageURL, packageSubpath);
  794. }
  795. }
  796. exports.Resolver = Resolver;
  797. exports.DefaultResolver = DefaultResolver;