MCPcopy Index your code
hub / github.com/nodejs/node / resolveAsCommonJS

Function resolveAsCommonJS

lib/internal/modules/esm/resolve.js:888–936  ·  view source on GitHub ↗

* Try to resolve an import as a CommonJS module. * @param {string} specifier - The specifier to resolve. * @param {string} parentURL - The base URL. * @returns {string | Buffer | false}

(specifier, parentURL)

Source from the content-addressed store, hash-verified

886 * @returns {string | Buffer | false}
887 */
888function resolveAsCommonJS(specifier, parentURL) {
889 try {
890 const { Module: CJSModule } = require('internal/modules/cjs/loader');
891 const parent = fileURLToPath(parentURL);
892 const tmpModule = new CJSModule(parent, null);
893 tmpModule.paths = CJSModule._nodeModulePaths(parent);
894
895 let found = CJSModule._resolveFilename(specifier, tmpModule, false);
896
897 // If it is a relative specifier return the relative path
898 // to the parent
899 if (isRelativeSpecifier(specifier)) {
900 const foundURL = pathToFileURL(found).pathname;
901 found = relativePosixPath(
902 StringPrototypeSlice(parentURL, 'file://'.length, StringPrototypeLastIndexOf(parentURL, '/')),
903 foundURL);
904
905 // Add './' if the path does not start with '../'
906 // This should be a safe assumption because when loading
907 // esm modules there should be always a file specified so
908 // there should not be a specifier like '..' or '.'
909 if (!StringPrototypeStartsWith(found, '../')) {
910 found = `./${found}`;
911 }
912 } else if (isBareSpecifier(specifier)) {
913 // If it is a bare specifier return the relative path within the
914 // module
915 const i = StringPrototypeIndexOf(specifier, '/');
916 const pkg = i === -1 ? specifier : StringPrototypeSlice(specifier, 0, i);
917 const needle = `${sep}node_modules${sep}${pkg}${sep}`;
918 const index = StringPrototypeLastIndexOf(found, needle);
919 if (index !== -1) {
920 found = pkg + '/' + ArrayPrototypeJoin(
921 ArrayPrototypeMap(
922 StringPrototypeSplit(StringPrototypeSlice(found, index + needle.length), sep),
923 // Escape URL-special characters to avoid generating a incorrect suggestion
924 encodeURIComponent,
925 ),
926 '/',
927 );
928 } else {
929 found = `${pathToFileURL(found)}`;
930 }
931 }
932 return found;
933 } catch {
934 return false;
935 }
936}
937
938/**
939 * Validate user-input in `context` supplied by a custom loader.

Callers 1

Calls 5

fileURLToPathFunction · 0.85
isRelativeSpecifierFunction · 0.85
isBareSpecifierFunction · 0.85
requireFunction · 0.50
pathToFileURLFunction · 0.50

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…