1'use strict'; 2 3const { 4 StringPrototypeEndsWith, 5} = primordials; 6const { URL, fileURLToPath } = require('internal/url'); 7const packageJsonReader = require('internal/modules/package_json_reader'); 8 9/** 10 * @typedef {object} PackageConfig 11 * @property {string} pjsonPath - The path to the package.json file. 12 * @property {boolean} exists - Whether the package.json file exists. 13 * @property {'none' | 'commonjs' | 'module'} type - The type of the package. 14 * @property {string} [name] - The name of the package. 15 * @property {string} [main] - The main entry point of the package. 16 * @property {PackageTarget} [exports] - The exports configuration of the package. 17 * @property {Record<string, string | Record<string, string>>} [imports] - The imports configuration of the package. 18 */ 19/** 20 * @typedef {string | string[] | Record<string, string | Record<string, string>>} PackageTarget 21 */ 22 23/** 24 * Returns the package configuration for the given resolved URL. 25 * @param {URL | string} resolved - The resolved URL. 26 * @returns {PackageConfig} - The package configuration. 27 */ 28function getPackageScopeConfig(resolved) { 29 let packageJSONUrl = new URL('./package.json', resolved); 30 while (true) { 31 const packageJSONPath = packageJSONUrl.pathname; 32 if (StringPrototypeEndsWith(packageJSONPath, 'node_modules/package.json')) { 33 break; 34 } 35 const packageConfig = packageJsonReader.read(fileURLToPath(packageJSONUrl), { 36 __proto__: null, 37 specifier: resolved, 38 isESM: true, 39 }); 40 if (packageConfig.exists) { 41 return packageConfig; 42 } 43 44 const lastPackageJSONUrl = packageJSONUrl; 45 packageJSONUrl = new URL('../package.json', packageJSONUrl); 46 47 // Terminates at root where ../package.json equals ../../package.json 48 // (can't just check "/package.json" for Windows support). 49 if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) { 50 break; 51 } 52 } 53 const packageJSONPath = fileURLToPath(packageJSONUrl); 54 return { 55 __proto__: null, 56 pjsonPath: packageJSONPath, 57 exists: false, 58 main: undefined, 59 name: undefined, 60 type: 'none', 61 exports: undefined, 62 imports: undefined, 63 }; 64} 65 66 67module.exports = { 68 getPackageScopeConfig, 69}; 70